benignswarm 0.12.129 → 0.12.130

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.
@@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
- import { probeFor, turnHarness } from "../harnesses.js";
5
+ import { claudeSettings, probeFor, turnHarness } from "../harnesses.js";
6
6
  import { applyAck } from "./wake.js";
7
7
  import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
8
8
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
@@ -19,6 +19,7 @@ import { CliError } from "../errors.js";
19
19
  import { claudeTurnEnv } from "../providers.js";
20
20
  import { acquireWatchLock } from "../lock.js";
21
21
  import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
22
+ import { currentAssignmentEvent, deliveredAssignmentBinding } from "../turn-binding.js";
22
23
  import { writeFileAtomic } from "../shared-file.js";
23
24
  import { readState, updateState } from "../state.js";
24
25
  import { probeCapabilities } from "../capabilities.js";
@@ -107,12 +108,30 @@ export async function watch(p, out, dependencies = {}) {
107
108
  if (providerName === "deepseek" && harness !== "claude-code")
108
109
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
109
110
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
111
+ let claudeRuntime;
112
+ const claudeRuntimeText = str(p.flags, "turn-claude-runtime");
113
+ if (claudeRuntimeText !== undefined) {
114
+ if (harness !== "claude-code")
115
+ throw new CliError("usage", "--turn-claude-runtime is only valid with --harness claude-code");
116
+ try {
117
+ const value = JSON.parse(claudeRuntimeText);
118
+ if (typeof value.sandbox !== "string" || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")
119
+ || (value.effort !== undefined && typeof value.effort !== "string")
120
+ || (value.maxBudgetUsd !== undefined && (typeof value.maxBudgetUsd !== "number" || !Number.isFinite(value.maxBudgetUsd) || value.maxBudgetUsd <= 0))) {
121
+ throw new Error("invalid Claude turn runtime fields");
122
+ }
123
+ claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}) };
124
+ }
125
+ catch (error) {
126
+ throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
127
+ }
128
+ }
110
129
  const machineSessionId = str(p.flags, "machine-session-id") ?? process.env.BSCHAT_MACHINE_SESSION_ID;
111
130
  if (machineSessionId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(machineSessionId))
112
131
  throw new CliError("usage", "machine session id must be a UUID");
113
132
  if (machineSessionId)
114
133
  process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
115
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model, ...(machineSessionId ? { machineSessionId } : {}) };
134
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model, ...(claudeRuntime ? { claudeRuntime } : {}), ...(machineSessionId ? { machineSessionId } : {}) };
116
135
  }
117
136
  else if (p.flags.provider !== undefined) {
118
137
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -190,7 +209,13 @@ export async function watch(p, out, dependencies = {}) {
190
209
  while (!stopping) {
191
210
  if (watcherClient) {
192
211
  try {
193
- await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue");
212
+ const phase = turnMode && probe ? probe.phase() : null;
213
+ const saved = turnMode ? readState(name).watch_turn_binding : undefined;
214
+ const observed = phase && !("missing" in phase) && phase.running && phase.startedAt && saved?.started_at === phase.startedAt ? saved : null;
215
+ const binding = observed?.work_unit_number && observed.assignment_event_id
216
+ ? { work_unit_number: observed.work_unit_number, assignment_event_id: observed.assignment_event_id }
217
+ : null;
218
+ await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue", { startedAt: observed?.started_at ?? null, binding });
194
219
  }
195
220
  catch (e) {
196
221
  log(`watcher heartbeat failed: ${e.message}`);
@@ -302,7 +327,8 @@ export async function watch(p, out, dependencies = {}) {
302
327
  const activeProbe = probe;
303
328
  if (activeProbe)
304
329
  await (dependencies.turnStep ?? turnStep)(ctl, activeProbe, turnTimeout, log, async (sink, beforeTurn) => {
305
- const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, dependencies.wakeOnceDependencies);
330
+ const wakeDependencies = { ...dependencies.wakeOnceDependencies, ...(turn?.claudeRuntime ? { claudeRuntime: turn.claudeRuntime } : {}) };
331
+ const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, wakeDependencies);
306
332
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
307
333
  }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
308
334
  else {
@@ -396,6 +422,40 @@ async function waitIntervalOrStop(ms, stopped) {
396
422
  if (timer)
397
423
  clearTimeout(timer);
398
424
  }
425
+ /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
426
+ async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
427
+ const creds = loadAgent(name);
428
+ if (!creds.project)
429
+ throw new CliError("unit_worktree_prepare_failed", `cannot prepare WU #${binding.work_unit_number}: ${name} has no project-scoped identity`);
430
+ const client = Client.forAgent(creds, undefined, { presence: false });
431
+ const base = `/projects/${encodeURIComponent(creds.project)}/work-units/${binding.work_unit_number}`;
432
+ try {
433
+ const record = await client.call("GET", base);
434
+ const unit = record.unit;
435
+ if (!unit || unit.number !== binding.work_unit_number)
436
+ throw new Error("the server did not return the requested work unit");
437
+ if (unit.owner_name !== creds.agent) {
438
+ if (allowSuperseded)
439
+ return null;
440
+ throw new Error(`WU #${binding.work_unit_number} is now owned by ${unit.owner_name ?? "no agent"}, not ${creds.agent}`);
441
+ }
442
+ if (!["assigned", "open", "changes_requested"].includes(unit.status))
443
+ return null;
444
+ const activeAssignment = currentAssignmentEvent(record.events ?? [], unit.owner_agent_id, creds.agent);
445
+ if (activeAssignment?.id !== binding.assignment_event_id) {
446
+ if (allowSuperseded)
447
+ return null;
448
+ throw new Error(`assignment event ${binding.assignment_event_id} is no longer current`);
449
+ }
450
+ const process = await client.call("GET", `/projects/${encodeURIComponent(creds.project)}/process`);
451
+ const { prepareWorktreeForWatcher } = await import("./wu.js");
452
+ const prepared = prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []);
453
+ return { number: binding.work_unit_number, path: prepared.path, status: unit.status };
454
+ }
455
+ catch (error) {
456
+ throw new CliError("unit_worktree_prepare_failed", `watcher could not prepare the worktree for WU #${binding.work_unit_number}; no turn was started and the unit remains unchanged: ${error.message}`);
457
+ }
458
+ }
399
459
  const CODEX_THREAD_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
400
460
  /** Follow a Codex exec that opens a new thread, as soon as the session hook records its id. */
401
461
  export function followCurrentCodexProbe(name, initialThread) {
@@ -466,7 +526,9 @@ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, bef
466
526
  `Start it now with: b9s wu start ${unit.number} --context-checkpoint-ref ${clear.checkpoint_ref}`,
467
527
  `That command completes the pending clear only after this new thread is locally recorded. If any step fails, report the named failure and leave the unit unstarted.`,
468
528
  ].join("\n\n");
469
- const delivered = await deliver(name, command, prompt, `fresh-thread clear for WU #${unit.number}`, "direct", new TextEncoder().encode(prompt).byteLength, log, "context clear; ", seq, turnSink, {}, undefined, model, false, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}) }, allowTurn);
529
+ const clearEvent = typeof unit.owner_agent_id === "string" ? currentAssignmentEvent(unitResponse.events ?? [], unit.owner_agent_id, creds.agent) : null;
530
+ const clearAssignment = clearEvent ? { work_unit_number: unit.number, assignment_event_id: clearEvent.id } : null;
531
+ const delivered = await deliver(name, command, prompt, `fresh-thread clear for WU #${unit.number}`, "direct", new TextEncoder().encode(prompt).byteLength, log, "context clear; ", seq, turnSink, {}, undefined, model, false, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), workUnitBinding: clearAssignment }, allowTurn);
470
532
  if (!delivered)
471
533
  return { sent: false, recoveryBriefDelivered: false };
472
534
  const queuedAt = Date.now();
@@ -611,6 +673,21 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
611
673
  ...(u ? [`Run these, in order, to read it all:`, ...u.readCommands.map((c) => ` ${c}`)] : []),
612
674
  `Reply in chat with b9s send, not here. Your role and the project's process: b9s me, b9s process.`,
613
675
  ];
676
+ const basePayload = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
677
+ const eventBinding = deliveredAssignmentBinding(u?.turn_binding_candidates ?? [], basePayload?.delivery.selected_direct_ids ?? []);
678
+ const savedBinding = state.watch_turn_binding?.work_unit_number && state.watch_turn_binding.assignment_event_id
679
+ ? { work_unit_number: state.watch_turn_binding.work_unit_number, assignment_event_id: state.watch_turn_binding.assignment_event_id }
680
+ : null;
681
+ const bindingToPrepare = eventBinding ?? savedBinding;
682
+ let preparedWorktree = null;
683
+ if (turnSink && bindingToPrepare) {
684
+ preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare, !eventBinding && Boolean(savedBinding));
685
+ if (preparedWorktree) {
686
+ wakePrefix.push(preparedWorktree.status === "assigned"
687
+ ? `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}. Run b9s wu start ${preparedWorktree.number} from this checkout to record the start, then work in that path.`
688
+ : `The watcher prepared WU #${preparedWorktree.number}'s worktree at ${preparedWorktree.path}; continue working there.`);
689
+ }
690
+ }
614
691
  const payload = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
615
692
  const wake = payload?.text ?? [...wakePrefix, "Nothing else is new.", ...wakeSuffix].join("\n");
616
693
  const total = u ? u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest + u.counts.notices : 0;
@@ -619,7 +696,18 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
619
696
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
620
697
  const line = wake;
621
698
  debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
622
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId }, allowTurn))) {
699
+ const workUnitBinding = deliveredAssignmentBinding(u?.turn_binding_candidates ?? [], payload?.delivery.selected_direct_ids ?? []) ?? (preparedWorktree ? bindingToPrepare : null);
700
+ let turnExec = exec;
701
+ let turnCwd;
702
+ if (turnSink && provider && dependencies.claudeRuntime?.sandbox === "workspace-write")
703
+ turnCwd = preparedWorktree?.path ?? process.cwd();
704
+ if (turnSink && dependencies.claudeRuntime && turnExec?.includes(CLAUDE_SETTINGS_PLACEHOLDER)) {
705
+ const runtime = dependencies.claudeRuntime;
706
+ const cwd = turnCwd ?? process.cwd();
707
+ const args = claudeSettings(runtime.sandbox, model, runtime.effort, cwd, configRoot(), runtime.writableRoots);
708
+ turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
709
+ }
710
+ if (!(await deliver(name, turnExec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId, workUnitBinding, ...(turnCwd ? { cwd: turnCwd } : {}) }, allowTurn))) {
623
711
  debug("no wake: delivery failed or turn guard denied the launch");
624
712
  return { sent: false, recoveryBriefDelivered: false };
625
713
  }
@@ -649,6 +737,7 @@ async function recoveryBriefText(name, log) {
649
737
  }
650
738
  }
651
739
  /** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
740
+ const CLAUDE_SETTINGS_PLACEHOLDER = "__B9S_CLAUDE_TURN_SETTINGS__";
652
741
  export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}, allowTurn) {
653
742
  if (!exec) {
654
743
  process.stdout.write(wake + "\n");
@@ -668,14 +757,25 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
668
757
  if (allowTurn && !(await allowTurn()))
669
758
  return false;
670
759
  beforeTurn?.();
671
- turnSink((dependencies.startTurn ?? startTurn)(cmd, {
760
+ const launchedAt = new Date().toISOString();
761
+ const binding = dependencies.workUnitBinding ?? null;
762
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_binding: { launched_at: launchedAt, started_at: null, work_unit_number: binding?.work_unit_number ?? null, assignment_event_id: binding?.assignment_event_id ?? null } }));
763
+ const startedTurn = (dependencies.startTurn ?? startTurn)(cmd, {
672
764
  ...env,
673
765
  BSCHAT_AGENT: name,
674
766
  ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
675
767
  ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
676
768
  ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
677
769
  ...providerEnv,
678
- }, seq, turnStdin ? wake : undefined));
770
+ }, seq, turnStdin ? wake : undefined, binding, dependencies.cwd);
771
+ const startedAt = Number.isFinite(startedTurn.startedMs) ? new Date(startedTurn.startedMs).toISOString() : launchedAt;
772
+ updateState(name, (onDisk) => {
773
+ const pending = onDisk.watch_turn_binding;
774
+ if (!pending || pending.work_unit_number !== (binding?.work_unit_number ?? null) || pending.assignment_event_id !== (binding?.assignment_event_id ?? null))
775
+ return undefined;
776
+ return { ...onDisk, watch_turn_binding: { ...pending, launched_at: startedAt } };
777
+ });
778
+ turnSink(startedTurn);
679
779
  }
680
780
  else {
681
781
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
@@ -826,6 +926,16 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
826
926
  if (turn) {
827
927
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
828
928
  turn.confirmed = true;
929
+ const phase = probe.phase();
930
+ if (!("missing" in phase) && phase.running && phase.startedAt) {
931
+ const launchedAt = new Date(turn.startedMs).toISOString();
932
+ updateState(name, (onDisk) => {
933
+ const pending = onDisk.watch_turn_binding;
934
+ if (!pending || pending.launched_at !== launchedAt)
935
+ return undefined;
936
+ return { ...onDisk, watch_turn_binding: { ...pending, started_at: phase.startedAt } };
937
+ }, env);
938
+ }
829
939
  await ackTurn(name, turn.seq, log, env);
830
940
  log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
831
941
  }
@@ -1501,7 +1611,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1501
1611
  bindSession(sess.kind, sess.id, name);
1502
1612
  out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout ${plistLaunchdDomain(path)}/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
1503
1613
  }
1504
- export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
1614
+ export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : []), ...(t.claudeRuntime ? ["--turn-claude-runtime", JSON.stringify(t.claudeRuntime)] : [])] : []);
1505
1615
  function escapeXml(s) {
1506
1616
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1507
1617
  }
@@ -19,6 +19,7 @@ import { tmpdir } from "node:os";
19
19
  import { chooseAgentContextAction, contextModeFromRuntime, explicitContextCompactSupport, hasCorrectionHistory } from "../context-policy.js";
20
20
  import { formatConfidenceMatrix, formatExplorationSummary, formatUnitRoutingExplanation } from "./routing-admin.js";
21
21
  import { formatStandingRuleSet } from "../standing-rules.js";
22
+ import { projectOf } from "./agent.js";
22
23
  /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
23
24
  export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
24
25
  return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
@@ -35,6 +36,7 @@ export function scopeEditFromArgs(p) {
35
36
  const append = str(p.flags, "append");
36
37
  const scope = str(p.flags, "scope");
37
38
  const note = str(p.flags, "note");
39
+ const plain_summary = str(p.flags, "plain-summary") ?? str(p.flags, "summary");
38
40
  if (Number(replacement) + Number(append !== undefined) + Number(scope !== undefined) !== 1)
39
41
  throw new CliError("usage", "choose exactly one of --replace, --append, or --scope");
40
42
  if (!note)
@@ -43,14 +45,14 @@ export function scopeEditFromArgs(p) {
43
45
  const pieces = p.positionals.slice(3);
44
46
  if (pieces.length !== 2 || !pieces[0] || !pieces[1])
45
47
  throw new CliError("usage", "--replace needs two positional strings: '<old>' '<new>'");
46
- return { replace: { old: pieces[0], new: pieces[1] }, note };
48
+ return { replace: { old: pieces[0], new: pieces[1] }, note, ...(plain_summary === undefined ? {} : { plain_summary }) };
47
49
  }
48
50
  if (append !== undefined) {
49
51
  if (!append.trim())
50
52
  throw new CliError("usage", "--append needs non-empty text");
51
- return { append, note };
53
+ return { append, note, ...(plain_summary === undefined ? {} : { plain_summary }) };
52
54
  }
53
- return { scope: scope, note };
55
+ return { scope: scope, note, ...(plain_summary === undefined ? {} : { plain_summary }) };
54
56
  }
55
57
  export function scopeOnlyOutput(unit, only) {
56
58
  return only ? unit.scope : null;
@@ -537,9 +539,7 @@ export async function wu(p, out) {
537
539
  const name = resolveAgentName(str(p.flags, "as"));
538
540
  const creds = loadAgent(name);
539
541
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
540
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
541
- if (!project)
542
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
542
+ const project = projectOf(p, creds);
543
543
  const base = `/projects/${project}/work-units`;
544
544
  const list = (k) => {
545
545
  const raw = str(p.flags, k);
@@ -636,7 +636,7 @@ export async function wu(p, out) {
636
636
  const priority = str(p.flags, "priority");
637
637
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
638
638
  throw new CliError("usage", "--priority must be urgent or normal");
639
- const r = await client.call("POST", base, { client_id: clientId, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
639
+ const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
640
640
  const n = r.unit.number;
641
641
  const created = createdReceipt(r.unit);
642
642
  if (r.unit.waiting_on != null) {
@@ -691,7 +691,7 @@ export async function wu(p, out) {
691
691
  const scope = await scopeText();
692
692
  const replay = str(p.flags, "replay-of");
693
693
  const clientId = randomUUID();
694
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, 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: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
694
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
695
695
  out.print(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, createdReceipt(r.unit));
696
696
  return;
697
697
  }
@@ -932,7 +932,8 @@ export async function wu(p, out) {
932
932
  const hasEditMode = bool(p.flags, "replace") || str(p.flags, "append") !== undefined;
933
933
  if (Number(hasScopeSource) + Number(hasEditMode) !== 1)
934
934
  throw new CliError("usage", "choose exactly one scope source or edit mode (--scope, --scope-file, --scope-from, --replace, or --append)");
935
- const edit = hasScopeSource ? { scope: await scopeText(), note: note ?? "" } : scopeEditFromArgs(p);
935
+ const plainSummary = str(p.flags, "plain-summary") ?? str(p.flags, "summary");
936
+ const edit = hasScopeSource ? { scope: await scopeText(), note: note ?? "", ...(plainSummary === undefined ? {} : { plain_summary: plainSummary }) } : scopeEditFromArgs(p);
936
937
  if (("scope" in edit && !edit.scope.trim()) || !edit.note)
937
938
  throw new CliError("usage", 'wu scope <n> --scope "what it now covers" | --scope-file <path> | --scope-from <n> | --replace <old> <new> | --append "clause" --note "why"');
938
939
  const actionResult = "Scope amended; the owner and reviewers were told.";
@@ -991,12 +992,15 @@ export async function wu(p, out) {
991
992
  case "changes": {
992
993
  const note = str(p.flags, "note");
993
994
  const unmet = str(p.flags, "unmet");
995
+ const plainSummary = str(p.flags, "plain-summary") ?? str(p.flags, "summary");
994
996
  if (!note)
995
997
  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"`);
996
998
  const cause = str(p.flags, "cause");
997
999
  if (sub === "changes" && !cause)
998
1000
  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"');
999
- const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
1001
+ if (sub === "changes" && !plainSummary?.trim())
1002
+ throw new CliError("usage", 'wu changes <n> --summary "plain explanation of the revision" --cause <cause> --unmet "<cited clause>" --note "what must change"');
1003
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "changes" ? { plain_summary: plainSummary } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
1000
1004
  out.print(fmt(r.unit), r);
1001
1005
  return;
1002
1006
  }
@@ -1140,7 +1144,7 @@ export async function wu(p, out) {
1140
1144
  const t = p.positionals[3];
1141
1145
  if (!t)
1142
1146
  throw new CliError("usage", "wu target <n> <branch|default>");
1143
- const r = await client.call("POST", `${base}/${num()}/target`, { target: t === "default" ? null : t });
1147
+ const r = await client.call("POST", `${base}/${num()}/target`, { target: t === "default" ? null : t, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }) });
1144
1148
  out.print(fmt(r.unit), r);
1145
1149
  return;
1146
1150
  }
@@ -1304,9 +1308,7 @@ export async function processCmd(p, out) {
1304
1308
  const name = resolveAgentName(str(p.flags, "as"));
1305
1309
  const creds = loadAgent(name);
1306
1310
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
1307
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1308
- if (!project)
1309
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1311
+ const project = projectOf(p, creds);
1310
1312
  const [r, b] = await Promise.all([client.call("GET", `/projects/${project}/process`),
1311
1313
  // Only the roles are needed. This used to fetch the whole Work board, the heaviest read in the
1312
1314
  // API, and every agent runs this command after each process change.
@@ -1372,6 +1374,12 @@ function assertNotShaBranch(branch, flag = "--branch") {
1372
1374
  throw new CliError("usage", `refusing ${flag} ${branch}: never name a branch after a commit SHA`, "Pass a descriptive branch name like wu/123-fix or omit --branch to create one from origin's target.");
1373
1375
  }
1374
1376
  }
1377
+ export function prepareWorktreeForWatcher(n, unit, def, exclude = []) {
1378
+ const prepared = prepareWorktree(n, unit, def, { positionals: [], flags: {} }, exclude);
1379
+ if (prepared.mode === "here")
1380
+ throw new CliError("unit_worktree_prepare_failed", "watchers must prepare a linked unit worktree; --here is not available in watcher preparation");
1381
+ return { path: prepared.path, branch: prepared.branch, mode: prepared.mode, created: prepared.created, branchCreated: prepared.branchCreated };
1382
+ }
1375
1383
  function prepareWorktree(n, unit, def, p, exclude = []) {
1376
1384
  // The unit's own target when it has one: a lane or release branch the work lands in.
1377
1385
  const target = unit.target ?? def.merge.target_branch;
@@ -1408,7 +1416,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
1408
1416
  branchCreated = true;
1409
1417
  log(`created ${pinned} from origin/${pinned}`);
1410
1418
  }
1411
- const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites()) : { created: false };
1419
+ const result = !existing ? ensureUnitWorktree(path, pinned, baseRef, log, exclude) : { created: false, repaired: false };
1412
1420
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
1413
1421
  }
1414
1422
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -1422,9 +1430,18 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
1422
1430
  baseRef = at;
1423
1431
  }
1424
1432
  const branchCreated = fullSha(`refs/heads/${branch}`) === null;
1425
- const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
1433
+ const result = ensureUnitWorktree(path, branch, baseRef, log, exclude);
1426
1434
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
1427
1435
  }
1436
+ function ensureUnitWorktree(path, branch, baseRef, log, exclude) {
1437
+ try {
1438
+ return ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritSandboxUrlRewrites());
1439
+ }
1440
+ catch (error) {
1441
+ const cause = error.message;
1442
+ throw new CliError("worktree_prepare_failed", `cannot prepare worktree ${path} on ${branch}: ${cause}. In turn mode the watcher prepares unit worktrees before the turn; no fallback was applied.`);
1443
+ }
1444
+ }
1428
1445
  /** Select the replay commit from the same target ref used to create its worktree. */
1429
1446
  export function replayBaseRef(baseRef, createdAt, cwd = process.cwd()) {
1430
1447
  return commitAtTime(baseRef, createdAt, cwd);
@@ -1434,9 +1451,7 @@ export async function milestones(p, out) {
1434
1451
  const name = resolveAgentName(str(p.flags, "as"));
1435
1452
  const creds = loadAgent(name);
1436
1453
  const client = Client.forAgent(creds, undefined, { presence: false });
1437
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1438
- if (!project)
1439
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1454
+ const project = projectOf(p, creds);
1440
1455
  return milestonesWith(client, project, p.positionals[1], p, out);
1441
1456
  }
1442
1457
  /**
@@ -1481,9 +1496,7 @@ export async function milestone(p, out) {
1481
1496
  const name = resolveAgentName(str(p.flags, "as"));
1482
1497
  const creds = loadAgent(name);
1483
1498
  const client = Client.forAgent(creds, undefined, { presence: false });
1484
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1485
- if (!project)
1486
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1499
+ const project = projectOf(p, creds);
1487
1500
  return milestoneWith(client, project, p.positionals[1], p.positionals[2], p, out, p.positionals.slice(3));
1488
1501
  }
1489
1502
  /** One milestone, shared by agents (`b9s milestone`) and the operator (`b9s-admin milestone <project>`). */
@@ -1599,9 +1612,7 @@ export async function record(p, out) {
1599
1612
  const name = resolveAgentName(str(p.flags, "as"));
1600
1613
  const creds = loadAgent(name);
1601
1614
  const client = Client.forAgent(creds, undefined, { presence: false });
1602
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1603
- if (!project)
1604
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1615
+ const project = projectOf(p, creds);
1605
1616
  const by = str(p.flags, "by");
1606
1617
  if (by === "matrix") {
1607
1618
  const mode = str(p.flags, "mode");
@@ -1653,9 +1664,7 @@ export async function lock(p, out) {
1653
1664
  const name = resolveAgentName(str(p.flags, "as"));
1654
1665
  const creds = loadAgent(name);
1655
1666
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
1656
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1657
- if (!project)
1658
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1667
+ const project = projectOf(p, creds);
1659
1668
  const cmd = p.positionals[0];
1660
1669
  const lockName = p.positionals[1];
1661
1670
  if (cmd === "locks") {
@@ -1754,9 +1763,7 @@ export async function askOperator(p, out) {
1754
1763
  const name = resolveAgentName(str(p.flags, "as"));
1755
1764
  const creds = loadAgent(name);
1756
1765
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
1757
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1758
- if (!project)
1759
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1766
+ const project = projectOf(p, creds);
1760
1767
  if (p.positionals[1] === "withdraw") {
1761
1768
  const id = p.positionals[2];
1762
1769
  const note = str(p.flags, "note")?.trim();
@@ -1891,9 +1898,7 @@ export async function explainAsk(p, out) {
1891
1898
  const name = resolveAgentName(str(p.flags, "as"));
1892
1899
  const creds = loadAgent(name);
1893
1900
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), { effort: str(p.flags, "effort") });
1894
- const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1895
- if (!project)
1896
- throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1901
+ const project = projectOf(p, creds);
1897
1902
  const id = p.positionals[1];
1898
1903
  const text = p.positionals.slice(2).join(" ").trim();
1899
1904
  if (!id || !text)
package/dist/harnesses.js CHANGED
@@ -390,14 +390,18 @@ export function claudeTranscript(session) {
390
390
  const root = join(claudeHome(), "projects");
391
391
  if (!existsSync(root))
392
392
  return null;
393
+ let newest = null;
393
394
  for (const d of readdirSync(root, { withFileTypes: true })) {
394
395
  if (!d.isDirectory())
395
396
  continue;
396
397
  const f = join(root, d.name, `${session}.jsonl`);
397
- if (existsSync(f))
398
- return f;
398
+ if (!existsSync(f))
399
+ continue;
400
+ const mtimeMs = statSync(f).mtimeMs;
401
+ if (!newest || mtimeMs > newest.mtimeMs)
402
+ newest = { path: f, mtimeMs };
399
403
  }
400
- return null;
404
+ return newest?.path ?? null;
401
405
  }
402
406
  /** The last turn's output (`claude -p --output-format json`), written by the watcher's turn command. */
403
407
  export const claudeResultFile = (ref) => join(configRoot(), "logs", `turn.${ref.replace("/", ".")}.json`);
package/dist/heartbeat.js CHANGED
@@ -84,8 +84,14 @@ export async function heartbeatIfActive(client, src, prev, windowSeconds, log) {
84
84
  return cur;
85
85
  }
86
86
  /** A persistent watcher proves its own wake path independently of harness file activity. */
87
- export async function reportWatcherHeartbeat(client, intervalSeconds, mode) {
88
- await client.call("POST", "/agents/me/watcher/heartbeat", { interval_seconds: intervalSeconds, mode });
87
+ export async function reportWatcherHeartbeat(client, intervalSeconds, mode, turn) {
88
+ await client.call("POST", "/agents/me/watcher/heartbeat", {
89
+ interval_seconds: intervalSeconds,
90
+ mode,
91
+ turn_started_at: mode === "turn" ? turn?.startedAt ?? null : null,
92
+ work_unit_number: mode === "turn" ? turn?.binding?.work_unit_number ?? null : null,
93
+ assignment_event_id: mode === "turn" ? turn?.binding?.assignment_event_id ?? null : null,
94
+ });
89
95
  }
90
96
  /**
91
97
  * The hook variant: the hook running is itself the evidence, so report now, throttled by the