benignswarm 0.12.91 → 0.12.93

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.
@@ -5,11 +5,15 @@ import { Client } from "../client.js";
5
5
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
6
6
  import { readState } from "../state.js";
7
7
  import { codexRollout, sessionsOf } from "../sessions.js";
8
- import { sessionUsage } from "../usage.js";
8
+ import { sessionUsage, watcherClaudeUsage } from "../usage.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
11
11
  import { resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
+ /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
14
+ export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
15
+ return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
16
+ }
13
17
  export function scopeEditFromArgs(p) {
14
18
  const replacement = bool(p.flags, "replace");
15
19
  const append = str(p.flags, "append");
@@ -35,6 +39,45 @@ export function scopeEditFromArgs(p) {
35
39
  export function scopeOnlyOutput(unit, only) {
36
40
  return only ? unit.scope : null;
37
41
  }
42
+ function jsonFlag(p, key, expected) {
43
+ const raw = str(p.flags, key);
44
+ if (raw === undefined)
45
+ return undefined;
46
+ try {
47
+ return JSON.parse(raw);
48
+ }
49
+ catch {
50
+ throw new CliError("usage", `--${key} must be JSON ${expected}`);
51
+ }
52
+ }
53
+ export function needsRetrospectiveInput(status, events = []) {
54
+ if (status === "changes_requested")
55
+ return true;
56
+ const lastSubmission = events.reduce((last, event, index) => ["submitted", "resubmitted", "refreshed"].includes(event.type) ? index : last, -1);
57
+ return events.slice(lastSubmission + 1).some((event) => event.type === "changes_requested");
58
+ }
59
+ function retrospectiveEventDetail(event) {
60
+ const data = event.data ?? {};
61
+ if (event.type === "changes_requested") {
62
+ const cause = data.cause ? `cause=${data.cause}` : "cause=unclassified";
63
+ const citation = data.unmet ? `; cited ${data.cited_from ?? "clause"}: ${JSON.stringify(data.unmet)}` : "; no clause citation (legacy or citation rule disabled)";
64
+ return ` [event ${event.id}; ${cause}${citation}]`;
65
+ }
66
+ if (["resubmitted", "refreshed"].includes(event.type)) {
67
+ const lesson = typeof data.lesson === "string" ? `; lesson: ${data.lesson}` : "";
68
+ const disputes = Array.isArray(data.disputes) ? data.disputes.map((d) => `disputes ${d.send_back_event_id} as ${d.cause}: ${d.reason}`).join("; ") : "";
69
+ return `${lesson}${disputes ? `; ${disputes}` : ""}`;
70
+ }
71
+ if (event.type === "note" && data.annotation)
72
+ return ` [assigner view on ${data.annotation.finding_event_id}: ${data.annotation.cause}; ${data.annotation.reason}]`;
73
+ if (event.type === "ruled" && data.retrospective_resolution)
74
+ return ` [resolved ${data.send_back_event_id} as ${data.cause}; ${event.note}]`;
75
+ if (event.type === "approved" && Array.isArray(data.retrospective_confirmation))
76
+ return ` [confirmed send-back causes: ${data.retrospective_confirmation.map((x) => `${x.reviewer_cause} → ${x.confirmed_cause} (${x.cited_from ?? "uncited"})`).join(", ")}]`;
77
+ if (event.type === "abandoned" && data.retrospective?.complete)
78
+ return ` [send-back retrospective finalized: ${data.retrospective.send_backs.length} recorded]`;
79
+ return "";
80
+ }
38
81
  export function assignmentDisposition(unit, to) {
39
82
  if (unit.status !== "queued")
40
83
  return `Assigned to ${unit.owner_name}; they start it with b9s wu start ${unit.number}.`;
@@ -267,14 +310,19 @@ export async function wu(p, out) {
267
310
  }
268
311
  const to = str(p.flags, "to");
269
312
  const reason = str(p.flags, "reason");
313
+ const allowLowerTier = bool(p.flags, "allow-lower-tier");
314
+ if (allowLowerTier && (!reason?.trim() || reason.trim().length > 1000))
315
+ throw new CliError("usage", '--allow-lower-tier requires --reason "why this lower-tier assignment is needed" (up to 1000 characters)');
316
+ if (allowLowerTier && (to === "auto" || to === "queue"))
317
+ throw new CliError("usage", "--allow-lower-tier applies only when naming an agent");
270
318
  if (!to)
271
319
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
272
320
  const existingNumber = Number(p.positionals[2]);
273
321
  if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
274
322
  if (p.flags.after !== undefined)
275
323
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
276
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
277
- out.print(fmt(r.unit), r);
324
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
325
+ out.print(`${fmt(r.unit)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}`, r);
278
326
  return;
279
327
  }
280
328
  const title = p.positionals.slice(2).join(" ").trim();
@@ -282,8 +330,29 @@ export async function wu(p, out) {
282
330
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
283
331
  const scope = await scopeText();
284
332
  const replay = str(p.flags, "replay-of");
285
- const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }) });
286
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
333
+ const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
334
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
335
+ return;
336
+ }
337
+ case "park": {
338
+ const note = str(p.flags, "note");
339
+ if (!note?.trim())
340
+ throw new CliError("usage", 'wu park <n> --note "why this unit is being parked"');
341
+ const r = await client.call("POST", `${base}/${num()}/park`, { note: note.trim() });
342
+ out.print(`${fmt(r.unit)}\nParked; ${r.unit.owner_name} keeps the unit and branch, and its in-progress slot is free.`, r);
343
+ return;
344
+ }
345
+ case "unpark": {
346
+ const r = await client.call("POST", `${base}/${num()}/unpark`, {});
347
+ out.print(`${fmt(r.unit)}\nUnparked; the owner can continue it.`, r);
348
+ return;
349
+ }
350
+ case "requeue": {
351
+ const note = str(p.flags, "note");
352
+ if (!note?.trim())
353
+ throw new CliError("usage", 'wu requeue <n> --note "why this assigned unit is returning to the queue"');
354
+ const r = await client.call("POST", `${base}/${num()}/requeue`, { note: note.trim() });
355
+ out.print(`${fmt(r.unit)}\nReturned to the queue; branch and event history were kept.`, r);
287
356
  return;
288
357
  }
289
358
  case "take": {
@@ -344,7 +413,16 @@ export async function wu(p, out) {
344
413
  const evidenceIds = list("evidence"); // validated before anything talks to the server
345
414
  const def = await processDef();
346
415
  const where = branchAndHead();
347
- const unitTarget = (await client.call("GET", `${base}/${num()}`)).unit.target ?? def.merge.target_branch;
416
+ const submitRecord = await client.call("GET", `${base}/${num()}`);
417
+ const submitUnit = submitRecord.unit;
418
+ const unitTarget = submitUnit.target ?? def.merge.target_branch;
419
+ const lesson = str(p.flags, "lesson");
420
+ const disputes = jsonFlag(p, "disputes", "an array of dispute objects");
421
+ const retrospectiveDue = needsRetrospectiveInput(submitUnit.status, Array.isArray(submitRecord.events) ? submitRecord.events : []);
422
+ if (retrospectiveDue && !lesson?.trim())
423
+ throw new CliError("usage", 'resubmitting after a send-back requires --lesson "what would have let you get this right the first time?" (up to 280 characters)');
424
+ if (!retrospectiveDue && (lesson !== undefined || disputes !== undefined))
425
+ throw new CliError("usage", "--lesson and --disputes are only used when resubmitting after a send-back");
348
426
  let rebased = null;
349
427
  // The rebase requirement may come from the project or from a tag; the server tells us which
350
428
  // when it refuses. Check locally whenever we are in a repo so the claim is always a finding.
@@ -385,7 +463,7 @@ export async function wu(p, out) {
385
463
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
386
464
  }
387
465
  }
388
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect") }, !!def.review_rules?.length, unitTarget);
466
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
389
467
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
390
468
  const u = r.unit;
391
469
  out.print(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r);
@@ -421,10 +499,14 @@ export async function wu(p, out) {
421
499
  const approve = sub === "rule" && bool(p.flags, "approve");
422
500
  const text = (p.positionals.slice(3).join(" ") || str(p.flags, sub === "ask" ? "question" : "ruling") || str(p.flags, "note") || "").trim();
423
501
  if (!text && !approve)
424
- throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without"' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
425
- const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : approve ? { approve: true, ruling: text } : { ruling: text });
502
+ throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without" (works on queued units too)' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
503
+ const sendBackEvent = str(p.flags, "send-back-event");
504
+ const cause = str(p.flags, "cause");
505
+ if (sendBackEvent && (sub !== "rule" || !cause || !text))
506
+ throw new CliError("usage", 'wu rule <n> --send-back-event <event-id> --cause <cause> --ruling "decision"');
507
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
426
508
  const q = r.unit.question;
427
- out.print(`${fmt(r.unit)}\n${sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
509
+ out.print(`${fmt(r.unit)}\n${sendBackEvent ? "Retrospective ruling recorded on the unit; no chat message was added." : sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
428
510
  return;
429
511
  }
430
512
  case "escalate": {
@@ -486,7 +568,10 @@ export async function wu(p, out) {
486
568
  const unmet = str(p.flags, "unmet");
487
569
  if (!note)
488
570
  throw new CliError("usage", sub === "changes" ? 'wu changes <n> --unmet "<the clause of its scope, exit criterion or agreements it fails, quoted>" --note "what must change"' : `wu ${sub} <n> --note "what you checked"`);
489
- const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}) });
571
+ const cause = str(p.flags, "cause");
572
+ if (sub === "changes" && !cause)
573
+ throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
574
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
490
575
  out.print(fmt(r.unit), r);
491
576
  return;
492
577
  }
@@ -585,7 +670,8 @@ export async function wu(p, out) {
585
670
  return;
586
671
  }
587
672
  case "note": {
588
- const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence") });
673
+ const annotation = jsonFlag(p, "annotation", "an annotation object");
674
+ const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), ...(annotation ? { annotation } : {}) });
589
675
  out.print(fmt(r.unit), r);
590
676
  return;
591
677
  }
@@ -660,9 +746,10 @@ export async function wu(p, out) {
660
746
  out.print(onlyScope, { scope: onlyScope });
661
747
  return;
662
748
  }
663
- const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}${e.data?.to && Array.isArray(e.data.to) ? ` -> ${e.data.to.join(", ")}` : ""}`).join("\n");
749
+ const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}${e.data?.to && Array.isArray(e.data.to) ? ` -> ${e.data.to.join(", ")}` : ""}${retrospectiveEventDetail(e)}`).join("\n");
750
+ const lessons = [...r.events].reverse().filter((e) => typeof e.data?.lesson === "string").map((e) => ` ${e.actor_name}: ${e.data.lesson}`).join("\n");
664
751
  const context = measureContextOutput(r.measure_context, r.unit.expected_effect, r.unit.measured_effect);
665
- out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}\n${events}`, r);
752
+ out.print(`${fmt(r.unit)}${context ? `\n${context}` : ""}${lessons ? `\nWorker lessons (latest first):\n${lessons}` : ""}\n${events}`, r);
666
753
  return;
667
754
  }
668
755
  case "list":
@@ -783,7 +870,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
783
870
  branchCreated = true;
784
871
  log(`created ${pinned} from origin/${pinned}`);
785
872
  }
786
- const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude) : { created: false };
873
+ const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites()) : { created: false };
787
874
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
788
875
  }
789
876
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -797,7 +884,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
797
884
  baseRef = at;
798
885
  }
799
886
  const branchCreated = fullSha(branch) === null;
800
- const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude);
887
+ const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites());
801
888
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
802
889
  }
803
890
  /** Select the replay commit from the same target ref used to create its worktree. */
@@ -1082,14 +1169,20 @@ async function roundUsage(client, base, n, name) {
1082
1169
  return { harness: "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the unit's timeline: ${e.message}` };
1083
1170
  }
1084
1171
  let session = readState(name).harness_session;
1085
- if (!session) {
1086
- // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1087
- const ref = agentRef(loadAgent(name));
1088
- const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1089
- if (rollout)
1090
- session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1091
- }
1092
1172
  try {
1173
+ // Turn-mode watchers bind the session id they were configured to resume. Prefer that exact
1174
+ // transcript over any older hook binding left by another Claude Code session on this machine.
1175
+ if (process.env.BSCHAT_SESSION_ID) {
1176
+ const provider = process.env.BSCHAT_PROVIDER;
1177
+ return watcherClaudeUsage(process.env.BSCHAT_SESSION_ID, since, until, provider === "anthropic" || provider === "deepseek" ? provider : undefined);
1178
+ }
1179
+ if (!session) {
1180
+ // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1181
+ const ref = agentRef(loadAgent(name));
1182
+ const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1183
+ if (rollout)
1184
+ session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1185
+ }
1093
1186
  return sessionUsage(session, since, until);
1094
1187
  }
1095
1188
  catch (e) {
package/dist/git.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { hostname } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
5
  import { CliError } from "./errors.js";
6
6
  export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
7
7
  function status(cwd, timeoutMs) {
@@ -148,7 +148,7 @@ export function commitAtTime(ref, iso, cwd = process.cwd()) {
148
148
  * which case it is checked out as is. Returns the path. Fails loudly: a half-made worktree is
149
149
  * worse than none.
150
150
  */
151
- export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = []) {
151
+ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = [], inheritUrlRewrites = false) {
152
152
  const exists = git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], cwd) !== null;
153
153
  const sparse = exclude.length > 0;
154
154
  // Always defer checkout until we have explicitly applied this project's policy. Otherwise Git
@@ -161,6 +161,71 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
161
161
  applySparse(path, exclude);
162
162
  else
163
163
  applyFullCheckout(path);
164
+ // Git copies config.worktree into linked worktrees. Strip inherited URL rewrites first so a
165
+ // Claude-specific proxy workaround never leaks into Codex or full-access Claude worktrees.
166
+ clearWorktreeUrlRewrites(path);
167
+ if (inheritUrlRewrites)
168
+ copyWorktreeUrlRewrites(cwd, path);
169
+ else
170
+ copyGitHubAppUrlRewrites(cwd, path);
171
+ }
172
+ /** Carry back only HTTPS rewrites paired with this product's linked-repository credential helper. */
173
+ function copyGitHubAppUrlRewrites(from, to) {
174
+ const helpers = spawnSync("git", ["config", "--worktree", "--get-regexp", "^credential\\.https://github\\.com/.+\\.helper$"], { cwd: from, encoding: "utf8" });
175
+ if (helpers.status !== 0)
176
+ return;
177
+ for (const line of helpers.stdout.split(/\r?\n/).filter(Boolean)) {
178
+ const split = line.indexOf(" ");
179
+ if (split < 0 || !/^!.*\s+git-credential$/.test(line.slice(split + 1)))
180
+ continue;
181
+ const helperKey = line.slice(0, split);
182
+ const repoUrl = helperKey.slice("credential.".length, -".helper".length);
183
+ if (!repoUrl.startsWith("https://github.com/"))
184
+ continue;
185
+ const rewriteKey = `url.${repoUrl}.insteadOf`;
186
+ const rewrites = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd: from, encoding: "utf8" });
187
+ if (rewrites.status !== 0)
188
+ continue;
189
+ for (const value of rewrites.stdout.split(/\r?\n/).filter(Boolean)) {
190
+ const copied = spawnSync("git", ["config", "--worktree", "--add", rewriteKey, value], { cwd: to, encoding: "utf8" });
191
+ if (copied.status !== 0)
192
+ throw new Error(`could not preserve linked GitHub App transport in ${to}: ${(copied.stderr || copied.stdout).trim()}`);
193
+ }
194
+ }
195
+ }
196
+ /** Carry worktree-scoped URL rewrites to new unit worktrees so HTTPS proxy access survives `wu start`. */
197
+ export function copyWorktreeUrlRewrites(from, to) {
198
+ const listed = spawnSync("git", ["config", "--worktree", "--get-regexp", "^url\\..*\\.insteadof$"], { cwd: from, encoding: "utf8" });
199
+ if (listed.status !== 0)
200
+ return;
201
+ for (const line of listed.stdout.split(/\r?\n/).filter(Boolean)) {
202
+ const split = line.indexOf(" ");
203
+ if (split < 0)
204
+ continue;
205
+ const key = line.slice(0, split);
206
+ const value = line.slice(split + 1);
207
+ const copied = spawnSync("git", ["config", "--worktree", "--add", key, value], { cwd: to, encoding: "utf8" });
208
+ if (copied.status !== 0)
209
+ throw new Error(`could not copy worktree Git URL rewrite to ${to}: ${(copied.stderr || copied.stdout).trim()}`);
210
+ }
211
+ }
212
+ /** Remove only URL rewrites stored in this worktree's config, leaving shared and global config alone. */
213
+ function clearWorktreeUrlRewrites(cwd) {
214
+ const path = spawnSync("git", ["rev-parse", "--git-path", "config.worktree"], { cwd, encoding: "utf8" });
215
+ if (path.status !== 0)
216
+ return;
217
+ const configPath = path.stdout.trim();
218
+ if (!configPath)
219
+ return;
220
+ const listed = spawnSync("git", ["config", "--file", configPath, "--get-regexp", "^url\\..*\\.insteadof$"], { cwd, encoding: "utf8" });
221
+ if (listed.status !== 0)
222
+ return;
223
+ const keys = [...new Set(listed.stdout.split(/\r?\n/).filter(Boolean).map((line) => line.slice(0, line.indexOf(" "))))];
224
+ for (const key of keys) {
225
+ const removed = spawnSync("git", ["config", "--file", configPath, "--unset-all", key], { cwd, encoding: "utf8" });
226
+ if (removed.status !== 0)
227
+ throw new Error(`could not clear inherited Git URL rewrite from ${cwd}: ${(removed.stderr || removed.stdout).trim()}`);
228
+ }
164
229
  }
165
230
  /**
166
231
  * Non-cone sparse checkout patterns that keep everything except `exclude` (repository paths such as
@@ -227,7 +292,7 @@ function realpathOrSelf(p) {
227
292
  * `git worktree add` (a harness timeout on a large repo) is removed and created again rather than
228
293
  * failing on "already exists"; an existing complete worktree on the right branch is reused.
229
294
  */
230
- export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = () => { }, exclude = []) {
295
+ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = () => { }, exclude = [], inheritUrlRewrites = false) {
231
296
  const st = worktreeState(path, cwd);
232
297
  if (st.state === "foreign")
233
298
  throw new Error(`${path} exists but is not a worktree of this repository; move it aside or pass --here`);
@@ -251,7 +316,7 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
251
316
  log(exclude.length
252
317
  ? `creating ${path} with project checkout exclusions: ${exclude.join(", ")}${files > 20_000 ? ` (${files.toLocaleString()} tracked files)` : ""}`
253
318
  : `creating ${path} with a full checkout (no project exclusions)${files > 20_000 ? `; ${files.toLocaleString()} tracked files, this can take a minute or more` : ""}`);
254
- createWorktree(path, branch, base, cwd, exclude);
319
+ createWorktree(path, branch, base, cwd, exclude, inheritUrlRewrites);
255
320
  return { created: true, repaired };
256
321
  }
257
322
  /**
@@ -301,11 +366,29 @@ export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), ac
301
366
  kept.push({ path: w.path, branch: w.branch, reason: "you are standing in it" });
302
367
  continue;
303
368
  }
369
+ const worktreePath = realpathOrSelf(w.path);
370
+ const use = options.inUse?.find((entry) => {
371
+ if (!isAbsolute(entry.path))
372
+ return false;
373
+ const usePath = realpathOrSelf(entry.path);
374
+ const rel = relative(worktreePath, usePath);
375
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
376
+ });
377
+ if (use) {
378
+ kept.push({ path: w.path, branch: w.branch, reason: `in use by ${use.agent}` });
379
+ continue;
380
+ }
381
+ const homeAgent = w.branch?.startsWith("home/") ? w.branch.slice("home/".length) : null;
382
+ const retiredHome = homeAgent !== null && options.retiredHomeAgents?.has(homeAgent);
383
+ if (homeAgent && !retiredHome) {
384
+ kept.push({ path: w.path, branch: w.branch, reason: `agent home for ${homeAgent} (not retired)` });
385
+ continue;
386
+ }
304
387
  // An agent's home checkout is never leftovers, whatever its branch: join/setup bind an identity
305
388
  // there (unit worktrees never get one). And a worktree made in the last day is too new to judge:
306
389
  // StickJoy's watcher removed a home checkout two minutes after it was created, before the agent
307
390
  // could bind it, because a fresh branch on main's head looks merged.
308
- if (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json"))) {
391
+ if (!retiredHome && (existsSync(join(w.path, ".b9s", "identity.json")) || existsSync(join(w.path, ".bschat", "identity.json")))) {
309
392
  kept.push({ path: w.path, branch: w.branch, reason: "an agent's home checkout (it has a b9s identity file)" });
310
393
  continue;
311
394
  }
@@ -436,20 +519,30 @@ export function ensureReviewWorktree(path, sha, cwd = process.cwd()) {
436
519
  * worktree's own index and files are untouched and no commit hooks run. Returns the branch.
437
520
  * Throws when any step fails: nothing may be removed on the strength of a failed archive.
438
521
  */
439
- export function archiveWorktreeChanges(path, name, message) {
440
- const run = (args, env = process.env) => {
522
+ export function archiveWorktreeChanges(path, name, message, env = process.env) {
523
+ const run = (args) => {
441
524
  const r = spawnSync("git", args, { cwd: path, encoding: "utf8", env });
442
525
  if (r.status !== 0)
443
526
  throw new Error(`git ${args[0]} failed in ${path}: ${(r.stderr || r.stdout).trim()}`);
444
527
  return r.stdout.trim();
445
528
  };
529
+ const author = spawnSync("git", ["var", "GIT_AUTHOR_IDENT"], { cwd: path, encoding: "utf8", env });
530
+ const committer = spawnSync("git", ["var", "GIT_COMMITTER_IDENT"], { cwd: path, encoding: "utf8", env });
531
+ if (author.status !== 0 || committer.status !== 0) {
532
+ throw new Error(`cannot archive worktree changes without a Git author and committer identity; configure them with: git config --global user.name "Your Name" && git config --global user.email "you@example.com"`);
533
+ }
446
534
  const index = run(["rev-parse", "--git-path", "index"]);
447
535
  const tmp = `${index}.bschat-archive-${process.pid}`;
448
536
  copyFileSync(index.startsWith("/") ? index : join(path, index), tmp.startsWith("/") ? tmp : join(path, tmp));
449
537
  try {
450
- const env = { ...process.env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
451
- run(["add", "-A"], env);
452
- const tree = run(["write-tree"], env);
538
+ const indexEnv = { ...env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
539
+ const add = spawnSync("git", ["add", "-A"], { cwd: path, encoding: "utf8", env: indexEnv });
540
+ if (add.status !== 0)
541
+ throw new Error(`git add failed in ${path}: ${(add.stderr || add.stdout).trim()}`);
542
+ const writeTree = spawnSync("git", ["write-tree"], { cwd: path, encoding: "utf8", env: indexEnv });
543
+ if (writeTree.status !== 0)
544
+ throw new Error(`git write-tree failed in ${path}: ${(writeTree.stderr || writeTree.stdout).trim()}`);
545
+ const tree = writeTree.stdout.trim();
453
546
  const commit = run(["commit-tree", "-p", "HEAD", "-m", message, tree]);
454
547
  const branch = `archive/${name}`;
455
548
  run(["branch", branch, commit]);
package/dist/harnesses.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { CliError } from "./errors.js";
@@ -22,6 +22,100 @@ export function turnHarness(h) {
22
22
  }
23
23
  export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
24
24
  export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
25
+ /** Node's fetch ignores the sandbox's HTTP(S)_PROXY unless this opt-in is present. */
26
+ export function claudeSandboxEnv(sandbox) {
27
+ return sandbox === "workspace-write" ? { NODE_USE_ENV_PROXY: "1", BSCHAT_CLAUDE_SANDBOX: "workspace-write" } : {};
28
+ }
29
+ /** Resolve PATH first, then the native Claude Code installer's versioned executables. */
30
+ export function claudeCodePath(path = process.env.PATH ?? "", home = homedir()) {
31
+ const executableFile = (candidate) => {
32
+ try {
33
+ if (!statSync(candidate).isFile())
34
+ return false;
35
+ accessSync(candidate, constants.X_OK);
36
+ return true;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ };
42
+ for (const dir of path.split(":")) {
43
+ if (!dir)
44
+ continue;
45
+ const candidate = join(dir, "claude");
46
+ if (executableFile(candidate))
47
+ return candidate;
48
+ }
49
+ const versionsDir = join(home, ".local", "share", "claude", "versions");
50
+ let versions;
51
+ try {
52
+ versions = readdirSync(versionsDir).filter((v) => /^\d+(?:\.\d+)*(?:[-+][\w.-]+)?$/.test(v));
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ const compare = (a, b) => {
58
+ const [abase, apre] = a.split("-", 2);
59
+ const [bbase, bpre] = b.split("-", 2);
60
+ const av = abase.split(".").map(Number);
61
+ const bv = bbase.split(".").map(Number);
62
+ for (let i = 0; i < Math.max(av.length, bv.length); i++) {
63
+ const x = av[i] ?? 0;
64
+ const y = bv[i] ?? 0;
65
+ if (x === y)
66
+ continue;
67
+ return x - y;
68
+ }
69
+ if (apre === undefined || bpre === undefined)
70
+ return apre === bpre ? 0 : apre === undefined ? 1 : -1;
71
+ const preCompare = apre.localeCompare(bpre, undefined, { numeric: true });
72
+ if (preCompare)
73
+ return preCompare;
74
+ return 0;
75
+ };
76
+ for (const version of versions.sort(compare).reverse()) {
77
+ const versionPath = join(versionsDir, version);
78
+ if (executableFile(versionPath))
79
+ return versionPath;
80
+ const candidate = join(versionsDir, version, "claude");
81
+ if (executableFile(candidate))
82
+ return candidate;
83
+ }
84
+ return null;
85
+ }
86
+ export function claudeTurnArgs(maxBudgetUsd) {
87
+ return ["--max-budget-usd", String(maxBudgetUsd)];
88
+ }
89
+ /** Parse the strict JSON report requested from tools run inside Claude Code's sandbox. */
90
+ export function claudeSelfCheckError(stdout) {
91
+ let reportText = stdout;
92
+ try {
93
+ const envelope = JSON.parse(stdout);
94
+ if (typeof envelope.result === "string")
95
+ reportText = envelope.result;
96
+ }
97
+ catch { /* allow the direct report for tests and future CLI output formats */ }
98
+ let report;
99
+ try {
100
+ report = JSON.parse(reportText);
101
+ }
102
+ catch {
103
+ return `Claude Code did not return the self-check JSON report; output: ${stdout.trim().slice(0, 1500) || "(empty)"}`;
104
+ }
105
+ const errors = [];
106
+ const me = report.b9s_me;
107
+ if (!me || me.status !== 0 || typeof me.output !== "string" || !me.output.trim())
108
+ errors.push(`b9s me failed (exit ${typeof me?.status === "number" ? me.status : "unknown"}): ${String(me?.output ?? "(no output)").trim().slice(0, 600)}`);
109
+ const remote = report.git_ls_remote_origin;
110
+ if (!remote || remote.status !== 0 || typeof remote.output !== "string" || !/^([a-f0-9]{40}|[a-f0-9]{64})\s+\S+/m.test(remote.output))
111
+ errors.push(`git ls-remote origin failed (exit ${typeof remote?.status === "number" ? remote.status : "unknown"}): ${String(remote?.output ?? "(no refs returned)").trim().slice(0, 600)}`);
112
+ return errors.length ? errors.join("\n") : null;
113
+ }
114
+ export function assertClaudeSelfCheck(stdout) {
115
+ const error = claudeSelfCheckError(stdout);
116
+ if (error)
117
+ throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${error}`);
118
+ }
25
119
  export function probeFor(harness, session, ref) {
26
120
  return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
27
121
  }
@@ -446,13 +540,14 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
446
540
  throw new CliError("usage", `unknown sandbox ${sandbox}`);
447
541
  const dirs = [dirname(cwd), bschatHome, ...extraWritable];
448
542
  const settings = {
543
+ env: claudeSandboxEnv(sandbox),
449
544
  sandbox: {
450
545
  enabled: true,
451
546
  failIfUnavailable: true,
452
547
  autoAllowBashIfSandboxed: true,
453
548
  allowUnsandboxedCommands: false,
454
549
  filesystem: { allowWrite: dirs },
455
- network: { allowedDomains: ["*"] },
550
+ network: { allowedDomains: ["*", "api.benignswarm.org"] },
456
551
  },
457
552
  };
458
553
  return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
package/dist/help.js CHANGED
@@ -27,6 +27,7 @@ Agent commands
27
27
  b9s logout --as <name>
28
28
  b9s identities list saved identities on this machine
29
29
  b9s me who am I, role, permissions, channels
30
+ b9s git-credential get|store|erase Git credential helper for the project's linked GitHub repository
30
31
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process and notices
31
32
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
32
33
  assigner only: add a project notice; matching commands warn but continue
@@ -50,18 +51,21 @@ Agent commands
50
51
  b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--reworks n,m] [--after <n>[,<m>]] [--tier routine|careful|expert] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] open a work unit in its own
51
52
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
52
53
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
53
- b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--reworks n,m] [--after <n>[,<m>]] [--tier routine|careful|expert] [--requires cap,cap] [--force] [--replay-of n] [--template] [--reason "why"] hand out a unit (assigner roles);
54
+ b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--reworks n,m] [--after <n>[,<m>]] [--tier routine|careful|expert] [--allow-lower-tier --reason "why"] [--requires cap,cap] [--force] [--replay-of n] [--template] [--reason "why"] hand out a unit (assigner roles);
54
55
  --to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
55
56
  reports why candidates were passed over, and the sweep chases it;
56
57
  --to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
57
58
  anyone's after the takeover window); --hold keeps it assigned to them however long it takes;
58
59
  --template --tags a,b prints the scope skeleton; --force records missing required sections, including for queue.
59
- b9s wu assign <n> --to <agent> [--reason "why"] reassign an assigned or queued unit in place
60
+ b9s wu assign <n> --to <agent> [--reason "why"] [--allow-lower-tier] reassign an assigned or queued unit in place; a lower-tier target needs both flags and a reason
60
61
  b9s wu take <n> [--to <agent>] [--reason "why"] pull a unit or hand it to someone
61
62
  reason is required when an assigner uses its assign_outside_qualifications role capability
62
63
  b9s wu next take the oldest queued unit you qualify for
63
64
  b9s wu decline <n> --note "why" [--waits-on <milestone,...> | --defer] decline and requeue an assignment (use wu abandon to close); a steward planning unit
64
65
  ("Advance milestone X") needs the plan decision: what X waits on, or defer X
66
+ b9s wu park <n> --note "why" assigner or operator: park open or sent-back work, keep its owner/branch and free its in-progress slot
67
+ b9s wu unpark <n> assigner or operator: return parked work to open when its owner's slot is free
68
+ b9s wu requeue <n> --note "why" assigner or operator: return an assigned, unstarted unit to the queue; history and branch stay
65
69
  b9s wu start <n> [--branch b | --here] take it up: makes ../<repo>-wu<n> on branch wu/<n>-<slug> (replays: from the
66
70
  target as of the original); a worktree left half-written by an interrupted
67
71
  checkout is removed and made again; wu open does the same for your own units;
@@ -91,19 +95,20 @@ Agent commands
91
95
  b9s measure post <name> --sha <commit> --value <v> --evidence <id[,id...]> [--target branch]
92
96
  b9s measure check <name> run the command producer for the active matching unit at this clean worktree's HEAD and compare with its target's latest good value
93
97
  Global: --effort <high|medium|low|...> reasoning effort to report (else BSCHAT_EFFORT, CLAUDE_EFFORT, codex model_reasoning_effort)
94
- b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] ask for review; repeat --evidence or pass comma-separated ids; optional expected effect is shown to reviewers; verifies the commit on origin branches
98
+ b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] [--lesson "..."] [--disputes '<JSON list>'] ask for review; after a send-back give one lesson (max 280 chars); optional disputes cite send-back event IDs and exact clauses
95
99
  b9s wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
96
100
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
97
- b9s wu approve <n> --note ".." approval covers tags your role reviews
101
+ b9s wu approve <n> --note ".." [--confirm-causes cause,cause] approval covers tags your role reviews; complete approval confirms classified send-back causes in timeline order
98
102
  a planned reviewer still owing may approve after coverage; status stays approved until merge
99
- b9s wu changes <n> --unmet ".." --note ".." send back, quoting the failed scope, exit or agreement clause; a planned reviewer still owing may send an approved, unmerged unit back
103
+ b9s wu changes <n> --unmet ".." --cause <cause> --note ".." send back with a cited clause and cause (scope_gap, missing_context, worker_error, reviewer_scope_growth, environment, stale_base); a planned reviewer still owing may send an approved, unmerged unit back
100
104
  concerns outside those are notes (wu note) or questions (wu ask)
101
105
  b9s wu classify <n> --tags a,b classifier: confirm or change a new unit's tags before it routes for review
102
106
  b9s wu proceed <n> --note ".." reviewer: this step is good, carry on; back to the owner, NOT an approval
103
107
  b9s wu reopen <n> --note ".." owner or reviewer: withdraw an unmerged approval (verification failed); resubmit the same unit
104
108
  b9s wu supersede <n> --by <m> owner or assigner: this unit continues as #m; anyone blocked on #n now waits on #m
105
- b9s wu ask <n> "question" owner, reviewer or assigner: a decision this unit cannot move without (tag expert first, then the operator)
106
- b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console)
109
+ b9s wu ask <n> "question" owner, reviewer or assigner: a decision this unit cannot move without, including queued units (tag expert first, then the operator)
110
+ b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console); --send-back-event <id> --cause <cause> records an explicit retrospective ruling
111
+ b9s wu note <n> --note ".." [--annotation '<JSON object>'] add a note; assigner annotation links a cited scope finding to a cause and one-line reason
107
112
  b9s wu propose <n> "answer" owner, reviewer, assigner or expert: recommend an answer to the unit's open question, approvable as written
108
113
  b9s wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
109
114
  b9s wu wait <n> --on <m> --note "why" | --clear
@@ -157,8 +162,9 @@ Agent commands
157
162
  b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
158
163
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
159
164
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
160
- b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--turns-per-hour 1..20] [--dsh path]
165
+ b9s start --harness codex|claude-code|dsh --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..20] [--dsh path]
161
166
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
167
+ Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
162
168
  (b9s codex start is the same with --harness codex)
163
169
  b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
164
170
  b9s machine run | once | status | prepare | service the machine daemon (prepare checks dsh availability/version; Linux reports no DeepSeek build)
@@ -283,6 +289,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
283
289
  15 min before, its agents away until the machine reports back after booting
284
290
  b9s-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access> [--harness codex|claude-code] [--provider anthropic|deepseek]
285
291
  [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..20]
292
+ b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
286
293
  b9s-admin machine session stop|start|resume|limit|remove <machine> <project>/<agent> resume a latched turn fault or set a lower per-session hourly limit
287
294
  (change its count/settings, pause scaling, pin, or bench the agent)
288
295
  b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]