open-pstack 0.9.159 → 0.9.161

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 (31) hide show
  1. package/lib/bundle.mjs +12 -3
  2. package/lib/cli.mjs +2 -2
  3. package/package.json +1 -1
  4. package/plugin/.antigravity-plugin/plugin.json +1 -1
  5. package/plugin/.claude-plugin/plugin.json +1 -1
  6. package/plugin/.codex-plugin/plugin.json +1 -1
  7. package/plugin/.github/plugin/plugin.json +1 -1
  8. package/plugin/.grok-plugin/plugin.json +1 -1
  9. package/plugin/.muse-plugin/plugin.json +1 -1
  10. package/plugin/omp/index.mjs +2 -3
  11. package/plugin/package.json +1 -1
  12. package/plugin/pi/agent-text.ts +4 -3
  13. package/plugin/pi/agent-tools.ts +2 -2
  14. package/plugin/pi/agents.ts +75 -40
  15. package/plugin/pi/child.ts +1 -0
  16. package/plugin/pi/config.ts +6 -3
  17. package/plugin/pi/hc-child.ts +11 -7
  18. package/plugin/pi/orca-child.ts +242 -0
  19. package/plugin/pi/prompt.ts +8 -2
  20. package/plugin/pi/t3-child.ts +94 -26
  21. package/plugin/skills/babysit/SKILL.md +4 -2
  22. package/plugin/skills/poteto-mode/playbooks/babysit.md +1 -1
  23. package/plugin/skills/poteto-mode/references/cloud-session-pr-reads.md +5 -4
  24. package/plugin/skills/poteto-mode/references/codex-tools.md +3 -2
  25. package/plugin/skills/poteto-mode/references/omp-tools.md +7 -3
  26. package/plugin/skills/poteto-mode/references/pi-tools.md +5 -4
  27. package/plugin/skills/poteto-mode/scripts/watch-pr/cli.port.test.ts +41 -0
  28. package/plugin/skills/poteto-mode/scripts/watch-pr/cli.ts +18 -0
  29. package/plugin/skills/poteto-mode/scripts/watch-pr/policy.port.test.ts +132 -0
  30. package/plugin/skills/poteto-mode/scripts/watch-pr/policy.ts +17 -0
  31. package/plugin/skills/poteto-mode/scripts/watch-pr/types.ts +2 -0
@@ -35,8 +35,9 @@ poteto-mode's Subagents section applies on Pi through the `agent` tool:
35
35
  - `subagent_type` takes the same values. `pstack:poteto-agent`, `pstack:comment-sicko`, `pstack:thermo-nuclear-review-subagent`, and `pstack:thermo-nuclear-code-quality-review-subagent` resolve to the plugin's agent files. A `.md` file in `pstack-agents` in the Pi agent directory adds a type under its file name with no `pstack:` prefix, as a Claude Code user agent has no plugin prefix, and the body after the frontmatter is the child's system prompt. Its `tools:`, `disallowedTools:`, and `isolation:` fields are ignored, so pass `readonly: true` or `isolation: "worktree"` on the `agent` call instead. A hidden file, a file whose name has a colon, and one that cannot be read are skipped. The extension reads the frontmatter as YAML, and a repeated key keeps its last value, as in Claude Code. When the YAML does not parse, it retries as Claude Code 2.1.310 does, reading an unquoted top-level value that holds YAML syntax, such as `description: Use for a: b`, as text and turning leading tabs into spaces. It skips a user file whose frontmatter still does not parse. A user file never replaces a type, so `poteto-agent.md` there adds `poteto-agent` and leaves `pstack:poteto-agent` alone. The extension does not read Pi's `agents` folder, whose files other subagent extensions write with their own frontmatter. `general-purpose`, or no `subagent_type`, runs a child with no agent file. Claude Code's built-in types such as `Explore` and `Plan` do not exist on Pi, so use `general-purpose` and put the constraint in the prompt. An unknown type errors and lists the valid ones. The `agent` tool's `subagent_type` description lists each type the session starts with and what it is for, from each agent file's `description:`, the user's files included.
36
36
  - `readonly: true`, which the `how` subagent sets, runs the child without the `edit` and `write` tools. It keeps `bash`, so a reviewer can still run `git diff`; say in the prompt that it must not change files.
37
37
  - Each child is its own `pi --mode rpc` process in your working directory, and the extension sends it the prompt on its stdin. It loads the packages and settings saved on disk, so it sees the pstack skills when pstack was installed with `pi install`. It does not inherit the parent's command-line flags, such as `-e`, `--api-key`, or a one-off `-a` project trust, so a pstack loaded only through `-e` gives children no extension.
38
- - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child started there is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt. Messaged from a session outside herdr-core, it runs that turn as an RPC child.
39
- - With a `pi agent host: t3` line in the sheet and the session inside T3 Code (`T3_MCP_URL` and `T3_MCP_BEARER_TOKEN` are set), each child started there without `isolation: "worktree"` is instead a T3 Code child thread of your thread, titled with the agent's description, on the agent's model, in your thread's folder. Its effort goes to T3 Code only when T3 Code lists that level for the model. The user can watch it and type into it in T3 Code. `send_message` to a running one steers its turn, a finished one resumes in the same thread, and `stop_agent` cancels its task; when T3 Code refuses the cancel, the agent reads as stopped with the refusal as its text, and its thread can go on running. When T3 Code accepts the cancel but the thread has not settled after the kill grace, the agent also reads as stopped. A worktree agent and the agents it starts stay local processes in its worktree. A `readonly: true` agent and an agent at the third layer also stay local processes, because T3 Code cannot remove a thread's tools. A question it asks waits until someone answers it in T3 Code. T3 Code marks its first message as sent by an agent, so say in the prompt that the user started the task. The agent file's body arrives at the top of its first message. Only a Pi session inside T3 Code can message it. `list_agents` shows no `activity` and no transcript for it; its transcript is the T3 Code thread.
38
+ - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child started there is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt. A prompt that is empty once trimmed is refused, as is such a message to a finished one. Messaged from a session outside herdr-core, it runs that turn as an RPC child.
39
+ - With a `pi agent host: t3` line in the sheet and the session inside T3 Code (`T3_MCP_URL` and `T3_MCP_BEARER_TOKEN` are set), each child started there without `isolation: "worktree"` is instead a T3 Code child thread of your thread, titled with the agent's description, on the agent's model, in your thread's folder. Its effort goes to T3 Code only when T3 Code lists that level for the model. The user can watch it and type into it in T3 Code. `send_message` to a running one steers its turn, a finished one resumes in the same thread, and `stop_agent` cancels its task; when T3 Code refuses the cancel, the agent reads as stopped with the refusal as its text, and its thread can go on running. When T3 Code accepts the cancel but the thread has not settled after the kill grace, the agent also reads as stopped. A message that T3 Code queues or starts as a new turn instead of steering, such as one that starts with a slash command, is sent once, and the agent runs until that turn ends. A worktree agent and the agents it starts stay local processes in its worktree. A `readonly: true` agent and an agent at the third layer also stay local processes, because T3 Code cannot remove a thread's tools. A question it asks waits until someone answers it in T3 Code. T3 Code marks its first message as sent by an agent, so say in the prompt that the user started the task. The agent file's body arrives at the top of its first message. Only a Pi session inside T3 Code can message it. `list_agents` shows no `activity` and no transcript for it; its transcript is the T3 Code thread.
40
+ - With a `pi agent host: orca` line in the sheet and the session in an [Orca](https://github.com/stablyai/orca) terminal or its chat panel (`ORCA_TERMINAL_HANDLE` or `ORCA_STRUCTURED_SESSION` is set, and `ORCA_CLI_COMMAND` too except on macOS, where the `orca` on `PATH` is used), each child started there is instead an interactive `pi` in its own tab of your Orca workspace, titled with the agent's description and its id, as in `review the diff (a1b2c3d4e5f6a7b8)`, with the same flags as an RPC child. The workspace is the one `ORCA_WORKTREE_ID` or `ORCA_WORKSPACE_ID` names. Without either, as in a structured worker from Orca's `orchestration worker-start` or the Pi in Orca's chat panel, it is the workspace at the git top level of your session's working directory, or at that directory when git gives no top level, as outside a git repository, and when Orca's `worktree show` does not confirm that directory as one Orca registered, or its CLI is missing, the agent runs as an RPC child. When the sheet also has `pi agent host: hc` and the session is inside herdr-core, hc wins. The user can watch it and type into it. `send_message` to a running one types into its tab with Orca's `terminal send`, and its reply is read from its transcript. Pi's editor takes that message, so a message that starts with `!` or `/`, which the editor would run as a command, is refused, and the editor trims the message's ends and turns tabs into spaces and CRLF into LF, so an empty message is refused too. A prompt that starts with `@` or `/` reaches the child with one leading space. A prompt that is empty once trimmed is refused, as is such a message to a finished one. A run that the user stops with Escape in Orca ends `stopped`, and its notice starts a turn. Each Orca CLI call gives up after 10 seconds. A child that stops at a dialog waits until someone answers it in Orca. Stop it with `stop_agent`, not by closing its tab. Its tab closes when the run ends, and a message to a finished one resumes it in a new tab. It gets your environment, except Orca's own terminal variables (`ORCA_*`), and your session's project trust. A worktree agent's tab is in your workspace and runs in its worktree. `list_agents` shows no `activity` for it. On Linux, a prompt over 128 KiB fails and a message over 128 KiB is refused; put long material in a file and name the file in the prompt. Messaged from a session outside an Orca terminal, it runs that turn as an RPC child. Orca on Windows is not supported.
40
41
  - A child can start its own agents, down to three layers below the main session, as on Claude Code. A child at the third layer runs without the `agent` tool.
41
42
  - `isolation: "worktree"` runs the child in its own git worktree under `.claude/worktrees/`. A worktree the agent left nothing in is removed when the agent finishes; a change, a gitignored file it wrote, or a commit on its branch or on any commit its HEAD visited keeps it.
42
43
  - `run_in_background: true` returns the agent id at once. The completion joins the conversation after your current tool calls finish, as on Claude Code, or starts a turn when you are idle. In print and JSON mode (`pi -p`), where Pi exits once the run settles, the extension holds the settle while a background agent runs, so each completion still arrives as a turn and the process ends after the last one. A child agent holds its settle the same way while its own background agents run, because its parent closes its stdin once it settles, and a message from the parent ends the hold. Interactive and RPC main sessions settle as usual and take the completion when it arrives.
@@ -70,7 +71,7 @@ A `pi models: opus=<provider/id>, sonnet=<provider/id>` line in the Pi override
70
71
 
71
72
  ## Session routing
72
73
 
73
- The pstack Pi extension adds the poteto-mode mandate, the text the Claude Code and Codex `SessionStart` hook injects, to the system prompt at every agent start, so the mandate survives compaction. It also adds the Pi override sheet, because Pi has no include syntax for context files. The sheet is `pstack-models.md` in the Pi agent directory, which is `$PI_CODING_AGENT_DIR` when set and `~/.pi/agent` otherwise. A sheet committed at `.claude/pstack-models.md` replaces it in that project, as on Claude Code. The extension looks for it at the repository root of the working directory, or in the working directory itself outside a repository. It then reads nothing from the agent directory's sheet, so a project sheet that Pi users share needs its own `pi models:` line. `session hook: off` in the sheet stops the mandate. Child agents that the `agent` tool starts get the sheet but not the mandate, as Claude Code subagents see CLAUDE.md but run no `SessionStart` hook. Every session, child agents and sessions with the hook off included, also gets a pointer to this file and Claude Code's sentence on making independent tool calls in one response.
74
+ The pstack Pi extension adds the poteto-mode mandate, the text the Claude Code and Codex `SessionStart` hook injects with each `pstack:<name>` skill named by its bare name, to the system prompt at every agent start, so the mandate survives compaction. It also adds the Pi override sheet, because Pi has no include syntax for context files. The sheet is `pstack-models.md` in the Pi agent directory, which is `$PI_CODING_AGENT_DIR` when set and `~/.pi/agent` otherwise. A sheet committed at `.claude/pstack-models.md` replaces it in that project, as on Claude Code. The extension looks for it at the repository root of the working directory, or in the working directory itself outside a repository. It then reads nothing from the agent directory's sheet, so a project sheet that Pi users share needs its own `pi models:` line. `session hook: off` in the sheet stops the mandate. Child agents that the `agent` tool starts get the sheet but not the mandate, as Claude Code subagents see CLAUDE.md but run no `SessionStart` hook. Every session, child agents and sessions with the hook off included, also gets a pointer to this file and Claude Code's sentence on making independent tool calls in one response.
74
75
 
75
76
  Without the extension nothing is injected. Request `poteto-mode` explicitly with `/skill:poteto-mode`, or add a standing instruction to `AGENTS.md`.
76
77
 
@@ -96,7 +97,7 @@ No skill file carries a Pi line. poteto-mode's Platform Adaptation section point
96
97
  | `interrogate` | Adversaries dispatch through `agent` with the same `subagent_type` and `model` (see Subagent policy). Keep the panel on distinct models (see Model names). |
97
98
  | `recall` | Search the Pi sessions directory for this workspace (see Tool actions). Do not list or read `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/`: it holds Claude Code transcripts, not this session's history. Match on `type: "message"` entries and their `message.role`. |
98
99
  | `show-me-your-work` | Check the log against this run's Pi session file (see Tool actions), not a Claude Code transcript. |
99
- | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`; inside T3 Code, add `pi agent host: t3`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
100
+ | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`; inside T3 Code, add `pi agent host: t3`. In an Orca terminal, add `pi agent host: orca`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
100
101
  | `no-comments` | `pstack:comment-sicko` resolves through `agent` as written. Pass it the scope, not a request to run `/no-comments`, and run it without `isolation: "worktree"`, because a worktree starts from `HEAD` and lacks the scope's uncommitted changes. |
101
102
  | `teach` | Running `how` and `why` in parallel maps to two background `agent` calls. Pi has no image generation tool, so draw with Mermaid or plain text. |
102
103
  | `create-verification-skill` | The generated skill lands under `.claude/skills/verify/` on Claude Code. Write it where Pi discovers project skills, `.pi/skills/verify/` or `.agents/skills/verify/`, instead. The app-driving harness is platform-neutral. |
@@ -78,6 +78,47 @@ describe("watching a head without checks after an earlier commit passed", () =>
78
78
  );
79
79
  });
80
80
 
81
+ describe("--head", () => {
82
+ const usage = async (argv: readonly string[]) => {
83
+ const stderr: string[] = [];
84
+ const runtime = {
85
+ reader: fakeReader(),
86
+ deadline: new WatchDeadline(0, () => 0),
87
+ clock: {
88
+ now: () => 0,
89
+ observedAt: () => "2026-07-26T00:00:00.000Z",
90
+ async sleep() {},
91
+ },
92
+ stdout: () => {},
93
+ stderr: (text: string) => stderr.push(text),
94
+ } satisfies CliRuntime;
95
+ return { code: await main(argv, runtime), stderr: stderr.join("") };
96
+ };
97
+
98
+ it("passes the pushed commit to the polling options in lower case", () => {
99
+ expect(
100
+ parseArgs(["--head", "ABCDEF1"], silentIo).polling.expectedHead
101
+ ).toBe("abcdef1");
102
+ expect(parseArgs([], silentIo).polling.expectedHead).toBeUndefined();
103
+ });
104
+
105
+ it("rejects a value that is not a commit SHA as usage", async () => {
106
+ for (const value of ["", "abc12", "HEAD", "abcdefg", "a".repeat(41)]) {
107
+ const { code, stderr } = await usage(["--head", value]);
108
+ expect(code).toBe(64);
109
+ expect(stderr).toContain("commit SHA");
110
+ }
111
+ });
112
+
113
+ it("rejects --head with a stack, which has one head per PR", async () => {
114
+ for (const mode of ["--stack", "--queued-stack"]) {
115
+ const { code, stderr } = await usage(["--head", "abcdef1", mode]);
116
+ expect(code).toBe(64);
117
+ expect(stderr).toContain("--head watches one PR");
118
+ }
119
+ });
120
+ });
121
+
81
122
  describe("--expect-app", () => {
82
123
  it("collects each named app into the polling options", () => {
83
124
  expect(
@@ -87,6 +87,13 @@ function appSlugs(
87
87
  );
88
88
  return [...(previous ?? []), value];
89
89
  }
90
+ function commitSha(value: string): string {
91
+ if (!/^[0-9a-f]{7,40}$/i.test(value))
92
+ throw new InvalidArgumentError(
93
+ "must be a commit SHA of 7 to 40 hex digits"
94
+ );
95
+ return value.toLowerCase();
96
+ }
90
97
  interface RawOptions {
91
98
  readonly owner?: string;
92
99
  readonly repo?: string;
@@ -101,6 +108,7 @@ interface RawOptions {
101
108
  readonly statusOnly: boolean;
102
109
  readonly allowDraft: boolean;
103
110
  readonly expectApp?: readonly string[];
111
+ readonly head?: string;
104
112
  readonly pretty: boolean;
105
113
  }
106
114
  export function parseArgs(
@@ -166,11 +174,20 @@ export function parseArgs(
166
174
  "a GitHub App that runs CI here; a suite it has queued on the head with no runs counts as pending, and an app that never runs waits until --timeout, which is off by default (repeatable)",
167
175
  appSlugs
168
176
  )
177
+ .option(
178
+ "--head <sha>",
179
+ "the commit just pushed to the PR's branch; reads retry until GitHub first reports it",
180
+ commitSha
181
+ )
169
182
  .option("--pretty", "render human text instead of JSON", false);
170
183
  program.parse(argv, { from: "user" });
171
184
  const raw = program.opts<RawOptions>();
172
185
  if (raw.stackPrs !== undefined && !raw.queuedStack)
173
186
  program.error("error: --stack-prs requires --queued-stack");
187
+ if (raw.head !== undefined && (raw.stack || raw.queuedStack))
188
+ program.error(
189
+ "error: --head watches one PR, so it cannot be used with --stack or --queued-stack"
190
+ );
174
191
  return {
175
192
  owner: raw.owner ?? null,
176
193
  repo: raw.repo ?? null,
@@ -186,6 +203,7 @@ export function parseArgs(
186
203
  maxQueryErrors: raw.maxQueryErrors,
187
204
  allowDraft: raw.allowDraft,
188
205
  expectedApps: raw.expectApp,
206
+ expectedHead: raw.head,
189
207
  },
190
208
  };
191
209
  }
@@ -999,3 +999,135 @@ describe("apps named with --expect-app", () => {
999
999
  }
1000
1000
  });
1001
1001
  });
1002
+
1003
+ describe("the head pushed just before the watch", () => {
1004
+ const pushed = "bbbb2222bbbb2222bbbb2222bbbb2222bbbb2222";
1005
+ const previous = "aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111";
1006
+ // For about 2 s after a push, GitHub still reports the previous head and
1007
+ // that head's merge state; both reads of the first snapshot see it.
1008
+ const lagging = (): GitHubReader => {
1009
+ const reader = fakeReader({
1010
+ facts: { headRefOid: pushed },
1011
+ commitRollups: [
1012
+ { oid: previous, state: null },
1013
+ { oid: pushed, state: "SUCCESS" },
1014
+ ],
1015
+ });
1016
+ let reads = 0;
1017
+ return {
1018
+ ...reader,
1019
+ async pullRequest(requested) {
1020
+ reads += 1;
1021
+ const facts = await reader.pullRequest(requested);
1022
+ return reads <= 2
1023
+ ? {
1024
+ ...facts,
1025
+ headRefOid: previous,
1026
+ mergeable: "CONFLICTING",
1027
+ mergeStateStatus: "DIRTY",
1028
+ }
1029
+ : facts;
1030
+ },
1031
+ };
1032
+ };
1033
+ const watch = async (
1034
+ polling: Partial<PollingOptions>,
1035
+ statusOnly = false
1036
+ ) => {
1037
+ const clock = ticking();
1038
+ const emitted: ProgressVerdict[] = [];
1039
+ const verdict = await runSimple({
1040
+ dependencies: dependencies(lagging(), clock, emitted),
1041
+ contexts: [context(41)],
1042
+ mode: "single",
1043
+ statusOnly,
1044
+ options: { ...options, ...polling },
1045
+ });
1046
+ return { verdict, emitted: kinds(emitted) };
1047
+ };
1048
+
1049
+ it("retries until GitHub reports the pushed head, instead of reporting the previous head's conflict", async () => {
1050
+ const { verdict, emitted } = await watch({ expectedHead: pushed });
1051
+ expect(emitted.length).toBeGreaterThan(0);
1052
+ expect(emitted.every((kind) => kind === "RETRY")).toBe(true);
1053
+ expect(verdict).toMatchObject({ kind: "READY", exitCode: 0 });
1054
+ });
1055
+
1056
+ it("matches the pushed head by a short SHA", async () => {
1057
+ const { verdict } = await watch({ expectedHead: pushed.slice(0, 7) });
1058
+ expect(verdict).toMatchObject({ kind: "READY", exitCode: 0 });
1059
+ });
1060
+
1061
+ it("follows a later push once GitHub has reported the pushed head", async () => {
1062
+ const later = "cccc3333cccc3333cccc3333cccc3333cccc3333";
1063
+ const base = fakeReader({
1064
+ facts: { headRefOid: later },
1065
+ commitRollups: [
1066
+ { oid: pushed, state: null },
1067
+ { oid: later, state: "SUCCESS" },
1068
+ ],
1069
+ });
1070
+ let reads = 0;
1071
+ // The first snapshot sees the pushed head before GitHub has computed its
1072
+ // mergeability; a later push lands before the next poll.
1073
+ const moving: GitHubReader = {
1074
+ ...base,
1075
+ async pullRequest(requested) {
1076
+ reads += 1;
1077
+ const facts = await base.pullRequest(requested);
1078
+ return reads <= 2
1079
+ ? {
1080
+ ...facts,
1081
+ headRefOid: pushed,
1082
+ mergeable: "UNKNOWN",
1083
+ mergeStateStatus: "UNKNOWN",
1084
+ }
1085
+ : facts;
1086
+ },
1087
+ };
1088
+ const clock = ticking();
1089
+ const emitted: ProgressVerdict[] = [];
1090
+ const verdict = await runSimple({
1091
+ dependencies: dependencies(moving, clock, emitted),
1092
+ contexts: [context(41)],
1093
+ mode: "single",
1094
+ statusOnly: false,
1095
+ options: { ...options, expectedHead: pushed },
1096
+ });
1097
+ expect(kinds(emitted)).toEqual(["WAITING:mergeability-unknown"]);
1098
+ expect(verdict).toMatchObject({ kind: "READY", exitCode: 0 });
1099
+ });
1100
+
1101
+ it("gives a status-only read the pushed head's row", async () => {
1102
+ const { verdict, emitted } = await watch({ expectedHead: pushed }, true);
1103
+ expect(emitted.length).toBeGreaterThan(0);
1104
+ expect(emitted.every((kind) => kind === "RETRY")).toBe(true);
1105
+ expect(verdict).toMatchObject({
1106
+ kind: "STATUS",
1107
+ rows: [
1108
+ {
1109
+ kind: "open",
1110
+ facts: { headRefOid: pushed, mergeStateStatus: "CLEAN" },
1111
+ },
1112
+ ],
1113
+ });
1114
+ });
1115
+
1116
+ it("names both heads in the retry", async () => {
1117
+ await expect(
1118
+ readSnapshot({
1119
+ reader: lagging(),
1120
+ context: context(41),
1121
+ pendingHistory: "include",
1122
+ allowDraft: false,
1123
+ expectedHead: pushed,
1124
+ })
1125
+ ).rejects.toMatchObject({
1126
+ failure: {
1127
+ kind: "snapshot-changed",
1128
+ retryable: true,
1129
+ detail: `GitHub reports head ${previous}, not the expected head ${pushed}`,
1130
+ },
1131
+ });
1132
+ });
1133
+ });
@@ -165,12 +165,24 @@ export async function readSnapshot(args: {
165
165
  readonly allowDraft: boolean;
166
166
  readonly confirmNoChecks?: NoChecksConfirmer;
167
167
  readonly expectedApps?: readonly string[];
168
+ readonly expectedHead?: string;
168
169
  }): Promise<T.PrSnapshot> {
169
170
  const facts = await args.reader.pullRequest(args.context);
170
171
  if (facts.state === "MERGED" || facts.mergedAt !== null)
171
172
  return { kind: "merged", context: args.context, facts };
172
173
  if (facts.state === "CLOSED")
173
174
  return { kind: "closed", context: args.context, facts };
175
+ // For about 2 s after a push, GitHub still reports the previous head with
176
+ // that head's merge state and checks.
177
+ if (
178
+ args.expectedHead !== undefined &&
179
+ !facts.headRefOid.startsWith(args.expectedHead)
180
+ )
181
+ throw new WatcherQueryError({
182
+ kind: "snapshot-changed",
183
+ retryable: true,
184
+ detail: `GitHub reports head ${facts.headRefOid}, not the expected head ${args.expectedHead}`,
185
+ });
174
186
  const [threads, checks] = await Promise.all([
175
187
  resolveReviewThreads(args.reader, args.context),
176
188
  resolveHeadChecks(args.reader, facts, args.expectedApps),
@@ -586,6 +598,9 @@ export async function runSimple(args: {
586
598
  }): Promise<T.TerminalVerdict> {
587
599
  const stamp = verdictFactory(args.dependencies.clock, args.mode);
588
600
  const confirmNoChecks = noChecksConfirmer(args.dependencies.clock);
601
+ // --head waits out GitHub's lag after a push. Once a read has reported that
602
+ // head, the watch follows the PR, later pushes included.
603
+ let expectedHead = args.options.expectedHead;
589
604
  const step = async (): Promise<StepResult<T.TerminalVerdict>> => {
590
605
  const rows: T.PrSnapshot[] = [];
591
606
  for (const context of args.contexts)
@@ -597,8 +612,10 @@ export async function runSimple(args: {
597
612
  allowDraft: args.options.allowDraft,
598
613
  confirmNoChecks,
599
614
  expectedApps: args.options.expectedApps,
615
+ expectedHead,
600
616
  })
601
617
  );
618
+ expectedHead = undefined;
602
619
  const complete = nonEmpty(rows);
603
620
  if (complete === null) throw new Error("watch context cannot be empty");
604
621
  if (args.statusOnly)
@@ -499,4 +499,6 @@ export interface PollingOptions {
499
499
  readonly allowDraft: boolean;
500
500
  /** App slugs from --expect-app, whose queued suite with no runs counts as pending. */
501
501
  readonly expectedApps?: readonly string[];
502
+ /** The commit from --head, a full or short SHA; a read that reports another head retries. */
503
+ readonly expectedHead?: string;
502
504
  }