@a2f0/agent-tool 0.1.78 → 0.1.79

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.78",
3
+ "version": "0.1.79",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -2,6 +2,7 @@ import { gitEnvironment } from "./environment";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { boundedExecFileSync } from "../system/boundedCalls";
4
4
  import { retryGitHubRead } from "../system/githubRetry";
5
+ import { outputTail } from "../system/outputTail";
5
6
  import { randomUUID } from "node:crypto";
6
7
 
7
8
  import { viewCurrentBranchPr } from "./currentBranchPr";
@@ -41,8 +42,10 @@ export function run(command: string, args: string[]): string {
41
42
  }
42
43
 
43
44
  /**
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.
45
+ * `run` for a read-only GitHub call, through `gh` or Git's transport
46
+ * (`ls-remote`, `fetch`): a transient network, SSH, or server failure is
47
+ * repeated within `retryGitHubRead`'s budget. Never use it for a mutation,
48
+ * such as a push or a merge.
46
49
  */
47
50
  export function runRead(command: string, args: string[]): string {
48
51
  return retryGitHubRead(() => run(command, args));
@@ -168,13 +171,16 @@ export function parseRemoteBranchHead(
168
171
  return null;
169
172
  }
170
173
 
171
- /** The commit a branch points to on the repository, or null when absent. */
174
+ /**
175
+ * The commit a branch points to on the repository, or null when absent. The
176
+ * listing is read-only, so a transient SSH or network failure is retried.
177
+ */
172
178
  export function remoteBranchHead(
173
179
  repositoryUrl: string,
174
180
  branch: string,
175
181
  ): string | null {
176
182
  return parseRemoteBranchHead(
177
- run("git", ["ls-remote", "--heads", repositoryUrl, `refs/heads/${branch}`]),
183
+ runRead("git", ["ls-remote", "--heads", repositoryUrl, `refs/heads/${branch}`]),
178
184
  branch,
179
185
  );
180
186
  }
@@ -194,19 +200,28 @@ export function buildBaseFetchArgs(
194
200
  ];
195
201
  }
196
202
 
197
- function fetchBase(repositoryUrl: string, target: string): string {
203
+ /**
204
+ * Fetch `target` into a private ref and return its commit. The fetch only
205
+ * reads the repository, so a transient SSH or network failure is retried
206
+ * within `retryGitHubRead`'s budget; Git's stderr explains a final failure.
207
+ */
208
+ export function fetchBase(repositoryUrl: string, target: string): string {
198
209
  const temporaryRef = `refs/codex/review-base/${process.pid}-${randomUUID()}`;
199
210
  try {
200
- const result = spawnSync(
201
- "git",
202
- buildBaseFetchArgs(repositoryUrl, target, temporaryRef),
203
- { stdio: "ignore", env: gitEnvironment() },
204
- );
205
- if (spawnExitCode("git fetch", result) !== 0) {
206
- throw new Error(
207
- `Could not fetch base '${target}' from '${repositoryUrl}'.`,
211
+ retryGitHubRead(() => {
212
+ const result = spawnSync(
213
+ "git",
214
+ buildBaseFetchArgs(repositoryUrl, target, temporaryRef),
215
+ { stdio: ["ignore", "ignore", "pipe"], encoding: "utf8", env: gitEnvironment() },
208
216
  );
209
- }
217
+ if (spawnExitCode("git fetch", result) === 0) return;
218
+ const stderr = result.stderr ?? "";
219
+ const detail = outputTail(stderr);
220
+ // The retry classifies Git's whole stderr when there is any, rather than this bounded message.
221
+ throw Object.assign(new Error(
222
+ `Could not fetch base '${target}' from '${repositoryUrl}'${detail ? `: ${detail}` : "."}`,
223
+ ), { stderr });
224
+ });
210
225
  return run("git", ["rev-parse", `${temporaryRef}^{commit}`]);
211
226
  } finally {
212
227
  spawnSync("git", ["update-ref", "-d", temporaryRef], {
@@ -8,12 +8,17 @@ import { callDeadline } from "./boundedCalls";
8
8
  export const GITHUB_RETRY = { attempts: 4, initialDelayMs: 1_000, maxDelayMs: 8_000 };
9
9
 
10
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;
11
+ // validation, absent objects, and rate limits, as `gh` reports them and as
12
+ // OpenSSH and GitHub's SSH endpoint report them to Git ("git@github.com:
13
+ // Permission denied (publickey).", "Host key verification failed.", "ERROR:
14
+ // Repository not found."). These win over any transient match.
15
+ const PERMANENT = /\bHTTP 4\d\d\b|gh auth login|authentication|bad credentials|not found|could not resolve to|rate limit|permission denied|host key verification failed/i;
13
16
  // Network failures and server errors that a later call commonly survives, as
14
- // Go's HTTP client and GitHub report them through `gh`.
17
+ // Go's HTTP client and GitHub report them through `gh`, and as OpenSSH reports
18
+ // them to Git.
15
19
  const TRANSIENT = [
16
20
  /i\/o timeout/i,
21
+ // Also OpenSSH's "read: Connection reset by peer" and "Connection reset by <ip> port <n>".
17
22
  /connection reset/i,
18
23
  /broken pipe/i,
19
24
  /\bEOF\b/,
@@ -22,6 +27,21 @@ const TRANSIENT = [
22
27
  /\bHTTP 50[234]\b/,
23
28
  // GraphQL's own server-side timeout, reported with HTTP 200.
24
29
  /Something went wrong while executing your query/i,
30
+ // OpenSSH (sshconnect.c, kex.c, packet.c, clientloop.c, ssh.c): a connect or
31
+ // banner exchange that timed out ("ssh: connect to host <host> port <n>:
32
+ // Operation timed out", strerror(ETIMEDOUT) on macOS and the BSDs, which
33
+ // Linux spells "Connection timed out"; "Connection timed out during banner
34
+ // exchange"; "Connection to <ip> port <n> timed out"), a server that closed
35
+ // the connection ("kex_exchange_identification: Connection closed by remote
36
+ // host", "Connection closed by <ip> port <n>", "Connection to <host> closed
37
+ // by remote host."), and a name lookup the resolver calls temporary. Git then
38
+ // prints "Could not read from remote repository." after every SSH failure, so
39
+ // that line decides nothing on its own: a permission or absence error before
40
+ // it stays permanent.
41
+ /\b(?:Operation|Connection) timed out\b/i,
42
+ /\bConnection to \S+ port \d+ timed out\b/,
43
+ /\bConnection (?:to \S+ )?closed by (?:remote host|\S+ port \d+)/,
44
+ /\bTemporary failure in name resolution\b/i,
25
45
  ];
26
46
 
27
47
  /** The failure output to classify: a command's stderr when it has any, else the error's message. */
@@ -73,10 +93,11 @@ function repeat<T>(call: () => T, transient: (outcome: Outcome<T>) => boolean):
73
93
  }
74
94
 
75
95
  /**
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.
96
+ * Run a read-only GitHub call, through `gh` or Git's transport (`ls-remote`,
97
+ * `fetch`), repeating it after a transient failure within the budget. A
98
+ * client error is thrown at once; a transient failure that outlasts the
99
+ * budget is thrown as `TransientGitHubError`. Never pass a mutation, such as
100
+ * a push: a request that failed in transit may still have taken effect.
80
101
  */
81
102
  export function retryGitHubRead<T>(read: () => T): T {
82
103
  const { outcome, attempts } = repeat(read, result => !result.ok && transientGitHubFailure(result.error));
@@ -0,0 +1,5 @@
1
+ /** The last lines of a command's output, bounded for an error message. */
2
+ export function outputTail(text: string, lines = 20, characters = 2000): string {
3
+ const tail = text.trim().split("\n").slice(-lines).join("\n");
4
+ return tail.length > characters ? `…${tail.slice(-characters)}` : tail;
5
+ }
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { loadConfig, type AgentToolConfig } from "../config";
4
4
  import { remoteBranchHead } from "../git/prContext";
5
5
  import { gitEnvironment } from "../git/environment";
6
+ import { retryGitHubRead } from "../system/githubRetry";
6
7
  import { assert, clean, currentBranch, flag, git, head, mutateGit, mutateGitCaptured, nativeBranch, oid, option, output, repository } from "./core";
7
8
 
8
9
  export function branchErrors(name: string, config: AgentToolConfig): string[] {
@@ -73,7 +74,8 @@ export function branchCommand(args: string[]): number {
73
74
  if (pushUrl !== url) assert(!remoteBranchHead(pushUrl, name), `Push destination branch '${name}' already exists.`);
74
75
  const baseOid = remoteBranchHead(url, base);
75
76
  assert(baseOid, `Remote base '${base}' does not exist.`);
76
- git(["fetch", "--no-tags", remote, `refs/heads/${base}`]);
77
+ // Read-only on the remote, so a transient SSH or network failure is retried, unlike `branch push`'s push.
78
+ retryGitHubRead(() => git(["fetch", "--no-tags", remote, `refs/heads/${base}`]));
77
79
  assert(git(["rev-parse", "FETCH_HEAD"]) === baseOid && remoteBranchHead(url, base) === baseOid, "Base moved while fetching; retry creation.");
78
80
  mutateGitCaptured(["switch", "--no-track", "-c", name, oid(baseOid)]);
79
81
  assert(currentBranch() === name && head() === baseOid, "Checkout changed during branch creation.");
@@ -87,6 +89,7 @@ export function branchCommand(args: string[]): number {
87
89
  clean();
88
90
  assert(head() === expected, "HEAD differs from the reviewed commit.");
89
91
  const url = remoteUrl(remote, true);
92
+ // Sent once, never retried: a push that failed in transit may still have landed.
90
93
  mutateGit(["push", "--set-upstream", remote, `HEAD:refs/heads/${branch}`]);
91
94
  assert(head() === expected && currentBranch() === branch && remoteBranchHead(url, branch) === expected, "Push changed local or remote HEAD; review the resulting commit before shipping.");
92
95
  clean();
@@ -5,6 +5,7 @@ import { gitEnvironment } from "../git/environment";
5
5
  import { runRead } from "../git/prContext";
6
6
  import { boundedExecFileSync, withCallDeadline } from "../system/boundedCalls";
7
7
  import { TransientGitHubError } from "../system/githubRetry";
8
+ import { outputTail } from "../system/outputTail";
8
9
 
9
10
  export function output(value: unknown): void { writeSync(1, `${JSON.stringify(value, null, 2)}\n`); }
10
11
  export function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); }
@@ -40,11 +41,6 @@ export function mutateGitCaptured(args: string[]): void {
40
41
  const detail = outputTail(result.stderr || result.stdout || "");
41
42
  throw new Error(`git ${args[0]} failed (${result.signal ?? result.status})${detail ? `: ${detail}` : "."} Inspect checkout state before retrying.`);
42
43
  }
43
- /** The last lines of a command's output, bounded for an error message. */
44
- export function outputTail(text: string, lines = 20, characters = 2000): string {
45
- const tail = text.trim().split("\n").slice(-lines).join("\n");
46
- return tail.length > characters ? `…${tail.slice(-characters)}` : tail;
47
- }
48
44
  export function clean(): void { assert(!git(["status", "--porcelain=v1", "--untracked-files=all"]), "Checkout has local changes; preserve them before continuing."); }
49
45
  export function head(): string { return oid(git(["rev-parse", "HEAD"])); }
50
46
  export function currentBranch(): string {
@@ -73,6 +73,7 @@ export function repoCommand(args: string[]): number {
73
73
  // REST avoids pre-push hooks. GitHub has no expected-OID delete guard.
74
74
  retryCheckedGitHubMutation(() => { read("gh", ["api", "--method", "DELETE", `repos/${repo.nameWithOwner}/git/refs/heads/${encodeURIComponent(pr.headRefName)}`]); }, () => {
75
75
  // A delete that failed in transit may have landed: confirm the merge and the ref again before resending it.
76
+ // These reads retry on their own too, so a recheck can add its own bounded backoff to the delete's.
76
77
  const current = pullRequest(args[0], repo.nameWithOwner);
77
78
  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
79
  const remote = remoteBranchHead(url, pr.headRefName);