benignswarm 0.12.158 → 0.12.160

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) {
package/dist/help.js CHANGED
@@ -29,7 +29,7 @@ Mac capacity/signing API (profiles, leases, signer-only references, TestFlight a
29
29
  Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are WU #313.
30
30
  Claude Code, Codex, and Antigravity SessionStart hooks retrieve the complete effective rules at fresh start, resume, compaction, and clear into a new thread. They acknowledge only after complete output; an unavailable or over-budget payload points to b9s process without acknowledgment. b9s me shows concise rule text and acknowledgment, b9s process shows the full project rules and acknowledges that fingerprint after display, and b9s resume includes the effective rulesets.
31
31
 
32
- GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
32
+ GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Open or reuse a PR for a unit's pushed branch with b9s wu pr <n>; add --auto-merge to ask GitHub to merge it after required checks pass. The API scopes its installation token to the linked repository, stores the PR URL on the unit, and never prints or persists the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
33
33
 
34
34
  Environment problems: agents report bounded, redacted observations with b9s environment report; reports use scoped project or machine access, account-scoped evidence, and only the agent's own blocked units. Agents can append observations but cannot claim, diagnose, or resolve issues. Operators and agents whose role has own_environment_problems can manage visible issues. Operators use Account → Environment in the console to filter and inspect issues, claim/assign/reassign, record diagnoses, and resolve with a note and verification. Manual diagnoses use source agent; doctor/daemon provenance is for actual check results. Banner links open the same issue detail with impact context. Issue detail links active notices in the same scope and current machine-session faults related to its machine or explicitly linked unit owner. The read-only steward summary lists active linked issues and currently waiting linked units, without publishing notices or creating work. Machine issue views respect linked-project access. Spending impact is unknown and creates no banner until unit-attributed telemetry lands in WU #236; see packages/skill/references/api.md.
35
35
 
@@ -201,6 +201,7 @@ Machine placement enforces configured session slots and reports machine pressure
201
201
  b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
202
202
  b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; checks its branch has no commits beyond the target for no-source; requires a passing lock-run gate receipt for the commit or matching tree
203
203
  Antigravity workspace-write queues the exact closed worktree for cleanup outside the sandbox at turn finalization; branches are kept
204
+ b9s wu pr <n> [--auto-merge] open or reuse a pull request for the linked repository and unit branch
204
205
  b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
205
206
  b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
206
207
  b9s wu train list [--target <branch>] [--limit <n>] list active merge train queue and recent train runs
@@ -327,9 +328,9 @@ Machine placement enforces configured session slots and reports machine pressure
327
328
  queue a remote seeded browser task or ux:compare on an account machine labeled ux-host or browser
328
329
  b9s ux job <id> [--log] inspect remote browser job diagnostics; --log prints its full log
329
330
  b9s ux jobs [--unit <n>] [--limit n] list remote browser jobs in this project
330
- b9s gate run <n> [--merge-candidate <sha>] --on <machine>
331
+ b9s gate run <n> [--merge-candidate <sha>] [--on <machine>]
331
332
  b9s gate run --train [--target <branch>] [--on <machine>]
332
- queue a complete-suite gate run (or merge-train run) on a machine; records the receipt and posts the log as evidence
333
+ queue a complete-suite gate run (or merge-train run); auto-selects a qualified free gate machine unless --on is given, records the receipt and posts the log as evidence
333
334
  b9s gate job <id> [--log] inspect remote gate diagnostics; --log prints its full log
334
335
  b9s gate jobs [--unit <n>] [--limit n] list remote gate jobs in this project
335
336
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
@@ -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
+ }