@a2f0/agent-tool 0.1.67 → 0.1.69

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.67",
3
+ "version": "0.1.69",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
package/src/config.ts CHANGED
@@ -135,8 +135,9 @@ export function parseConfig(source: string): AgentToolConfig {
135
135
  }
136
136
  const variants = object(result.review.opencodeVariants, "review.opencodeVariants");
137
137
  keys(variants, ["low", "medium", "high", "xhigh", "max"], "review.opencodeVariants");
138
- for (const value of Object.values(variants)) if (typeof value !== "string" || !/^[^\s]+$/.test(value)) invalid("review.opencodeVariants");
139
- if (typeof result.review.opencodeModel !== "string" || !/^[^\s/]+\/[^\s]+$/.test(result.review.opencodeModel)) invalid("review.opencodeModel");
138
+ // OpenCode 2 takes the model as provider/model#variant, so neither part may contain '#'.
139
+ for (const value of Object.values(variants)) if (typeof value !== "string" || !/^[^\s#]+$/.test(value)) invalid("review.opencodeVariants");
140
+ if (typeof result.review.opencodeModel !== "string" || !/^[^\s/#]+\/[^\s#]+$/.test(result.review.opencodeModel)) invalid("review.opencodeModel");
140
141
  if (!Number.isSafeInteger(result.review.timeoutMs) || result.review.timeoutMs < 1000 || result.review.timeoutMs > 3_600_000) invalid("review.timeoutMs");
141
142
  const packageDirs = (dirs: unknown): boolean => strings(dirs) && !dirs.some(dir => dir !== "." && (path.isAbsolute(dir) || dir.includes("\\") || dir.split("/").some(part => !part || part === "." || part === "..")));
142
143
  if (result.versions.packages !== null && !packageDirs(result.versions.packages)) invalid("versions.packages");
package/src/doctor.ts CHANGED
@@ -6,7 +6,8 @@ const specifications = [
6
6
  { name: "gh", help: ["pr", "checks", "--help"], flags: ["--json"] },
7
7
  { name: "claude", help: ["--help"], flags: ["--safe-mode", "--permission-mode", "--effort"] },
8
8
  { name: "codex", help: ["exec", "--help"], flags: ["--ignore-user-config", "--ignore-rules", "--strict-config", "--ephemeral", "--output-last-message"] },
9
- { name: "opencode", help: ["run", "--help"], flags: ["--pure", "--variant", "--agent"] },
9
+ // OpenCode 2: the variant rides in --model as provider/model#variant, and --standalone runs a private server.
10
+ { name: "opencode", help: ["run", "--help"], flags: ["--standalone", "--agent", "--archived", "provider/model#variant"] },
10
11
  ];
11
12
 
12
13
  /** Probe only local versions and flags; never launch a model or print credentials. */
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { retryGitHubResult } from "../system/githubRetry";
2
3
 
3
4
  interface CurrentBranchPr {
4
5
  readonly baseRefName: string;
@@ -18,18 +19,21 @@ interface CommandResult {
18
19
 
19
20
  type CommandRunner = (command: string, args: string[]) => CommandResult;
20
21
 
22
+ /** A read-only `gh` call, repeated after a transient network or server failure. */
21
23
  function runWithResult(command: string, args: string[]): CommandResult {
22
- const result = spawnSync(command, args, {
23
- encoding: "utf8",
24
- stdio: ["ignore", "pipe", "pipe"],
24
+ return retryGitHubResult(() => {
25
+ const result = spawnSync(command, args, {
26
+ encoding: "utf8",
27
+ stdio: ["ignore", "pipe", "pipe"],
28
+ });
29
+ const output = {
30
+ status: result.status,
31
+ signal: result.signal,
32
+ stderr: result.stderr,
33
+ stdout: result.stdout,
34
+ };
35
+ return result.error ? { ...output, error: result.error } : output;
25
36
  });
26
- const output = {
27
- status: result.status,
28
- signal: result.signal,
29
- stderr: result.stderr,
30
- stdout: result.stdout,
31
- };
32
- return result.error ? { ...output, error: result.error } : output;
33
37
  }
34
38
 
35
39
  function field(source: string, key: string): unknown {
@@ -1,6 +1,7 @@
1
1
  import { gitEnvironment } from "./environment";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { boundedExecFileSync } from "../system/boundedCalls";
4
+ import { retryGitHubRead } from "../system/githubRetry";
4
5
  import { randomUUID } from "node:crypto";
5
6
 
6
7
  import { viewCurrentBranchPr } from "./currentBranchPr";
@@ -39,9 +40,17 @@ export function run(command: string, args: string[]): string {
39
40
  }).trim();
40
41
  }
41
42
 
43
+ /**
44
+ * `run` for a read-only GitHub call: a transient network or server failure is
45
+ * repeated within `retryGitHubRead`'s budget. Never use it for a mutation.
46
+ */
47
+ export function runRead(command: string, args: string[]): string {
48
+ return retryGitHubRead(() => run(command, args));
49
+ }
50
+
42
51
  function tryRun(command: string, args: string[]): string | null {
43
52
  try {
44
- return run(command, args);
53
+ return runRead(command, args);
45
54
  } catch {
46
55
  return null;
47
56
  }
@@ -134,7 +143,7 @@ export function selectRepositoryGitUrl(
134
143
  }
135
144
 
136
145
  export function resolveRepositoryGitUrl(repo: string): string {
137
- const repoRaw = run("gh", ["repo", "view", repo, "--json", "url,sshUrl"]);
146
+ const repoRaw = runRead("gh", ["repo", "view", repo, "--json", "url,sshUrl"]);
138
147
  const httpsUrl = stringField(repoRaw, "url");
139
148
  const sshUrl = stringField(repoRaw, "sshUrl");
140
149
  let host = "";
@@ -334,7 +343,7 @@ export function findOpenPrNumber(branch: string, repo: string): string {
334
343
 
335
344
  /** Read a known-open PR's title and base identity from GitHub. */
336
345
  function viewPr(branch: string, repo: string, prNumber: string): PrView {
337
- const viewRaw = run("gh", [
346
+ const viewRaw = runRead("gh", [
338
347
  "pr",
339
348
  "view",
340
349
  prNumber,
@@ -406,7 +415,7 @@ function fetchPrView(): PrView {
406
415
  /** Current GitHub state of a PR (e.g. "OPEN", "MERGED", "CLOSED"). */
407
416
  export function prState(prNumber: string, repo: string): string {
408
417
  return stringField(
409
- run("gh", ["pr", "view", prNumber, "--json", "state", "-R", repo]),
418
+ runRead("gh", ["pr", "view", prNumber, "--json", "state", "-R", repo]),
410
419
  "state",
411
420
  );
412
421
  }
@@ -1,4 +1,4 @@
1
- import { run } from "../git/prContext";
1
+ import { run, runRead } from "../git/prContext";
2
2
 
3
3
  function field(value: unknown, key: string): unknown {
4
4
  return typeof value === "object" && value !== null
@@ -26,7 +26,7 @@ function strictStatusRule(rule: unknown): boolean {
26
26
  export function assertStrictBaseFreshness(
27
27
  repo: string,
28
28
  baseRef: string,
29
- read: typeof run = run,
29
+ read: typeof run = runRead,
30
30
  ): void {
31
31
  const where = `${repo}:${baseRef}`;
32
32
  let rulesetIds: unknown[];
@@ -1,4 +1,4 @@
1
- import { run } from "../git/prContext";
1
+ import { run, runRead } from "../git/prContext";
2
2
  import { loadConfig, type AgentToolConfig } from "../config";
3
3
 
4
4
  type CheckPolicy = Pick<AgentToolConfig["merge"], "requireChecks" | "requiredChecks">;
@@ -43,7 +43,7 @@ export function assertMergeChecks(source: string, expectedHead: string, policy:
43
43
  export function requirePassingMergeChecks(
44
44
  pr: { readonly prNumber: string; readonly repo: string },
45
45
  expectedHead: string,
46
- read: typeof run = run,
46
+ read: typeof run = runRead,
47
47
  policy: CheckPolicy = loadConfig().merge,
48
48
  ): void {
49
49
  // gh pr checks paginates and selects the latest run per workflow/job/event.
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
 
3
3
  import { loadConfig } from "../config";
4
- import { prState, resolvePr, run, spawnExitCode } from "../git/prContext";
4
+ import { prState, resolvePr, runRead, spawnExitCode } from "../git/prContext";
5
5
  import { assertStrictBaseFreshness } from "./baseFreshness";
6
6
  import { requirePassingMergeChecks } from "./mergeChecks";
7
7
  import {
@@ -120,7 +120,7 @@ export function resolvePullRequestMergeTarget(
120
120
  throw new Error(`Invalid repository slug '${pr.repo}'.`);
121
121
  }
122
122
  const [owner, name] = repoParts;
123
- const source = run("gh", [
123
+ const source = runRead("gh", [
124
124
  "api",
125
125
  "graphql",
126
126
  "-f",
@@ -167,6 +167,32 @@ export function buildSquashMergeArgs(
167
167
  ];
168
168
  }
169
169
 
170
+ /**
171
+ * After a failed merge mutation, read the PR's state once more and say whether
172
+ * the merge landed anyway, so nobody sends it again blindly. The mutation was
173
+ * bound to the reviewed head through `expectedHeadOid`; repeating `pr merge`
174
+ * reruns every gate first.
175
+ */
176
+ function reportFailedMerge(prNumber: string, repo: string): void {
177
+ let state: string;
178
+ try {
179
+ state = prState(prNumber, repo);
180
+ } catch (error) {
181
+ process.stderr.write(
182
+ `The merge mutation for PR #${prNumber} failed, and its state could not be read again: ${(error as Error).message}\n` +
183
+ "Check whether it merged before running pr merge again.\n",
184
+ );
185
+ return;
186
+ }
187
+ process.stderr.write(
188
+ state === "MERGED"
189
+ ? `The merge mutation for PR #${prNumber} reported a failure, but GitHub now reports the PR MERGED. ` +
190
+ "Do not merge again; confirm its merge commit and head before cleanup.\n"
191
+ : `The merge mutation for PR #${prNumber} failed and GitHub reports the PR ${state || "in an unknown state"}, so it did not merge. ` +
192
+ "Read the error above; running pr merge again repeats every gate first.\n",
193
+ );
194
+ }
195
+
170
196
  /**
171
197
  * Squash-merge the open PR for the current branch with a subject-only commit
172
198
  * message — no auto-generated body or extended message. The subject defaults to
@@ -212,6 +238,8 @@ export function squashMerge(
212
238
  );
213
239
  const exitCode = spawnExitCode("GitHub mergePullRequest mutation", result);
214
240
  if (exitCode !== 0) {
241
+ // Never sent twice: a mutation that failed in transit may still have merged.
242
+ reportFailedMerge(pr.prNumber, pr.repo);
215
243
  return exitCode;
216
244
  }
217
245
 
@@ -37,7 +37,7 @@ const OPENCODE_MODEL = DEFAULT_CONFIG.review.opencodeModel;
37
37
  const OPENCODE_REVIEW_AGENT = "agent-tool-review";
38
38
 
39
39
  /**
40
- * Map the shared effort vocabulary to a `--variant` deepseek-v4-pro accepts.
40
+ * Map the shared effort vocabulary to a variant deepseek-v4-pro accepts.
41
41
  * The skill's levels are `low | medium | high | xhigh | max`; this model's
42
42
  * variants are `low | medium | high | max`, so `xhigh` collapses onto `max`.
43
43
  */
@@ -67,6 +67,12 @@ export function resolveOpencodeVariant(
67
67
  * resolves it, because on macOS the temp dir is a symlink (`/var` →
68
68
  * `/private/var`) and the model may pass either spelling; a denied spelling
69
69
  * only costs the model a retry, but both spellings allowed costs nothing.
70
+ *
71
+ * OpenCode 2 normalizes this `permission` map into its ordered `permissions`
72
+ * rules, renaming `bash` to `shell` and `task` to `subagent` and keeping the
73
+ * order, so the default deny still precedes the allows; tools it added since,
74
+ * such as `browser`, fall under the default deny. `opencode debug agents
75
+ * --standalone` with the review's environment shows the effective rules.
70
76
  */
71
77
  export function buildOpencodeInlineConfig(snapshotRoot: string, model = OPENCODE_MODEL): string {
72
78
  const normalized = path.resolve(snapshotRoot).replaceAll("\\", "/");
@@ -105,27 +111,61 @@ export function buildOpencodeInlineConfig(snapshotRoot: string, model = OPENCODE
105
111
  }
106
112
 
107
113
  /**
108
- * Build the `opencode run` argv for a non-interactive review. The prompt goes
109
- * over stdin (opencode reads stdin when no message positional is given), so a
110
- * large diff never hits argv limits. `--pure` drops external plugins, and the
111
- * confinement itself lives in the inline config passed through the
112
- * environment: opencode has no per-run flag for permissions, and
113
- * `--dangerously-skip-permissions` would only *add* authority, never remove
114
- * it.
114
+ * Build the OpenCode 2 `opencode run` argv for a non-interactive review. The
115
+ * prompt goes over stdin (opencode reads stdin when no message positional is
116
+ * given), so a large diff never hits argv limits, and the variant rides in the
117
+ * model as `provider/model#variant`, OpenCode 2's replacement for `--variant`.
118
+ *
119
+ * `--standalone` is what keeps the confinement in force. By default `run`
120
+ * attaches to the shared background service, a server started earlier with its
121
+ * own environment and the user's global config, which never sees the inline
122
+ * config below: the reviewer agent would not exist there, or would not be
123
+ * confined. A standalone server is a private child that inherits this run's
124
+ * environment and working directory and exits with it. It also stands in for
125
+ * OpenCode 1's `--pure`: plugins load only from config, and the empty config
126
+ * directory with project config off leaves none to load. `--archived` keeps
127
+ * review sessions out of the user's session lists. Opencode has no per-run
128
+ * flag for permissions, and `--auto` would only *add* authority, never remove it.
115
129
  */
116
130
  export function buildOpencodeReviewArgs(variant: string, model = OPENCODE_MODEL): string[] {
117
131
  return [
118
132
  "run",
119
133
  "--model",
120
- model,
121
- "--variant",
122
- variant,
134
+ `${model}#${variant}`,
123
135
  "--agent",
124
136
  OPENCODE_REVIEW_AGENT,
125
- "--pure",
137
+ "--standalone",
138
+ "--archived",
126
139
  ];
127
140
  }
128
141
 
142
+ /**
143
+ * The reviewer's environment: the caller's, with the inline config and
144
+ * OpenCode's outside configuration turned off. `directory` is the empty,
145
+ * non-repository directory the reviewer runs in. OpenCode 2 takes a session's
146
+ * directory from `PWD` before its working directory, and an inherited `PWD`
147
+ * names the checkout agent-tool runs from, so `PWD` is pinned too. The same
148
+ * directory is the config directory, which in OpenCode 2 replaces the global
149
+ * `~/.config/opencode` (its config, plugins, and MCP servers) outright.
150
+ * Project config and Claude Code compatibility (`~/.claude` skills, config,
151
+ * and CLAUDE.md instructions) are off, both spellings of the project switch
152
+ * are set because the newer one takes precedence, and an inherited
153
+ * `OPENCODE_CONFIG`, which would load one more config file, is dropped.
154
+ */
155
+ export function buildOpencodeReviewEnv(env: ReviewerEnv, snapshotRoot: string, directory: string, model = OPENCODE_MODEL): ReviewerEnv {
156
+ const reviewEnv: ReviewerEnv = {
157
+ ...env,
158
+ PWD: directory,
159
+ OPENCODE_CONFIG_CONTENT: buildOpencodeInlineConfig(snapshotRoot, model),
160
+ OPENCODE_CONFIG_DIR: directory,
161
+ OPENCODE_CONFIG_PROJECT_DISABLE: "1",
162
+ OPENCODE_DISABLE_PROJECT_CONFIG: "1",
163
+ OPENCODE_DISABLE_CLAUDE_CODE: "1",
164
+ };
165
+ delete reviewEnv.OPENCODE_CONFIG;
166
+ return reviewEnv;
167
+ }
168
+
129
169
  /**
130
170
  * Run `opencode run` over an already-built review prompt and relay whatever it
131
171
  * prints to stdout — the final message alone, since run mode keeps its TUI
@@ -139,16 +179,17 @@ export function buildOpencodeReviewArgs(variant: string, model = OPENCODE_MODEL)
139
179
  * stderr tail is relayed so the error is still diagnosable (the Codex path
140
180
  * makes the same trade-off).
141
181
  *
142
- * The reviewer runs from a fresh, empty, non-repository cwd so nothing
143
- * branch-controlled loads: not the snapshot's `AGENTS.md` or `opencode.json`,
144
- * and not its `.opencode/` directory. `OPENCODE_CONFIG_DIR` points at that
145
- * same empty directory so no user-defined agents, commands, or plugins from
146
- * `~/.config/opencode` ride along either; `--pure` additionally disables
147
- * external plugins. That directory is *config* only: opencode's credentials
148
- * live in its data directory (`~/.local/share/opencode/auth.json` on macOS),
149
- * which `OPENCODE_CONFIG_DIR` does not touch, so the deepseek auth the review
150
- * needs still resolves. Global config still loads, but the inline config's
151
- * agent-scoped deny rules take precedence over whatever it sets.
182
+ * The reviewer runs on a private standalone server from a fresh, empty,
183
+ * non-repository directory (`buildOpencodeReviewEnv`), so nothing
184
+ * branch-controlled loads: not the snapshot's or checkout's `AGENTS.md` or
185
+ * `opencode.json`, and not a `.opencode/` directory. `OPENCODE_CONFIG_DIR`
186
+ * points at that same empty directory, so no user-defined agents, commands,
187
+ * plugins, or MCP servers from `~/.config/opencode` ride along either. That
188
+ * directory is *config* only: opencode's credentials live in its data
189
+ * directory (`~/.local/share/opencode/auth.json` on macOS), which
190
+ * `OPENCODE_CONFIG_DIR` does not touch, so the provider auth the review needs
191
+ * still resolves. Skills in `~/.agents/skills` are still discovered, but the
192
+ * inline config denies the skill tool and every read outside the snapshot.
152
193
  */
153
194
  export async function spawnOpencodeReview(
154
195
  prompt: string,
@@ -176,11 +217,7 @@ export async function spawnOpencodeReview(
176
217
  // Neutral cwd: opencode would otherwise load the snapshot's
177
218
  // branch-controlled config and instructions into the reviewer.
178
219
  cwd: outDir,
179
- env: {
180
- ...env,
181
- OPENCODE_CONFIG_CONTENT: buildOpencodeInlineConfig(snapshotRoot, model),
182
- OPENCODE_CONFIG_DIR: outDir,
183
- },
220
+ env: buildOpencodeReviewEnv(env, snapshotRoot, outDir, model),
184
221
  },
185
222
  ));
186
223
  const exitCode = spawnExitCode("opencode", result);
@@ -18,6 +18,11 @@ export async function withCallDeadline<T>(until: number, inspect: () => T | Prom
18
18
  return await deadlines.run(until, inspect);
19
19
  }
20
20
 
21
+ /** The deadline of the wait running the current call, or undefined outside every wait. */
22
+ export function callDeadline(): number | undefined {
23
+ return deadlines.getStore();
24
+ }
25
+
21
26
  function currentLimit(): number | undefined {
22
27
  const deadline = deadlines.getStore();
23
28
  if (deadline === undefined) return undefined;
@@ -0,0 +1,116 @@
1
+ import { callDeadline } from "./boundedCalls";
2
+
3
+ /**
4
+ * The retry budget for a GitHub call that failed transiently: `attempts` calls
5
+ * in all, sleeping `initialDelayMs` before the first retry and doubling up to
6
+ * `maxDelayMs`, so 1, 2, then 4 seconds by default. Mutable for tests.
7
+ */
8
+ export const GITHUB_RETRY = { attempts: 4, initialDelayMs: 1_000, maxDelayMs: 8_000 };
9
+
10
+ // The same request would fail the same way: authentication, permissions,
11
+ // validation, absent objects, and rate limits. These win over any transient match.
12
+ const PERMANENT = /\bHTTP 4\d\d\b|gh auth login|authentication|bad credentials|not found|could not resolve to|rate limit/i;
13
+ // Network failures and server errors that a later call commonly survives, as
14
+ // Go's HTTP client and GitHub report them through `gh`.
15
+ const TRANSIENT = [
16
+ /i\/o timeout/i,
17
+ /connection reset/i,
18
+ /broken pipe/i,
19
+ /\bEOF\b/,
20
+ /TLS handshake timeout/i,
21
+ /context deadline exceeded|Client\.Timeout exceeded/i,
22
+ /\bHTTP 50[234]\b/,
23
+ // GraphQL's own server-side timeout, reported with HTTP 200.
24
+ /Something went wrong while executing your query/i,
25
+ ];
26
+
27
+ /** The failure output to classify: a command's stderr when it has any, else the error's message. */
28
+ function failureText(failure: unknown): string {
29
+ if (typeof failure === "string") return failure;
30
+ const stderr: unknown = typeof failure === "object" && failure !== null ? Reflect.get(failure, "stderr") : undefined;
31
+ const text = typeof stderr === "string" ? stderr : Buffer.isBuffer(stderr) ? stderr.toString("utf8") : "";
32
+ if (text.trim()) return text;
33
+ return failure instanceof Error ? failure.message : String(failure);
34
+ }
35
+
36
+ /** Whether a failed GitHub call is worth repeating: a network or server error, never a client error. */
37
+ export function transientGitHubFailure(failure: unknown): boolean {
38
+ const text = failureText(failure);
39
+ return !PERMANENT.test(text) && TRANSIENT.some(pattern => pattern.test(text));
40
+ }
41
+
42
+ /** A GitHub call that still failed transiently once its retry budget, or its wait's deadline, ran out. */
43
+ export class TransientGitHubError extends Error {
44
+ constructor(readonly attempts: number, cause: unknown) {
45
+ const message = cause instanceof Error ? cause.message : failureText(cause);
46
+ super(`${message.trimEnd()}\nGitHub failed transiently on all ${attempts} attempt(s); try again once it is reachable.`, { cause });
47
+ this.name = "TransientGitHubError";
48
+ }
49
+ }
50
+
51
+ /**
52
+ * The pause before retry number `retry` (1-based), or null when the budget is
53
+ * spent or the pause would end past the deadline of the wait making the call,
54
+ * so retries never stretch a wait beyond its timeout.
55
+ */
56
+ function retryDelay(retry: number): number | null {
57
+ if (retry >= GITHUB_RETRY.attempts) return null;
58
+ const delay = Math.min(GITHUB_RETRY.maxDelayMs, GITHUB_RETRY.initialDelayMs * 2 ** (retry - 1));
59
+ const deadline = callDeadline();
60
+ return deadline !== undefined && Date.now() + delay >= deadline ? null : delay;
61
+ }
62
+
63
+ type Outcome<T> = { ok: true; value: T } | { ok: false; error: unknown };
64
+
65
+ function repeat<T>(call: () => T, transient: (outcome: Outcome<T>) => boolean): { outcome: Outcome<T>; attempts: number } {
66
+ for (let attempts = 1; ; attempts++) {
67
+ let outcome: Outcome<T>;
68
+ try { outcome = { ok: true, value: call() }; } catch (error) { outcome = { ok: false, error }; }
69
+ const delay = transient(outcome) ? retryDelay(attempts) : null;
70
+ if (delay === null) return { outcome, attempts };
71
+ Bun.sleepSync(delay);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Run a read-only GitHub call, repeating it after a transient failure within
77
+ * the budget. A client error is thrown at once; a transient failure that
78
+ * outlasts the budget is thrown as `TransientGitHubError`. Never pass a
79
+ * mutation: a request that failed in transit may still have taken effect.
80
+ */
81
+ export function retryGitHubRead<T>(read: () => T): T {
82
+ const { outcome, attempts } = repeat(read, result => !result.ok && transientGitHubFailure(result.error));
83
+ if (outcome.ok) return outcome.value;
84
+ throw transientGitHubFailure(outcome.error) ? new TransientGitHubError(attempts, outcome.error) : outcome.error;
85
+ }
86
+
87
+ /**
88
+ * `retryGitHubRead` for a runner that reports failure in its result, as
89
+ * `spawnSync` does, rather than by throwing. Once the budget runs out the last
90
+ * result is returned for the caller to report as before.
91
+ */
92
+ export function retryGitHubResult<T extends { status: number | null; stderr?: string | null }>(read: () => T): T {
93
+ const { outcome } = repeat(read, result => result.ok && result.value.status !== 0 && transientGitHubFailure(result.value.stderr ?? ""));
94
+ if (outcome.ok) return outcome.value;
95
+ throw outcome.error;
96
+ }
97
+
98
+ /**
99
+ * Send a mutation that is safe to repeat only once its preconditions are read
100
+ * again. After a transient failure and the backoff pause, `recheck` rereads
101
+ * them: it throws when they no longer hold, returns true when the failed
102
+ * attempt already took effect, and false to send the mutation again. Any other
103
+ * failure propagates at once, and the last transient one as
104
+ * `TransientGitHubError`.
105
+ */
106
+ export function retryCheckedGitHubMutation(mutate: () => void, recheck: () => boolean): void {
107
+ for (let attempts = 1; ; attempts++) {
108
+ try { mutate(); return; } catch (error) {
109
+ if (!transientGitHubFailure(error)) throw error;
110
+ const delay = retryDelay(attempts);
111
+ if (delay === null) throw new TransientGitHubError(attempts, error);
112
+ Bun.sleepSync(delay);
113
+ if (recheck()) return;
114
+ }
115
+ }
116
+ }
@@ -1,5 +1,6 @@
1
1
  import { loadConfig, type RequiredCheck } from "../config";
2
- import { assert, json, nativeBranch, option, output, read, repository } from "./core";
2
+ import { runRead } from "../git/prContext";
3
+ import { assert, json, nativeBranch, option, output, repository } from "./core";
3
4
 
4
5
  /** The health of a branch's tip: one of four closed states. */
5
6
  export type BaseHealthStatus = "green" | "red" | "pending" | "no-ci";
@@ -113,7 +114,7 @@ export function baseHealthCommand(args: string[]): number {
113
114
  const required = loadConfig().merge.requiredChecks;
114
115
  // Every page, one entry per line, so a failing required check is never past the first page. Required
115
116
  // checks are check runs or, for external CI, commit status contexts; the combined status keeps each context's latest.
116
- const lines = (args: string[]) => read("gh", args).split("\n").filter(Boolean).map(line => JSON.parse(line) as CheckRun);
117
+ const lines = (args: string[]) => runRead("gh", args).split("\n").filter(Boolean).map(line => JSON.parse(line) as CheckRun);
117
118
  const checkRuns: CheckRun[] = required.length ? [
118
119
  ...lines(["api", "--paginate", `repos/${name}/commits/${tip}/check-runs?per_page=100`, "--jq", ".check_runs[] | {name, status, conclusion, url: .html_url}"]),
119
120
  ...lines(["api", "--paginate", `repos/${name}/commits/${tip}/status?per_page=100`, "--jq", '.statuses[] | {name: .context, status: (if .state == "pending" then "in_progress" else "completed" end), conclusion: (if .state == "success" then "success" elif .state == "pending" then null else .state end), url: .target_url}']),
@@ -127,7 +128,7 @@ export function baseHealthCommand(args: string[]): number {
127
128
  if (status === "no-ci") notes.push(`No push-triggered workflow ran on ${branch} within the last ${limit} runs; this repository lacks CI on pushes to it.`);
128
129
  else if (!tipHasRuns) notes.push(`No push run has started on the tip yet, or path filters skipped it; workflows show their latest run on ${branch}.`);
129
130
  const failingRuns = latest.filter(run => outcome(run.status, run.conclusion) === "failing");
130
- const failingJobs: FailingJob[] = failingRuns.flatMap(run => read("gh", ["api", "--paginate", `repos/${name}/actions/runs/${run.id}/jobs?per_page=100`, "--jq", ".jobs[] | {id, name, status, conclusion, url: .html_url}"]).split("\n").filter(Boolean).map(line => JSON.parse(line) as Job)
131
+ const failingJobs: FailingJob[] = failingRuns.flatMap(run => runRead("gh", ["api", "--paginate", `repos/${name}/actions/runs/${run.id}/jobs?per_page=100`, "--jq", ".jobs[] | {id, name, status, conclusion, url: .html_url}"]).split("\n").filter(Boolean).map(line => JSON.parse(line) as Job)
131
132
  .filter(job => outcome(job.status, job.conclusion) === "failing")
132
133
  .map(job => ({ workflow: run.name, runId: run.id, runUrl: run.url, headOid: run.headSha, job: job.name, jobId: job.id, url: job.url, conclusion: job.conclusion })));
133
134
  // A failing required check outside those runs (another app, or a run beyond the window) is listed by its own link.
@@ -2,7 +2,9 @@ import { spawnSync } from "node:child_process";
2
2
  import { lstatSync, realpathSync, writeSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { gitEnvironment } from "../git/environment";
5
+ import { runRead } from "../git/prContext";
5
6
  import { boundedExecFileSync, withCallDeadline } from "../system/boundedCalls";
7
+ import { TransientGitHubError } from "../system/githubRetry";
6
8
 
7
9
  export function output(value: unknown): void { writeSync(1, `${JSON.stringify(value, null, 2)}\n`); }
8
10
  export function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); }
@@ -11,7 +13,8 @@ export function read(command: string, args: string[], cwd = process.cwd()): stri
11
13
  return boundedExecFileSync(command, args, { cwd, env: gitEnvironment(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trimEnd();
12
14
  }
13
15
  export function git(args: string[], cwd = process.cwd()): string { return read("git", args, cwd); }
14
- export function json<T>(args: string[]): T { return JSON.parse(read("gh", args)) as T; }
16
+ /** A read-only `gh` call's JSON output; transient failures are retried (`runRead`), so never pass a mutation. */
17
+ export function json<T>(args: string[]): T { return JSON.parse(runRead("gh", args)) as T; }
15
18
  /**
16
19
  * Mutating Git commands deliberately retain normal hooks and their environment.
17
20
  * This one streams Git's and its hooks' output to stderr for commands people
@@ -110,13 +113,23 @@ export function timeoutOptions(args: string[], defaultSeconds = 900): { timeoutM
110
113
  assert(Number.isFinite(seconds) && seconds >= 0 && seconds <= 86400 && Number.isFinite(interval) && interval >= 1 && interval <= 60, "Timeout must be 0–86400 seconds and interval 1–60 seconds.");
111
114
  return { timeoutMs: seconds * 1000, intervalMs: interval * 1000 };
112
115
  }
116
+ /**
117
+ * Inspect until done or the deadline passes. An inspection whose GitHub read
118
+ * still failed transiently after its retries is a missed observation rather
119
+ * than a failed wait while time remains; at the deadline its error is thrown.
120
+ */
113
121
  export async function poll<T>(inspect: () => { done: boolean; value: T } | Promise<{ done: boolean; value: T }>, options: { timeoutMs: number; intervalMs: number }): Promise<T> {
114
122
  const deadline = Date.now() + options.timeoutMs;
115
123
  while (true) {
116
- // Each external call inside an inspection is bounded too, so a hung one cannot outlast the wait.
117
- const result = await withCallDeadline(deadline, inspect);
118
- if (result.done) return result.value;
119
- assert(Date.now() < deadline, `Timed out waiting: ${JSON.stringify(result.value)} Pass --timeout <seconds> to wait longer.`);
124
+ let result: { done: boolean; value: T } | undefined;
125
+ try {
126
+ // Each external call inside an inspection is bounded too, so a hung one cannot outlast the wait.
127
+ result = await withCallDeadline(deadline, inspect);
128
+ } catch (error) {
129
+ if (!(error instanceof TransientGitHubError) || Date.now() >= deadline) throw error;
130
+ }
131
+ if (result?.done) return result.value;
132
+ if (result) assert(Date.now() < deadline, `Timed out waiting: ${JSON.stringify(result.value)} Pass --timeout <seconds> to wait longer.`);
120
133
  await new Promise(resolve => setTimeout(resolve, Math.min(options.intervalMs, deadline - Date.now())));
121
134
  }
122
135
  }
@@ -10,7 +10,7 @@ import { assertStrictBaseFreshness } from "../pr/baseFreshness";
10
10
  import { baseFreshness, behindReason, cancelRuns } from "./prFreshness";
11
11
  import { resolvePullRequestMergeTarget, squashMerge } from "../pr/squashMerge";
12
12
  import { planVersions } from "../version/bumpVersions";
13
- import { assert, clean, currentBranch, git, head, json, oid, option, flag, output, poll, timeoutOptions } from "./core";
13
+ import { assert, clean, currentBranch, git, head, json, oid, option, flag, output, poll, read, timeoutOptions } from "./core";
14
14
 
15
15
  export interface PullRequest {
16
16
  number: number; url: string; state: string; title: string; headRefName: string; headRefOid: string;
@@ -157,8 +157,10 @@ export function mergeReviewedHead(rootDir: string, subject: string | undefined,
157
157
  interface Comment { id: string; databaseId: number; body: string; url: string; author: { login: string } | null }
158
158
  interface Page<T> { nodes: T[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
159
159
  interface Thread { id: string; isResolved: boolean; isOutdated: boolean; path: string; line: number | null; comments: Page<Comment> }
160
- function graphql<T>(query: string, variables: Record<string, string | number>): T {
161
- const response = json<{ data?: T; errors?: unknown[] }>(["api", "graphql", "-f", `query=${query}`, ...Object.entries(variables).flatMap(([key, value]) => [typeof value === "number" ? "-F" : "-f", `${key}=${value}`])]);
160
+ /** A GraphQL query, retried after a transient failure, or a mutation, which is sent once. */
161
+ function graphql<T>(query: string, variables: Record<string, string | number>, mutation = false): T {
162
+ const args = ["api", "graphql", "-f", `query=${query}`, ...Object.entries(variables).flatMap(([key, value]) => [typeof value === "number" ? "-F" : "-f", `${key}=${value}`])];
163
+ const response = (mutation ? JSON.parse(read("gh", args)) : json(args)) as { data?: T; errors?: unknown[] };
162
164
  assert(response.data && !response.errors?.length, "GitHub GraphQL response was incomplete.");
163
165
  return response.data;
164
166
  }
@@ -207,7 +209,7 @@ function threadsCommand(args: string[]): number {
207
209
  const thread = reviewThreads(identity).find(thread => thread.id === args[0]);
208
210
  assert(thread, "Thread does not belong to this PR.");
209
211
  if (thread.isResolved) { output({ id: thread.id, isResolved: true, changed: false }); return 0; }
210
- output(graphql("mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id isResolved}}}", { id: thread.id })); return 0;
212
+ output(graphql("mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id isResolved}}}", { id: thread.id }, true)); return 0;
211
213
  }
212
214
 
213
215
  export async function prWorkflowCommand(args: string[]): Promise<number> {
@@ -2,7 +2,8 @@ import { spawnSync } from "node:child_process";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { loadConfig } from "../config";
5
- import { remoteBranchHead, resolveFreshBaseRef, resolveRepositoryGitUrl } from "../git/prContext";
5
+ import { remoteBranchHead, resolveFreshBaseRef, resolveRepositoryGitUrl, runRead } from "../git/prContext";
6
+ import { retryCheckedGitHubMutation, retryGitHubResult } from "../system/githubRetry";
6
7
  import { viewCurrentBranchPr } from "../git/currentBranchPr";
7
8
  import { assert, clean, currentBranch, flag, git, head, mutateGitCaptured, oid, output, read, repository } from "./core";
8
9
  import { pullRequest } from "./pr";
@@ -46,12 +47,13 @@ export function repoCommand(args: string[]): number {
46
47
  const url = resolveRepositoryGitUrl(repo.nameWithOwner);
47
48
  const remoteFeature = remoteBranchHead(url, pr.headRefName);
48
49
  assert(!remoteFeature || remoteFeature === shipped, "Remote feature branch moved beyond the shipped HEAD.");
49
- const plan = { repo: repo.nameWithOwner, pr: pr.number, mergeOid: pr.mergeCommit.oid, shippedHead: shipped, defaultBranch, featureBranch: pr.headRefName, keepBranch: keep };
50
+ const mergeOid = pr.mergeCommit.oid;
51
+ const plan = { repo: repo.nameWithOwner, pr: pr.number, mergeOid, shippedHead: shipped, defaultBranch, featureBranch: pr.headRefName, keepBranch: keep };
50
52
  if (!apply) { output({ ...plan, applied: false }); return 0; }
51
53
  const completed: string[] = [];
52
54
  try {
53
55
  const defaultOid = resolveFreshBaseRef(repo.nameWithOwner, defaultBranch);
54
- assert(git(["merge-base", defaultOid, pr.mergeCommit.oid]) === pr.mergeCommit.oid, "Default branch does not contain the confirmed merge commit.");
56
+ assert(git(["merge-base", defaultOid, mergeOid]) === mergeOid, "Default branch does not contain the confirmed merge commit.");
55
57
  const localDefault = spawnSync("git", ["rev-parse", "--verify", `refs/heads/${defaultBranch}`], { encoding: "utf8" });
56
58
  if (localDefault.status === 0) {
57
59
  assert(git(["merge-base", localDefault.stdout.trim(), defaultOid]) === localDefault.stdout.trim(), "Local default branch diverged; preserve it for inspection.");
@@ -69,7 +71,14 @@ export function repoCommand(args: string[]): number {
69
71
  assert(!live || live === shipped, "Remote feature branch changed before deletion.");
70
72
  if (live) {
71
73
  // REST avoids pre-push hooks. GitHub has no expected-OID delete guard.
72
- read("gh", ["api", "--method", "DELETE", `repos/${repo.nameWithOwner}/git/refs/heads/${encodeURIComponent(pr.headRefName)}`]);
74
+ retryCheckedGitHubMutation(() => { read("gh", ["api", "--method", "DELETE", `repos/${repo.nameWithOwner}/git/refs/heads/${encodeURIComponent(pr.headRefName)}`]); }, () => {
75
+ // A delete that failed in transit may have landed: confirm the merge and the ref again before resending it.
76
+ const current = pullRequest(args[0], repo.nameWithOwner);
77
+ assert(current.state === "MERGED" && current.headRefOid === shipped && current.mergeCommit?.oid === mergeOid, "PR is no longer confirmed MERGED at the shipped HEAD; not retrying the remote branch deletion.");
78
+ const remote = remoteBranchHead(url, pr.headRefName);
79
+ assert(!remote || remote === shipped, "Remote feature branch changed before deletion.");
80
+ return !remote;
81
+ });
73
82
  completed.push("deleted-remote-branch");
74
83
  }
75
84
  }
@@ -81,8 +90,8 @@ export function policyCommand(args: string[]): number {
81
90
  assert(args.length === 1 && args[0] === "check", "Usage: policy check");
82
91
  const repo = repository();
83
92
  const branch = repo.defaultBranchRef.name;
84
- const rules = read("gh", ["api", "--paginate", `repos/${repo.nameWithOwner}/rules/branches/${encodeURIComponent(branch)}`, "--jq", ".[]"]).split("\n").filter(Boolean).map((line): unknown => JSON.parse(line));
85
- const protection = spawnSync("gh", ["api", `repos/${repo.nameWithOwner}/branches/${encodeURIComponent(branch)}/protection`], { encoding: "utf8" });
93
+ const rules = runRead("gh", ["api", "--paginate", `repos/${repo.nameWithOwner}/rules/branches/${encodeURIComponent(branch)}`, "--jq", ".[]"]).split("\n").filter(Boolean).map((line): unknown => JSON.parse(line));
94
+ const protection = retryGitHubResult(() => spawnSync("gh", ["api", `repos/${repo.nameWithOwner}/branches/${encodeURIComponent(branch)}/protection`], { encoding: "utf8" }));
86
95
  assert(protection.status === 0 || /HTTP 404/.test(protection.stderr), "Could not read classic branch protection.");
87
96
  const classic = protection.status === 0 ? JSON.parse(protection.stdout) as { required_status_checks?: { contexts?: string[]; checks?: { context: string }[]; strict?: boolean } } : null;
88
97
  const required = new Set<string>(classic?.required_status_checks?.contexts ?? []);