benignswarm 0.12.158 → 0.12.159

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/dist/git.js CHANGED
@@ -4,6 +4,7 @@ import { hostname } from "node:os";
4
4
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  import { configDirectory } from "./directories.js";
7
+ import { retryGitFetchSync } from "./git-fetch.js";
7
8
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
8
9
  function status(cwd, timeoutMs) {
9
10
  const r = spawnSync("git", ["status", "--porcelain"], { cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
@@ -21,29 +22,58 @@ export function sessionCheckoutFacts(cwd, options = {}) {
21
22
  const branchResult = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
22
23
  cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
23
24
  });
25
+ const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
24
26
  const statusResult = spawnSync("git", ["status", "--porcelain"], {
25
27
  cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024, timeout: 5_000,
26
28
  });
27
- const fetched = options.verifyOrigin && gitDir ? spawnSync("git", ["--git-dir", gitDir, "--work-tree", cwd, "fetch", "--prune", "origin"], {
28
- cwd, encoding: "utf8", stdio: ["ignore", "ignore", "ignore"], timeout: 30_000,
29
- env: gitTransportEnv(),
30
- }) : null;
31
- const remoteResult = spawnSync("git", ["rev-list", "--count", "HEAD", "--not", options.verifyOrigin ? "--remotes=origin" : "--remotes"], {
29
+ let fetchFailure = null;
30
+ const liveRemoteRefs = [];
31
+ if (options.verifyOrigin && gitDir) {
32
+ // Reachability has historically meant any advertised origin branch. Enumerate that live set,
33
+ // update each changed tracking ref explicitly, and keep deleted cached refs out of the proof.
34
+ // Fetching all origin refs in one operation let an unrelated branch update abort this check.
35
+ const advertised = spawnSync("git", ["ls-remote", "--heads", "origin"], { cwd, encoding: "utf8", timeout: 30_000, env: gitTransportEnv(), maxBuffer: 16 * 1024 * 1024 });
36
+ if (advertised.status !== 0) {
37
+ fetchFailure = { status: advertised.status, stdout: advertised.stdout, stderr: advertised.stderr, error: advertised.error };
38
+ }
39
+ else {
40
+ for (const line of advertised.stdout.split("\n")) {
41
+ const [remoteSha, remoteBranchRef] = line.trim().split(/\s+/);
42
+ if (!/^[0-9a-f]{40,64}$/i.test(remoteSha ?? "") || !remoteBranchRef?.startsWith("refs/heads/"))
43
+ continue;
44
+ const branchName = remoteBranchRef.slice("refs/heads/".length);
45
+ const trackingRef = `refs/remotes/origin/${branchName}`;
46
+ if (fullSha(trackingRef, cwd) !== remoteSha.toLowerCase()) {
47
+ const fetched = retryGitFetchSync(["--git-dir", gitDir, "--work-tree", cwd, "fetch", "--no-tags", "origin", `+${remoteBranchRef}:${trackingRef}`], cwd, { timeoutMs: 30_000, env: gitTransportEnv() });
48
+ if (fetched.status !== 0 || fullSha(trackingRef, cwd) === null) {
49
+ fetchFailure = fetched.status === 0
50
+ ? { ...fetched, status: 1, stderr: `${trackingRef} was unavailable after fetch` }
51
+ : fetched;
52
+ break;
53
+ }
54
+ }
55
+ liveRemoteRefs.push(trackingRef);
56
+ }
57
+ }
58
+ }
59
+ const reachabilityArgs = options.verifyOrigin
60
+ ? ["rev-list", "--count", "HEAD", ...(liveRemoteRefs.length ? ["--not", ...liveRemoteRefs] : [])]
61
+ : ["rev-list", "--count", "HEAD", "--not", "--remotes"];
62
+ const remoteResult = spawnSync("git", reachabilityArgs, {
32
63
  cwd, env: gitMetadataEnv(cwd), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024, timeout: 5_000,
33
64
  });
34
65
  const statusError = statusResult.error;
35
66
  const remoteError = remoteResult.error;
36
67
  const statusOk = statusResult.status === 0;
37
68
  const countText = remoteResult.stdout.trim();
38
- const count = (!options.verifyOrigin || fetched?.status === 0) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
69
+ const count = (!options.verifyOrigin || (gitDir !== null && fetchFailure === null)) && remoteResult.status === 0 && /^\d+$/.test(countText) ? Number(countText) : null;
39
70
  const entries = statusOk ? statusResult.stdout.split("\n").filter(Boolean) : [];
40
71
  const untracked = statusOk ? entries.some((line) => line.startsWith("??")) : null;
41
72
  const uncommitted = statusOk ? entries.some((line) => !line.startsWith("??")) : null;
42
73
  const clean = statusOk ? entries.length === 0 : null;
43
- const branch = branchResult.status === 0 && branchResult.stdout.trim() ? branchResult.stdout.trim() : null;
44
74
  const branchError = branchResult.error;
45
- const fetchError = fetched?.error;
46
- const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), options.verifyOrigin && !gitDir ? "git fetch origin failed: checkout could not be resolved" : fetched && fetched.status !== 0 ? `git fetch origin failed: ${fetchError?.code ?? `exit ${fetched.status}`}` : null, remoteError?.code ?? (remoteResult.status !== 0 || !/^\d+$/.test(countText) ? `git remote reachability exited ${remoteResult.status}` : null), branchError?.code ?? (branch === null ? `git branch inspection exited ${branchResult.status}` : null)].filter(Boolean);
75
+ const fetchError = fetchFailure?.error;
76
+ const errors = [statusError?.code ?? (statusOk ? null : `git status exited ${statusResult.status}`), options.verifyOrigin && !gitDir ? "git fetch origin failed: checkout could not be resolved" : fetchFailure ? `git fetch origin failed: ${fetchError?.code ?? fetchFailure.stderr?.trim() ?? `exit ${fetchFailure.status}`}` : null, remoteError?.code ?? (remoteResult.status !== 0 || !/^\d+$/.test(countText) ? `git remote reachability exited ${remoteResult.status}` : null), branchError?.code ?? (branch === null ? `git branch inspection exited ${branchResult.status}` : null)].filter(Boolean);
47
77
  return {
48
78
  branch,
49
79
  clean,
@@ -224,7 +254,7 @@ export function isAncestor(ancestor, ref, cwd = process.cwd()) {
224
254
  export function verifyNoCommitsBeyondTarget(branch, target, cwd = process.cwd(), requirePushed = false) {
225
255
  const localBranch = `refs/heads/${branch}`;
226
256
  const ref = `origin/${target}`;
227
- const fetchTarget = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 });
257
+ const fetchTarget = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd);
228
258
  if (fetchTarget.status !== 0) {
229
259
  const detail = fetchTarget.error?.message || fetchTarget.stderr?.trim() || fetchTarget.stdout?.trim() || `git fetch exited ${fetchTarget.status ?? "without a status"}`;
230
260
  return { on: null, ref, reason: `git fetch origin ${target} failed: ${detail}` };
@@ -242,7 +272,7 @@ export function verifyNoCommitsBeyondTarget(branch, target, cwd = process.cwd(),
242
272
  const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", remoteBranchRef], { cwd, encoding: "utf8", timeout: 120_000 });
243
273
  if (listed.status === 0 && listed.stdout?.trim()) {
244
274
  const remoteTracking = `refs/remotes/origin/${branch}`;
245
- const fetchBranch = spawnSync("git", ["fetch", "--quiet", "origin", `+${remoteBranchRef}:${remoteTracking}`], { cwd, encoding: "utf8", timeout: 120_000 });
275
+ const fetchBranch = retryGitFetchSync(["fetch", "--quiet", "origin", `+${remoteBranchRef}:${remoteTracking}`], cwd);
246
276
  if (fetchBranch.status !== 0) {
247
277
  const detail = fetchBranch.error?.message || fetchBranch.stderr?.trim() || fetchBranch.stdout?.trim() || `git fetch exited ${fetchBranch.status ?? "without a status"}`;
248
278
  return { on: null, ref, reason: `git fetch origin ${branch} failed: ${detail}` };
@@ -661,7 +691,7 @@ export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), re
661
691
  const repositoryArgs = gitRepositoryArgs(cwd);
662
692
  // Submission only needs current remote-tracking refs. Force pruning off even when user/repo
663
693
  // config enables it: pruning stale refs takes .git/packed-refs.lock in the shared Git dir.
664
- const fetched = spawnSync("git", [...repositoryArgs, "-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], { cwd, env: gitTransportEnv(), encoding: "utf8", timeout: 120_000 });
694
+ const fetched = retryGitFetchSync([...repositoryArgs, "-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], cwd, { env: gitTransportEnv() });
665
695
  if (fetched.status !== 0) {
666
696
  const detail = (fetched.stderr || fetched.stdout || `git fetch ${remote} exited with status ${fetched.status ?? "unknown"}`).trim();
667
697
  return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
@@ -712,7 +742,7 @@ export function fullSha(ref, cwd = process.cwd()) {
712
742
  }
713
743
  /** `git fetch <remote> <ref>`; false when the fetch fails (no remote, unreachable, no such ref). */
714
744
  export function fetchRef(ref, remote = "origin", cwd = process.cwd()) {
715
- return spawnSync("git", ["fetch", "--quiet", remote, ref], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
745
+ return retryGitFetchSync(["fetch", "--quiet", remote, ref], cwd).status === 0;
716
746
  }
717
747
  export function hasRemote(remote = "origin", cwd = process.cwd()) {
718
748
  return spawnSync("git", ["remote", "get-url", remote], { cwd, encoding: "utf8" }).status === 0;
@@ -744,10 +774,10 @@ export function pushBranchToOrigin(branch, cwd = process.cwd(), remote = "origin
744
774
  * the updated tracking ref or the git failure reason.
745
775
  */
746
776
  export function fetchRemoteBranch(branch, remote = "origin", cwd = process.cwd()) {
747
- const r = spawnSync("git", ["fetch", "--quiet", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], { cwd, encoding: "utf8", timeout: 120_000 });
777
+ const r = retryGitFetchSync(["fetch", "--quiet", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`], cwd);
748
778
  const trackingRef = `${remote}/${branch}`;
749
779
  if (r.status !== 0) {
750
- const reason = (r.error ? r.error.message : (r.stderr || r.stdout).trim()) || `git fetch ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
780
+ const reason = r.error?.message || r.stderr?.trim() || r.stdout?.trim() || `git fetch ${remote} ${branch} failed (exit ${r.status ?? "unknown"})`;
751
781
  return { ok: false, reason };
752
782
  }
753
783
  if (fullSha(trackingRef, cwd) === null) {
@@ -821,7 +851,7 @@ export function verifyMergedCommit(merged, target, cwd = process.cwd()) {
821
851
  // Fetch into the remote-tracking ref explicitly. Fetching a bare branch name updates
822
852
  // FETCH_HEAD only and leaves origin/<target> stale, which cannot verify this condition.
823
853
  const ref = `origin/${target}`;
824
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], { cwd, encoding: "utf8", timeout: 120_000 }).status === 0;
854
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${target}:refs/remotes/origin/${target}`], cwd).status === 0;
825
855
  if (!fetched)
826
856
  return { on: local, ref: target };
827
857
  const remote = isAncestor(merged, ref, cwd);
@@ -956,7 +986,7 @@ function pushedToOrigin(head, branch, cwd) {
956
986
  if (!head || !branch)
957
987
  return false;
958
988
  const remoteRef = `refs/remotes/origin/${branch}`;
959
- const fetched = spawnSync("git", ["fetch", "--quiet", "origin", `+refs/heads/${branch}:${remoteRef}`], { cwd, encoding: "utf8", timeout: 120_000 });
989
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${branch}:${remoteRef}`], cwd);
960
990
  return fetched.status === 0 && spawnSync("git", ["merge-base", "--is-ancestor", head, remoteRef], { cwd, stdio: "ignore" }).status === 0;
961
991
  }
962
992
  export function removeWorktreeIfClean(path, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
@@ -0,0 +1,33 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { CliError } from "./errors.js";
3
+ export const LOCK_RUN_LEASE_MS = 60_000;
4
+ /** Retry an uncertain renewal while the last confirmed lock lease is still valid. */
5
+ export function createLockHeartbeatReporter(heartbeat, options = {}) {
6
+ const leaseMs = options.leaseMs ?? LOCK_RUN_LEASE_MS;
7
+ const now = options.now ?? (() => performance.now());
8
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
9
+ let lastConfirmedAt = now();
10
+ return async (commandPid) => {
11
+ let attempt = 0;
12
+ for (;;) {
13
+ try {
14
+ await heartbeat(commandPid);
15
+ lastConfirmedAt = now();
16
+ return;
17
+ }
18
+ catch (error) {
19
+ if (error instanceof CliError && (error.code === "lock_lease_lost" || error.code === "not_found")) {
20
+ throw new CliError("lock_lease_lost", `the server says this job no longer holds its lock: ${error.message}`, undefined, error.httpStatus);
21
+ }
22
+ const remainingMs = leaseMs - (now() - lastConfirmedAt);
23
+ if (remainingMs <= 0) {
24
+ throw new CliError("lock_heartbeat_failed", `lock renewal did not succeed for ${leaseMs}ms; the lease may have expired: ${error instanceof Error ? error.message : String(error)}`);
25
+ }
26
+ const delayMs = Math.min(remainingMs, Math.min(5_000, 500 * 2 ** Math.min(attempt, 4)));
27
+ options.onRetry?.(error, delayMs);
28
+ attempt++;
29
+ await sleep(delayMs);
30
+ }
31
+ }
32
+ };
33
+ }