open-pstack 0.9.174 → 0.9.175

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +1 -1
  2. package/plugin/.antigravity-plugin/plugin.json +1 -1
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin/.codex-plugin/plugin.json +1 -1
  5. package/plugin/.github/plugin/plugin.json +1 -1
  6. package/plugin/.grok-plugin/plugin.json +1 -1
  7. package/plugin/.muse-plugin/plugin.json +1 -1
  8. package/plugin/package.json +1 -1
  9. package/plugin/pi/index.ts +3 -2
  10. package/plugin/pi/prompt.ts +8 -3
  11. package/plugin/skills/poteto-mode/playbooks/worktree-cleanup.md +1 -1
  12. package/plugin/skills/poteto-mode/scripts/.prettierignore +3 -0
  13. package/plugin/skills/poteto-mode/scripts/watch-pr/cloud-reader.test.ts +21 -0
  14. package/plugin/skills/poteto-mode/scripts/watch-pr/cloud-reader.ts +7 -0
  15. package/plugin/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +6 -0
  16. package/plugin/skills/poteto-mode/scripts/watch-pr/github.port.test.ts +33 -0
  17. package/plugin/skills/poteto-mode/scripts/watch-pr/github.ts +25 -23
  18. package/plugin/skills/poteto-mode/scripts/watch-pr/head-checks.ts +47 -1
  19. package/plugin/skills/poteto-mode/scripts/watch-pr/policy.port.test.ts +158 -0
  20. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/fixtures/grafana-139602-cancelled-suites-beside-green.json +921 -0
  21. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/fixtures/grafana-139606-approval-gated.json +82 -0
  22. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/fixtures/grafana-139612-cancelled-check-beside-green.json +174 -0
  23. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/fixtures/octocat-hello-world-34-no-checks.json +42 -0
  24. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/gh.ts +144 -0
  25. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/harness.ts +172 -0
  26. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/heads.json +73 -0
  27. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/record.ts +410 -0
  28. package/plugin/skills/poteto-mode/scripts/watch-pr/replay/watch.ts +72 -0
  29. package/plugin/skills/poteto-mode/scripts/watch-pr/replay.port.test.ts +264 -0
  30. package/plugin/skills/poteto-mode/scripts/watch-pr/types.ts +2 -0
  31. package/plugin/skills/poteto-mode/scripts/watch-pr/workflow-runs.ts +58 -21
  32. package/plugin/skills/poteto-mode/scripts/worktree-audit.mjs +75 -6
  33. package/plugin/skills/setup-pstack/scripts/read-sheet.sh +6 -2
  34. package/plugin/vibe/plugin.json +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-pstack",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "description": "Install pstack into the agent harnesses on this machine: Claude Code, Codex, Pi, Copilot, Muse, OMP, Kimi, Grok, MiniMax, OpenCode, Antigravity, Vibe, and the shared skills directory.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Antigravity. Original pstack by Lauren Tan (poteto).",
5
5
  "author": "Michael Denyer",
6
6
  "logo": "assets/pstack-icon.png",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (Claude Code port)",
4
- "version": "0.9.174",
4
+ "version": "0.9.175",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Claude Code. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Codex port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/codex-tools.md. Original pstack by Lauren Tan (poteto).",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (GitHub Copilot port)",
4
- "version": "0.9.174",
4
+ "version": "0.9.175",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to GitHub Copilot CLI and app. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "description": "pstack workflows and skills for Grok Build",
5
5
  "skills": [
6
6
  "./skills",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "name": "pstack",
4
4
  "displayName": "pstack (Muse port)",
5
- "version": "0.9.174",
5
+ "version": "0.9.175",
6
6
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. Rigorous agent workflows you can parallelize with confidence. Muse port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/muse-tools.md. Original pstack by Lauren Tan (poteto).",
7
7
  "compat": {
8
8
  "source": "native",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.174",
3
+ "version": "0.9.175",
4
4
  "private": true,
5
5
  "omp": {
6
6
  "extensions": ["./omp/index.mjs"]
@@ -27,9 +27,10 @@ export function install(pi: ExtensionAPI, settings: Settings): void {
27
27
  process.on("exit", onExit);
28
28
  // Every entry, not the active branch: an agent started on a branch the user
29
29
  // later left is still a process, and its record is the only handle on it.
30
- pi.on("session_start", (_event, ctx) => {
30
+ // omo, a Pi fork, returns the entries as a Promise; Pi returns them directly.
31
+ pi.on("session_start", async (_event, ctx) => {
31
32
  runner.attachSession(ctx);
32
- runner.restore(ctx.sessionManager.getEntries());
33
+ runner.restore(await ctx.sessionManager.getEntries());
33
34
  });
34
35
  pi.on("session_shutdown", async () => {
35
36
  process.off("exit", onExit);
@@ -36,10 +36,15 @@ export function registerPromptSections(pi: ExtensionAPI, settings: Settings): vo
36
36
  const mandateFile = join(settings.pluginRoot, "hooks", "session-start-context.md");
37
37
  pi.on("before_agent_start", (event, ctx) => {
38
38
  const sheet = readSheet(settings.agentDir, ctx.cwd);
39
- const sections = event.systemPromptOptions.sections;
40
- sections[PARALLEL_SECTION] = PARALLEL_CALLS;
41
- sections[TOOLS_SECTION] = piToolsNote(settings.pluginRoot);
39
+ const sections: Record<string, string> = {
40
+ [PARALLEL_SECTION]: PARALLEL_CALLS,
41
+ [TOOLS_SECTION]: piToolsNote(settings.pluginRoot),
42
+ };
42
43
  if (settings.depth === 0 && !sheet?.hookOff) sections[MANDATE_SECTION] = piMandate(settings.pluginRoot, readFileSync(mandateFile, "utf8"));
43
44
  if (sheet) sections[SHEET_SECTION] = sheet.text;
45
+ // omo, a Pi fork, has no sections map; there they join the turn's system prompt.
46
+ const target = event.systemPromptOptions.sections;
47
+ if (!target) return { systemPrompt: [event.systemPrompt, ...Object.values(sections)].join("\n\n") };
48
+ Object.assign(target, sections);
44
49
  });
45
50
  }
@@ -3,7 +3,7 @@
3
3
  1. Snapshot and audit. Record `df -h /`, then run `skills/poteto-mode/scripts/worktree-audit.mjs` under the installed plugin (principle-build-the-lever). It reads paths from `git worktree list`, never hand-typed, since a hand-typed `myrepo-worktrees/x` misses one that lives at `.worktrees/myrepo/x` (principle-encode-lessons-in-structure). It classifies each worktree by size, age, merge state, uncommitted work, PR state, and the newest chat that touched it, then suggests a bucket. The transcript scan is slow, so background it.
4
4
  2. The bucket is advice, not permission. The pinned and active chats are the real artifact (principle-prove-it-works). Get that set from the user or your own session list and cross-check every candidate. The lever has marked `safe` a worktree the user had pinned, so the pinned set wins.
5
5
  3. Verify usage before deleting. For every `verify-recent-chat` row, or anything you doubt, fan subagents out to read the transcripts and report whether the chat is pinned or ongoing and which worktrees it touches (principle-guard-the-context-window, transcripts are bulk). A pinned chat spawns arena and repro trees into sibling worktrees via background subagents, and those are in use even when their names never hit the session list. Pick each subagent's reasoning level for the job, per the Subagents section.
6
- 4. Pause on irreversible loss. `wip:N` is N tracked paths with uncommitted changes and `untracked:N` is N files git has never seen. A worktree with both prints both, as in `wip:1,untracked:5`. `ignored:N` is N paths git ignores outside the build and cache directories named in the audit's `DISPOSABLE` list, such as `.env` or `.claude/settings.local.json`, which may exist nowhere else. List them with `git -C <path> status --porcelain --ignored=matching`. Also run `git -C <path> submodule foreach --recursive 'git ls-files --others --ignored --exclude-standard --directory --no-empty-directory'` to list ignored paths inside initialized submodules. `reflog:N` is N commits that no branch, tag, or remote reaches, kept only by the worktree's HEAD and its reflog, such as work committed on a detached HEAD. They are among the entries `git -C <path> reflog` prints. Keep any with `git branch <name> <sha>`. A clean worktree is recoverable from its branch. Either kind of uncommitted work is gone once the directory goes, so list it with the call the audit counted from, `git -C <path> status --porcelain --untracked-files=all --ignore-submodules=none`, show the diff from `git -C <path> diff HEAD --ignore-submodules=none --submodule=log`, and get a decision first. Each status line is work at stake, and an empty diff never means there is none. A diff leaves out every untracked file, and a plain `git diff` can leave out a submodule. A `wip` line that names a submodule stands for files changed or added inside it, or for commits made there. Run the same status call inside the submodule to list those files. `hold-locked` means another tool or agent locked the tree, with its reason in the LOCKED column. `git worktree remove` refuses a locked tree, so do not `rm -rf` around it. Per Autonomy, clean and merged and not-in-use proceeds. `wip`, `untracked`, `ignored`, `reflog`, locked, and in-use pause.
6
+ 4. Pause on irreversible loss. `wip:N` is N tracked paths with uncommitted changes and `untracked:N` is N files git has never seen. A worktree with both prints both, as in `wip:1,untracked:5`. `hidden:N` is N tracked files whose edits `git status` is told to overlook, because the file is flagged skip-worktree or assume-unchanged. The audit holds the row as `hold-wip`, since `git worktree remove` deletes such a tree without asking for `--force`. `git -C <path> ls-files -v` marks each flagged file with `S` or a lowercase letter, and `git -C <path> show HEAD:<file>` prints the committed text to compare one against. `autostash:N` is N stashes that a stopped `rebase --autostash` or `merge --autostash` keeps in the git directory of the worktree or of an initialized submodule, where status shows nothing and `ls-files -v` flags nothing. The audit holds the row as `hold-wip`; `git -C <path> rebase --abort`, or `merge --abort`, run in the worktree or the submodule that holds the stash, puts the edits back in the tree. `ignored:N` is N paths git ignores outside the build and cache directories named in the audit's `DISPOSABLE` list, such as `.env` or `.claude/settings.local.json`, which may exist nowhere else. List them with `git -C <path> status --porcelain --ignored=matching`. Also run `git -C <path> submodule foreach --recursive 'git ls-files --others --ignored --exclude-standard --directory --no-empty-directory'` to list ignored paths inside initialized submodules. `reflog:N` is N commits that no branch, tag, or remote reaches, kept only by the worktree's HEAD and its reflog, such as work committed on a detached HEAD. They are among the entries `git -C <path> reflog` prints. Keep any with `git branch <name> <sha>`. A clean worktree is recoverable from its branch. Either kind of uncommitted work is gone once the directory goes, so list it with the call the audit counted from, `git -C <path> status --porcelain --untracked-files=all --ignore-submodules=none`, show the diff from `git -C <path> diff HEAD --ignore-submodules=none --submodule=log`, and get a decision first. Each status line is work at stake, and an empty diff never means there is none. A diff leaves out every untracked file, and a plain `git diff` can leave out a submodule. A `wip` line that names a submodule stands for files changed or added inside it, or for commits made there. Run the same status call inside the submodule to list those files. `hold-locked` means another tool or agent locked the tree, with its reason in the LOCKED column. `git worktree remove` refuses a locked tree, so do not `rm -rf` around it. Per Autonomy, clean and merged and not-in-use proceeds. `wip`, `hidden`, `autostash`, `untracked`, `ignored`, `reflog`, locked, and in-use pause.
7
7
  5. Prune the confirmed set. Per path, `git worktree remove --force <path>`. If the dir survives on ignored build artifacts, `rm -rf` it, then `git worktree prune`. Branch refs survive, so commits on the worktree's branch are kept. The worktree's HEAD reflog goes with it, so a commit only that reflog reaches is lost. Commits made inside a submodule are stored with the worktree and go with it. Confirm with `df -h /` and re-list.
8
8
  6. Simulators and other reclaimers. Simulators are usually the next-biggest win. `xcrun simctl --set testing delete all` (XCTestDevices clones), `xcrun simctl delete unavailable`, and `xcrun simctl runtime list` then `runtime delete <id>` for old runtimes. More when needed: Xcode `DerivedData` and `iOS DeviceSupport`, your editor's application-support caches, `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/shell-snapshots/` and old `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/` transcripts (keep the recent ones the **recall** skill and Session pickup read), package caches (pnpm, uv, brew, yarn). Clear only caches the user has not said to keep.
9
9
 
@@ -17,3 +17,6 @@ watch-pr/fakes.test-helper.ts
17
17
  # Upstream stopped formatting github.test.ts with Prettier at 96dec8e;
18
18
  # keeping its wrapping keeps the fork small.
19
19
  watch-pr/github.test.ts
20
+
21
+ # replay/record.ts writes these, one check, suite, or run per line.
22
+ watch-pr/replay/fixtures/
@@ -62,10 +62,19 @@ if (path === prefix + 'pulls/1') {
62
62
  : scenario === 'replaced' ? [run('build', 'cancelled', 2, '2026-11-23T09:00:00Z'), run('build', 'success'), run('test', 'success')]
63
63
  // Two jobs of one workflow run, started in the same second, one still running.
64
64
  : scenario === 'tie' ? [run('build', 'success'), run('build'), run('test', 'success')]
65
+ // A job of a run cancelled before its matrix expanded, whose name no job of the later run has.
66
+ : scenario.startsWith('matrix-') ? [run('build-matrix', 'cancelled', 2, '2026-11-23T09:00:00Z'), run('build', 'success'), run('test', 'success')]
65
67
  : scenario === 'codeql' ? [run('build', 'success'), run('test', 'success'), run('Analyze (javascript)', null, 3)]
66
68
  : scenario === 'copilot-agent' ? [run('build', 'success'), run('test', 'success'), run('copilot-pull-request-reviewer', null, 4)]
67
69
  : [run('build', 'success'), run('test', 'success')];
68
70
  value = [{ total_count: scenario === 'short-page' ? runs.length + 1 : runs.length, check_runs: runs }];
71
+ } else if (path === prefix + 'actions/runs?head_sha=head&per_page=100' && scenario.startsWith('matrix-')) {
72
+ // The later run is of the same workflow when it replaced the cancelled one, and of another when not.
73
+ const workflowRun = (id, workflowId, conclusion, created) => ({ id, check_suite_id: id, workflow_id: workflowId, name: 'CI', event: 'pull_request', path: '.github/workflows/ci-' + workflowId + '.yml', head_sha: 'head', status: 'completed', conclusion, created_at: created });
74
+ value = [{ total_count: 2, workflow_runs: [
75
+ workflowRun(1, scenario === 'matrix-replaced' ? 100 : 200, 'success', '2026-11-23T10:00:00Z'),
76
+ workflowRun(2, 100, 'cancelled', '2026-11-23T09:00:00Z'),
77
+ ] }];
69
78
  } else if (path === prefix + 'actions/runs?head_sha=head&per_page=100') {
70
79
  value = [{ total_count: 4, workflow_runs: [
71
80
  { id: 1, check_suite_id: 1, name: 'CI', event: 'pull_request', path: '.github/workflows/ci.yml' },
@@ -228,6 +237,18 @@ it("keeps only the newest run per name, workflow, and event, as gh pr checks doe
228
237
  ).toEqual(["build/CI", "test/CI"]);
229
238
  });
230
239
 
240
+ it("drops a cancelled job that a later run of its workflow replaced, and keeps one that no later run replaced", () => {
241
+ expect(
242
+ watch("matrix-replaced", ["--status-only"]).verdict.rows[0].ci
243
+ ).toMatchObject({ kind: "ci-clean", failed: [] });
244
+ expect(
245
+ watch("matrix-alone", ["--status-only"]).verdict.rows[0].ci
246
+ ).toMatchObject({
247
+ kind: "ci-failing",
248
+ failed: [expect.objectContaining({ name: "build-matrix" })],
249
+ });
250
+ });
251
+
231
252
  it("counts CodeQL's dynamic workflow, as GitHub's rollup does, and leaves out Copilot's review agent", () => {
232
253
  expect(watch("codeql", ["--status-only"]).verdict.rows[0].ci).toMatchObject({
233
254
  kind: "ci-pending",
@@ -105,6 +105,9 @@ export class FallbackGitHubReader implements T.GitHubReader {
105
105
  reader.unsettledSuites(context, head, checksRead, expectedApps)
106
106
  );
107
107
  }
108
+ workflowRunPages(context: T.PrContext, head: string) {
109
+ return this.read((reader) => reader.workflowRunPages(context, head));
110
+ }
108
111
  }
109
112
 
110
113
  // One check as `gh pr checks --json` reports it, which parseFastCheck reads.
@@ -616,4 +619,8 @@ export class CloudSessionReader implements T.GitHubReader {
616
619
  ) {
617
620
  return this.local.unsettledSuites(context, head, checksRead, expectedApps);
618
621
  }
622
+ // A REST read, which the proxy serves, so the local reader makes it.
623
+ workflowRunPages(context: T.PrContext, head: string) {
624
+ return this.local.workflowRunPages(context, head);
625
+ }
619
626
  }
@@ -25,6 +25,8 @@ export interface FakeReaderOptions {
25
25
  readonly threadPages?: readonly ReviewThreadPage[];
26
26
  readonly commitRollups?: readonly CommitRollup[];
27
27
  readonly unsettledSuites?: readonly SuiteCheck[];
28
+ /** The head's Actions workflow runs, as REST lists them on one page. */
29
+ readonly workflowRuns?: readonly unknown[];
28
30
  readonly openPullRequests?: readonly OpenPullRequest[];
29
31
  readonly defaultBranch?: string;
30
32
  readonly origin?: Repository | null;
@@ -159,5 +161,9 @@ export function fakeReader(
159
161
  calls.push(`unsettledSuites:${head}:${checksRead}`);
160
162
  return { checks: options.unsettledSuites ?? [], queuedWithoutRuns: [] };
161
163
  },
164
+ async workflowRunPages(_requested, head) {
165
+ calls.push(`workflowRunPages:${head}`);
166
+ return [{ workflow_runs: options.workflowRuns ?? [] }];
167
+ },
162
168
  };
163
169
  }
@@ -1,4 +1,8 @@
1
1
  import { describe, expect, it } from "bun:test";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
2
6
  import { parseSuiteRead } from "./check-suites.ts";
3
7
  import { WatchDeadline } from "./deadline.ts";
4
8
  import {
@@ -828,6 +832,35 @@ it("reports a binary that cannot be spawned as a query failure that does not ret
828
832
  });
829
833
  });
830
834
 
835
+ // The check read can reach the workflow runs before any suite read, so their
836
+ // read names the gh upgrade as the suite read does.
837
+ it("asks for a newer gh when the workflow-run read meets one without --slurp", () => {
838
+ const directory = mkdtempSync(join(tmpdir(), "watch-pr-old-gh-"));
839
+ try {
840
+ writeFileSync(
841
+ join(directory, "gh"),
842
+ "#!/bin/sh\necho 'unknown flag: --slurp' >&2\nexit 1\n",
843
+ { mode: 0o755 }
844
+ );
845
+ const program = `import { GhGitHubReader } from ${JSON.stringify(import.meta.dir + "/github.ts")};
846
+ import { WatchDeadline } from ${JSON.stringify(import.meta.dir + "/deadline.ts")};
847
+ const reader = new GhGitHubReader(new WatchDeadline(0, Date.now));
848
+ await reader.workflowRunPages({ owner: "owner", repo: "repo", number: 42 }, "head").catch((error) => console.log(JSON.stringify(error.failure)));`;
849
+ const child = spawnSync(process.execPath, ["-e", program], {
850
+ encoding: "utf8",
851
+ timeout: 2000,
852
+ env: { ...process.env, PATH: directory + ":" + process.env.PATH },
853
+ });
854
+ expect(child.status).toBe(0);
855
+ expect(JSON.parse(child.stdout)).toMatchObject({
856
+ kind: "unsupported-gh",
857
+ retryable: false,
858
+ });
859
+ } finally {
860
+ rmSync(directory, { recursive: true, force: true });
861
+ }
862
+ });
863
+
831
864
  describe("fast-path check mapping", () => {
832
865
  // gh's aggregate.go files every state it does not name into the pending
833
866
  // bucket, including completed conclusions.
@@ -757,22 +757,9 @@ export class GhGitHubReader implements T.GitHubReader {
757
757
  checksRead: T.CheckRead["kind"],
758
758
  expectedApps: readonly string[]
759
759
  ): Promise<T.SuiteRead> {
760
- const result = await this.run([
761
- "gh",
762
- "api",
763
- "--paginate",
764
- "--slurp",
765
- `repos/${context.owner}/${context.repo}/commits/${head}/check-suites?per_page=100`,
766
- ]);
767
- if (
768
- result.code !== 0 &&
769
- firstLine(result.stderr) === "unknown flag: --slurp"
770
- )
771
- throw new WatcherQueryError({
772
- kind: "unsupported-gh",
773
- retryable: false,
774
- detail: "gh api rejected --slurp. Upgrade GitHub CLI to 2.48 or later.",
775
- });
760
+ const result = await this.slurp(
761
+ `repos/${context.owner}/${context.repo}/commits/${head}/check-suites?per_page=100`
762
+ );
776
763
  const parsed = parseSuiteRead(
777
764
  commandJson(result, "gh api check-suites"),
778
765
  head,
@@ -780,18 +767,33 @@ export class GhGitHubReader implements T.GitHubReader {
780
767
  expectedApps
781
768
  );
782
769
  if (parsed.startupFailureSuites.length === 0) return suiteReadOf(parsed);
783
- const workflowPages = await this.runJson([
784
- "gh",
785
- "api",
786
- "--paginate",
787
- "--slurp",
788
- `repos/${context.owner}/${context.repo}/actions/runs?head_sha=${head}&per_page=100`,
789
- ]);
770
+ const workflowPages = await this.workflowRunPages(context, head);
790
771
  return mergeWorkflowRunChecks(
791
772
  parsed,
792
773
  resolveWorkflowRunChecks(workflowPages, parsed, head)
793
774
  );
794
775
  }
776
+ async workflowRunPages(context: T.PrContext, head: string): Promise<unknown> {
777
+ const path = `repos/${context.owner}/${context.repo}/actions/runs?head_sha=${head}&per_page=100`;
778
+ return commandJson(
779
+ await this.slurp(path),
780
+ `gh api --paginate --slurp ${path}`
781
+ );
782
+ }
783
+ // gh before 2.48 has no --slurp, which every paginated REST read here uses.
784
+ private async slurp(path: string): Promise<CommandResult> {
785
+ const result = await this.run(["gh", "api", "--paginate", "--slurp", path]);
786
+ if (
787
+ result.code !== 0 &&
788
+ firstLine(result.stderr) === "unknown flag: --slurp"
789
+ )
790
+ throw new WatcherQueryError({
791
+ kind: "unsupported-gh",
792
+ retryable: false,
793
+ detail: "gh api rejected --slurp. Upgrade GitHub CLI to 2.48 or later.",
794
+ });
795
+ return result;
796
+ }
795
797
  }
796
798
 
797
799
  export { unsettledSuiteChecks };
@@ -2,10 +2,12 @@ import { resolveChecks } from "./github.ts";
2
2
  import type { LandingRevision } from "./landing.ts";
3
3
  import {
4
4
  nonEmpty,
5
+ type Check,
5
6
  type CheckRead,
6
7
  type GitHubReader,
7
8
  type SuiteApp,
8
9
  } from "./types.ts";
10
+ import { replacedRunIds } from "./workflow-runs.ts";
9
11
 
10
12
  // No check read shows a suite with no runs, such as a fork workflow waiting for
11
13
  // maintainer approval, so the head's suites are read before its CI counts as
@@ -15,7 +17,11 @@ export async function resolveHeadChecks(
15
17
  facts: Pick<LandingRevision, "context" | "headRefOid">,
16
18
  expectedApps: readonly string[] = []
17
19
  ): Promise<CheckRead & { readonly queuedWithoutRuns: readonly SuiteApp[] }> {
18
- const read = await resolveChecks(reader, facts.context);
20
+ const read = await withoutReplacedCancels(
21
+ reader,
22
+ facts,
23
+ await resolveChecks(reader, facts.context)
24
+ );
19
25
  if (
20
26
  read.checks.some(
21
27
  (check) => check.kind === "failed" || check.kind === "pending"
@@ -35,3 +41,43 @@ export async function resolveHeadChecks(
35
41
  ? { ...read, checks: [...read.checks, ...checks], queuedWithoutRuns }
36
42
  : { kind: "reported", source: "check-suites", checks, queuedWithoutRuns };
37
43
  }
44
+
45
+ const RUN_ID = /\/actions\/runs\/(\d+)(?:\/|$)/;
46
+ const cancelledRunId = (check: Check): number | null => {
47
+ if (check.kind !== "failed" || check.reportedState !== "CANCELLED")
48
+ return null;
49
+ const match = RUN_ID.exec(check.link);
50
+ return match === null ? null : Number(match[1]);
51
+ };
52
+
53
+ // gh lists a job of a cancelled workflow run when no job of a later run has
54
+ // its name, as when the run was cancelled before its matrix expanded. A later
55
+ // run of the same workflow and event on the head that finished, by succeeding
56
+ // or failing to start, replaces it, and its own checks then decide. A
57
+ // cancelled check that is not shown to be replaced stays failed. When another
58
+ // check failed, the verdict is already decided and the runs go unread.
59
+ async function withoutReplacedCancels(
60
+ reader: GitHubReader,
61
+ facts: Pick<LandingRevision, "context" | "headRefOid">,
62
+ read: CheckRead
63
+ ): Promise<CheckRead> {
64
+ if (
65
+ read.kind !== "reported" ||
66
+ read.checks.every((check) => cancelledRunId(check) === null) ||
67
+ read.checks.some(
68
+ (check) => check.kind === "failed" && cancelledRunId(check) === null
69
+ )
70
+ )
71
+ return read;
72
+ const replaced = replacedRunIds(
73
+ await reader.workflowRunPages(facts.context, facts.headRefOid),
74
+ facts.headRefOid
75
+ );
76
+ const checks = nonEmpty(
77
+ read.checks.filter((check) => {
78
+ const runId = cancelledRunId(check);
79
+ return runId === null || !replaced.has(runId);
80
+ })
81
+ );
82
+ return checks === null ? read : { ...read, checks };
83
+ }
@@ -11,6 +11,7 @@ import {
11
11
  import { fakeReader, failedCheck, pendingCheck } from "./fakes.test-helper.ts";
12
12
  import { unsettledSuiteChecks } from "./github.ts";
13
13
  import type {
14
+ Check,
14
15
  GitHubReader,
15
16
  NonEmpty,
16
17
  PollingOptions,
@@ -877,6 +878,163 @@ describe("check suites that no check read shows", () => {
877
878
  });
878
879
  });
879
880
 
881
+ // grafana/grafana PR 139612 at 8c63a54b, read on 2026-12-03: gh pr checks
882
+ // listed a Bundle size job cancelled before its matrix expanded, so no job of
883
+ // the later, passing Bundle size run shares its name. Both runs are workflow
884
+ // 342766777 on pull_request.
885
+ describe("a cancelled check from a run a later run replaced", () => {
886
+ const head = "8c63a54b5334bc97775bbfcfe858424434ff2d1f";
887
+ const jobLink = (run: number, job: number) =>
888
+ `https://github.com/grafana/grafana/actions/runs/${run}/job/${job}`;
889
+ const cancelled = {
890
+ kind: "failed",
891
+ name: "Build ${{ matrix.target }} frontend",
892
+ reportedState: "CANCELLED",
893
+ description: "",
894
+ link: jobLink(47100668579, 144370325863),
895
+ workflow: "Bundle size",
896
+ } as const;
897
+ const rebuilt = {
898
+ kind: "passed",
899
+ name: "Build pr frontend",
900
+ reportedState: "SUCCESS",
901
+ description: "",
902
+ link: jobLink(47139247402, 144371788751),
903
+ workflow: "Bundle size",
904
+ } as const;
905
+ const run = (
906
+ id: number,
907
+ suite: number,
908
+ createdAt: string,
909
+ conclusion: string | null
910
+ ) => ({
911
+ id,
912
+ workflow_id: 342766777,
913
+ check_suite_id: suite,
914
+ event: "pull_request",
915
+ head_sha: head,
916
+ status: conclusion === null ? "in_progress" : "completed",
917
+ conclusion,
918
+ created_at: createdAt,
919
+ name: "Bundle size",
920
+ });
921
+ const first = run(
922
+ 47100668579,
923
+ 127381116871,
924
+ "2026-12-03T11:56:06Z",
925
+ "cancelled"
926
+ );
927
+ const second = run(
928
+ 47139247402,
929
+ 127486757905,
930
+ "2026-12-03T15:29:54Z",
931
+ "success"
932
+ );
933
+ const read = async (
934
+ checks: readonly Check[],
935
+ workflowRuns: readonly unknown[]
936
+ ) => {
937
+ const reader = fakeReader({
938
+ facts: { headRefOid: head },
939
+ fastPath: { kind: "checks", checks: checks as [Check, ...Check[]] },
940
+ commitRollups: [{ oid: head, state: "SUCCESS" }],
941
+ workflowRuns,
942
+ });
943
+ const snapshot = await readSnapshot({
944
+ reader,
945
+ context: context(40),
946
+ pendingHistory: "include",
947
+ allowDraft: false,
948
+ });
949
+ return { snapshot, calls: reader.calls };
950
+ };
951
+
952
+ it("drops it when a later run of the same workflow and event succeeded", async () => {
953
+ const { snapshot, calls } = await read(
954
+ [cancelled, rebuilt],
955
+ [second, first]
956
+ );
957
+ expect(snapshot).toMatchObject({ ci: { kind: "ci-clean" } });
958
+ expect(calls).toContain(`workflowRunPages:${head}`);
959
+ expect(calls).toContain(`unsettledSuites:${head}:reported`);
960
+ });
961
+
962
+ // gh lists only the jobs a run has started, so a running replacement can
963
+ // show nothing but passes between one job and the next.
964
+ it("keeps it failed while the later run is still running", async () => {
965
+ const running = {
966
+ ...rebuilt,
967
+ kind: "pending",
968
+ reportedState: "IN_PROGRESS",
969
+ } as const;
970
+ for (const checks of [
971
+ [cancelled, running],
972
+ [cancelled, rebuilt],
973
+ ])
974
+ expect(
975
+ (
976
+ await read(checks, [
977
+ { ...second, status: "in_progress", conclusion: null },
978
+ first,
979
+ ])
980
+ ).snapshot
981
+ ).toMatchObject({ ci: { kind: "ci-failing", failed: [cancelled] } });
982
+ });
983
+
984
+ it("keeps it failed, and reads no runs, when another check failed", async () => {
985
+ const failing = failedCheck();
986
+ const { snapshot, calls } = await read(
987
+ [cancelled, rebuilt, failing],
988
+ [second, first]
989
+ );
990
+ expect(snapshot).toMatchObject({
991
+ ci: { kind: "ci-failing", failed: [cancelled, failing] },
992
+ });
993
+ expect(calls.filter((call) => call.startsWith("workflowRunPages"))).toEqual(
994
+ []
995
+ );
996
+ });
997
+
998
+ it("keeps it failed when no later run replaced it", async () => {
999
+ for (const runs of [
1000
+ [first],
1001
+ [{ ...second, conclusion: "cancelled" }, first],
1002
+ [{ ...second, event: "push" }, first],
1003
+ ])
1004
+ expect((await read([cancelled, rebuilt], runs)).snapshot).toMatchObject({
1005
+ ci: { kind: "ci-failing", failed: [cancelled] },
1006
+ });
1007
+ });
1008
+
1009
+ it("keeps it failed when its run is not one of the head's runs", async () => {
1010
+ const { snapshot } = await read([cancelled, rebuilt], [second]);
1011
+ expect(snapshot).toMatchObject({
1012
+ ci: { kind: "ci-failing", failed: [cancelled] },
1013
+ });
1014
+ });
1015
+
1016
+ it("keeps it failed, and reads no runs, when its link names no run", async () => {
1017
+ const unlinked = { ...cancelled, link: "" };
1018
+ const { snapshot, calls } = await read(
1019
+ [unlinked, rebuilt],
1020
+ [second, first]
1021
+ );
1022
+ expect(snapshot).toMatchObject({
1023
+ ci: { kind: "ci-failing", failed: [unlinked] },
1024
+ });
1025
+ expect(calls.filter((call) => call.startsWith("workflowRunPages"))).toEqual(
1026
+ []
1027
+ );
1028
+ });
1029
+
1030
+ it("reads no runs when no check was cancelled", async () => {
1031
+ const { calls } = await read([rebuilt, failedCheck()], [second, first]);
1032
+ expect(calls.filter((call) => call.startsWith("workflowRunPages"))).toEqual(
1033
+ []
1034
+ );
1035
+ });
1036
+ });
1037
+
880
1038
  describe("apps named with --expect-app", () => {
881
1039
  const queuedSuite = (slug: string, name: string) => ({
882
1040
  head_sha: "head",