benignswarm 0.12.131 → 0.12.133

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/args.js CHANGED
@@ -11,7 +11,7 @@ export const STRING_FLAGS = [
11
11
  "as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
12
12
  "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
13
13
  "cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
14
- "name", "out", "token", "token-file", "job", "gate-command", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
14
+ "name", "out", "token", "token-file", "job", "gate-command", "gate-override-note", "head", "baseline", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
15
15
  "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
17
  "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
@@ -20,7 +20,7 @@ export const STRING_FLAGS = [
20
20
  "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
21
21
  "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope",
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
23
- "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
23
+ "require-pushed", "require-gate-receipt", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
25
  "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "api", "nonce",
26
26
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
@@ -37,7 +37,7 @@ export const STRING_FLAGS = [
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
- "metadata-file", "confirm-agent", "confirm-parked",
40
+ "metadata-file", "confirm-agent", "confirm-parked", "step",
41
41
  ];
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
@@ -47,7 +47,7 @@ export const BOOL_FLAGS = [
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
49
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
- "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible",
50
+ "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "no-commits-beyond-target",
51
51
  ];
52
52
  export function parse(argv) {
53
53
  const options = {};
@@ -553,11 +553,38 @@ async function role(action, rest, p, out) {
553
553
  throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
554
554
  }
555
555
  async function workUnitAdmin(action, rest, p, out) {
556
+ if (action === "done" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
557
+ const project = rest[0];
558
+ const number = Number(rest[1]);
559
+ const merged = str(p.flags, "merged");
560
+ const gateOverrideNote = str(p.flags, "gate-override-note");
561
+ const noSource = bool(p.flags, "no-source");
562
+ const evidence = str(p.flags, "evidence")?.split(",").filter(Boolean) ?? [];
563
+ const noCommitsBeyondTarget = bool(p.flags, "no-commits-beyond-target");
564
+ if (!merged && !gateOverrideNote && !noSource)
565
+ throw new CliError("usage", `b9s-admin wu done ${project} ${number} --merged <sha> [--gate-override-note "why"]`);
566
+ if (merged && noSource)
567
+ throw new CliError("usage", "--merged and --no-source are mutually exclusive");
568
+ if (noSource && evidence.length === 0)
569
+ throw new CliError("usage", "--no-source requires --evidence id[,id...]");
570
+ if (noSource && !noCommitsBeyondTarget)
571
+ throw new CliError("usage", "--no-source requires --no-commits-beyond-target confirmation");
572
+ if (gateOverrideNote !== undefined && !gateOverrideNote.trim())
573
+ throw new CliError("usage", "--gate-override-note must explain why the exact commit has no passing gate receipt");
574
+ const result = await adminClient(p).call("POST", `/projects/${encodeURIComponent(project)}/work-units/${number}/done`, {
575
+ note: str(p.flags, "note") ?? "",
576
+ ...(merged ? { merged } : {}),
577
+ ...(gateOverrideNote !== undefined ? { gate_override_note: gateOverrideNote } : {}),
578
+ ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: true } : {}),
579
+ });
580
+ out.print(`WU #${number} marked done${merged ? ` (merged ${merged})` : noSource ? " (evidence only; no merge commit)" : ""}${gateOverrideNote ? " (operator gate override recorded)" : ""}`, result);
581
+ return;
582
+ }
556
583
  if (action === "required-class" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
557
584
  return runRequiredClassUpdate(adminClient(p), rest[0], Number(rest[1]), p, out);
558
585
  }
559
586
  if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
560
- throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
587
+ throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
561
588
  const to = str(p.flags, "to");
562
589
  if (!to)
563
590
  throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
@@ -376,6 +376,7 @@ export async function gatherUpdates(name, opts) {
376
376
  rendered: lines[index],
377
377
  work_unit_number: message.work_unit_number,
378
378
  assignment_event_id: message.assignment_event_id,
379
+ project: message.project,
379
380
  })) : [];
380
381
  const directTimes = [
381
382
  ...messages.filter(isDirectMessage).map((message) => message.created_at),
@@ -24,9 +24,9 @@ export async function runUnderLock(o, deps) {
24
24
  const label = commandLabel(o.command);
25
25
  const base = `/projects/${o.project}/locks/${o.lock}`;
26
26
  const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
27
- const release = async () => {
27
+ const release = async (completion) => {
28
28
  try {
29
- await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token });
29
+ await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
30
30
  }
31
31
  catch (error) {
32
32
  throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: b9s unlock ${o.lock}${o.shared ? " --shared" : ""} --job ${o.jobId}`);
@@ -57,13 +57,15 @@ export async function runUnderLock(o, deps) {
57
57
  try {
58
58
  await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label });
59
59
  deps.log(`job ${o.jobId} holds ${o.lock}; running: ${label}`);
60
- code = await deps.run(o.command);
60
+ const result = await deps.run(o.command);
61
+ code = typeof result === "number" ? result : result.exit_code;
62
+ await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
61
63
  }
62
64
  catch (error) {
63
- await release();
65
+ if (!error || !(error instanceof CliError) || error.code !== "lock_release_failed")
66
+ await release();
64
67
  throw error;
65
68
  }
66
- await release();
67
69
  deps.log(`${o.lock} released after ${Math.round((now() - startedMs) / 1000)} s; the command exited ${code}.`);
68
70
  return code;
69
71
  }
@@ -86,10 +88,22 @@ export function processDeps(call, log) {
86
88
  wake = () => { clearTimeout(timer); wake = undefined; resolve(); };
87
89
  }),
88
90
  run: (command) => new Promise((resolve, reject) => {
89
- const child = spawn(command[0], command.slice(1), { stdio: "inherit" });
91
+ const child = spawn(command[0], command.slice(1), { stdio: ["inherit", "pipe", "inherit"] });
92
+ let output = "";
93
+ child.stdout?.on("data", (chunk) => {
94
+ process.stdout.write(chunk);
95
+ if (output.length < 8192)
96
+ output += chunk.toString("utf8").slice(0, 8192 - output.length);
97
+ });
90
98
  forward = (signal) => { child.kill(signal); };
91
99
  child.once("error", (error) => { forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
92
- child.once("exit", (code, signal) => { forward = undefined; resolve(code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0)); });
100
+ child.once("exit", (code, signal) => {
101
+ forward = undefined;
102
+ const exit_code = code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0);
103
+ const baseline = output.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
104
+ const testedTree = output.match(/^gate: tested tree ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
105
+ resolve({ exit_code, ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
106
+ });
93
107
  }),
94
108
  dispose: () => { for (const signal of signals)
95
109
  process.off(signal, onSignal); },
@@ -25,7 +25,7 @@ import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, r
25
25
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
26
26
  import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
27
27
  import { bootTimeMs } from "../boot-time.js";
28
- import { bindingForObservedTurn } from "../turn-binding.js";
28
+ import { observedTurnBindingFields } from "../turn-binding.js";
29
29
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
30
30
  import { imageCacheBaseDir, imageCacheProjectRoot, projectsWithImageCaches } from "../image-caches.js";
31
31
  import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
@@ -119,7 +119,7 @@ export function turnFaultSessionFields(fault, agent) {
119
119
  const binding = agent ? readState(agent).watch_turn_binding : undefined;
120
120
  return {
121
121
  turn_fault_at: new Date(fault.at).toISOString(),
122
- ...(binding?.started_at ? { work_unit_number: binding.work_unit_number, assignment_event_id: binding.assignment_event_id } : {}),
122
+ ...(binding?.started_at ? { work_unit_number: binding.work_unit_number, assignment_event_id: binding.assignment_event_id, work_unit_binding_reason: binding.reason ?? null } : {}),
123
123
  };
124
124
  }
125
125
  const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
@@ -2079,12 +2079,11 @@ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
2079
2079
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
2080
2080
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
2081
2081
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
2082
- const binding = bindingForObservedTurn(ph.startedAt, savedBinding);
2082
+ const binding = observedTurnBindingFields(ph.startedAt, savedBinding);
2083
2083
  return { turn: {
2084
2084
  running: ph.running,
2085
2085
  since: ph.startedAt,
2086
- work_unit_number: binding?.work_unit_number ?? null,
2087
- assignment_event_id: binding?.assignment_event_id ?? null,
2086
+ ...binding,
2088
2087
  ...(!ph.running && !ph.lastError && ph.startedAt ? { completed_at: ph.lastEventAt } : {}),
2089
2088
  ...(!ph.running && ph.lastError && ph.lastErrorAt ? { turn_fault_at: ph.lastErrorAt, error: ph.lastError } : {}),
2090
2089
  }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null, turn_guard: busyTurnPause(readState(agent).turn_guard, turnCap, Date.now()), ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
@@ -98,13 +98,20 @@ export function definitionPatch(p, cur) {
98
98
  if (integ !== undefined)
99
99
  merge.integrator_role = integ === "none" ? null : integ;
100
100
  const gate = str(p.flags, "gate-command");
101
- if (gate !== undefined)
101
+ if (gate !== undefined) {
102
102
  merge.gate_command = gate === "none" || gate === "" ? null : gate;
103
+ // Changing the explicit gate declaration applies its documented default unless the operator
104
+ // also supplies an explicit receipt-policy value in this command.
105
+ merge.require_gate_receipt = merge.gate_command !== null;
106
+ }
103
107
  for (const [flag, key] of [["require-rebased", "require_rebased"], ["require-merge-commit", "require_merge_commit"], ["require-pushed", "require_pushed"]]) {
104
108
  const v = yesNo(str(p.flags, flag), flag);
105
109
  if (v !== undefined)
106
110
  merge[key] = v;
107
111
  }
112
+ const requireGateReceipt = yesNo(str(p.flags, "require-gate-receipt"), "require-gate-receipt");
113
+ if (requireGateReceipt !== undefined)
114
+ merge.require_gate_receipt = requireGateReceipt;
108
115
  if (Object.keys(merge).length)
109
116
  d.merge = { ...cur.merge, ...merge };
110
117
  const steward = {};
@@ -129,7 +136,7 @@ function describeProcess(r) {
129
136
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; nothing published yet)" : ""}`,
130
137
  ` timing: review SLA ${d.review_sla_minutes} min, takeover ${d.escalate_after_minutes} min, ${d.max_open_per_agent} open / ${d.max_in_progress_per_agent} in progress per agent`,
131
138
  ` requires: scope ${d.require_scope ? "yes" : "no"}, evidence to submit ${d.require_evidence_to_submit ? "yes" : "no"}; default approver ${d.default_approver_role ?? "none"}; assigners ${d.assigners.join(", ") || "none"}`,
132
- ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}; gate ${m.gate_command ?? "none"}`,
139
+ ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}; gate ${m.gate_command ?? "none"}; gate receipt required ${m.require_gate_receipt ? "yes" : "no"}`,
133
140
  ` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
134
141
  ` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
135
142
  ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (b9s-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
@@ -204,7 +211,7 @@ export async function processAdmin(action, rest, p, out) {
204
211
  if (!Object.keys(definition).length)
205
212
  throw new CliError("usage", action === "timing"
206
213
  ? "admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--default-approver role|none]"
207
- : "admin process merge <project> [--target branch] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased yes|no] [--require-merge-commit yes|no] [--require-pushed yes|no]");
214
+ : "admin process merge <project> [--target branch] [--merged-by owner|approver|integrator] [--integrator-role r] [--gate-command <cmd|none>] [--require-gate-receipt yes|no] [--require-rebased yes|no] [--require-merge-commit yes|no] [--require-pushed yes|no]");
208
215
  return publish({ definition }, Object.keys(definition).join(", "));
209
216
  }
210
217
  case "assigners": {
@@ -48,11 +48,16 @@ function body(p) {
48
48
  if (!text?.trim())
49
49
  throw new CliError("usage", "rule add/supersede needs --text <rule text>");
50
50
  const conflicts = str(p.flags, "conflicts-with");
51
+ const step = str(p.flags, "step");
52
+ if (step !== undefined && !["cut", "start", "submit", "verdict", "merge", "close"].includes(step)) {
53
+ throw new CliError("usage", "--step must be cut, start, submit, verdict, merge, or close");
54
+ }
51
55
  return {
52
56
  text,
53
57
  compatibility_confirmed: true,
54
58
  ...(str(p.flags, "expires-at") === undefined ? {} : { expires_at: str(p.flags, "expires-at") }),
55
59
  ...(conflicts === undefined ? {} : { conflicts_with: conflicts.split(",").map((value) => value.trim()).filter(Boolean) }),
60
+ ...(step === undefined ? {} : { step }),
56
61
  ...(str(p.flags, "source-channel-id") === undefined ? {} : { source_channel_id: str(p.flags, "source-channel-id") }),
57
62
  ...(str(p.flags, "source-message-id") === undefined ? {} : { source_message_id: str(p.flags, "source-message-id") }),
58
63
  };
@@ -108,6 +113,7 @@ async function runRuleAction(client, project, action, identifier, p, out) {
108
113
  throw new CliError("usage", "rule <list|show|add|supersede|retire>");
109
114
  }
110
115
  export async function standingRuleCommand(p, out) {
116
+ validateStep(p);
111
117
  const name = resolveAgentName(str(p.flags, "as"));
112
118
  const creds = loadAgent(name);
113
119
  const project = projectOf(p, creds);
@@ -117,6 +123,7 @@ export async function standingRuleCommand(p, out) {
117
123
  await runRuleAction(client, project, action ?? "list", identifier, p, out);
118
124
  }
119
125
  export async function standingRuleAdmin(action, rest, p, out) {
126
+ validateStep(p);
120
127
  const project = rest[0];
121
128
  if (!project)
122
129
  throw new CliError("usage", "b9s-admin rule <list|show|add|supersede|retire> <project> [rule-id] ...");
@@ -124,6 +131,12 @@ export async function standingRuleAdmin(action, rest, p, out) {
124
131
  const client = Client.forAdmin(creds);
125
132
  await runRuleAction(client, project, action ?? "list", rest[1], p, out);
126
133
  }
134
+ function validateStep(p) {
135
+ const step = str(p.flags, "step");
136
+ if (step !== undefined && !["cut", "start", "submit", "verdict", "merge", "close"].includes(step)) {
137
+ throw new CliError("usage", "--step must be cut, start, submit, verdict, merge, or close");
138
+ }
139
+ }
127
140
  export function formatOwnRuleSet(set, label) {
128
141
  return formatStandingRuleSet(set, label);
129
142
  }
@@ -422,13 +422,37 @@ async function waitIntervalOrStop(ms, stopped) {
422
422
  if (timer)
423
423
  clearTimeout(timer);
424
424
  }
425
+ /** Bind only when the server says this identity has exactly one active owner assignment. */
426
+ export async function resolveWatcherWorkUnitBinding(name) {
427
+ const creds = loadAgent(name);
428
+ const client = Client.forAgent(creds, undefined, { presence: false });
429
+ try {
430
+ const result = await client.call("GET", "/agents/me/work-unit-binding");
431
+ if (result.binding && Number.isSafeInteger(result.binding.work_unit_number) && Number(result.binding.work_unit_number) > 0
432
+ && typeof result.binding.assignment_event_id === "string" && result.binding.assignment_event_id
433
+ && typeof result.binding.project === "string" && result.binding.project) {
434
+ return { binding: { work_unit_number: Number(result.binding.work_unit_number), assignment_event_id: result.binding.assignment_event_id, project: result.binding.project }, reason: null };
435
+ }
436
+ if (result.reason === "agent has no in-progress work unit" || result.reason === "agent has multiple in-progress work units"
437
+ || result.reason === "current work-unit assignment event is unavailable") {
438
+ return { binding: null, reason: result.reason };
439
+ }
440
+ return { binding: null, reason: "current work-unit assignment event is unavailable" };
441
+ }
442
+ catch {
443
+ return { binding: null, reason: "current work-unit assignment event is unavailable" };
444
+ }
445
+ }
425
446
  /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
426
447
  async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
427
448
  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`);
449
+ const project = binding.project ?? creds.project;
450
+ if (!project)
451
+ throw new CliError("unit_worktree_prepare_failed", `cannot prepare WU #${binding.work_unit_number}: server did not identify its authorized project`);
452
+ if (creds.project && creds.project !== project)
453
+ throw new CliError("unit_worktree_prepare_failed", `cannot prepare WU #${binding.work_unit_number}: server project ${project} does not match ${name}'s project ${creds.project}`);
430
454
  const client = Client.forAgent(creds, undefined, { presence: false });
431
- const base = `/projects/${encodeURIComponent(creds.project)}/work-units/${binding.work_unit_number}`;
455
+ const base = `/projects/${encodeURIComponent(project)}/work-units/${binding.work_unit_number}`;
432
456
  try {
433
457
  const record = await client.call("GET", base);
434
458
  const unit = record.unit;
@@ -447,7 +471,7 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
447
471
  return null;
448
472
  throw new Error(`assignment event ${binding.assignment_event_id} is no longer current`);
449
473
  }
450
- const process = await client.call("GET", `/projects/${encodeURIComponent(creds.project)}/process`);
474
+ const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
451
475
  const { prepareWorktreeForWatcher } = await import("./wu.js");
452
476
  const prepared = prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []);
453
477
  return { number: binding.work_unit_number, path: prepared.path, status: unit.status };
@@ -673,15 +697,28 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
673
697
  ...(u ? [`Run these, in order, to read it all:`, ...u.readCommands.map((c) => ` ${c}`)] : []),
674
698
  `Reply in chat with b9s send, not here. Your role and the project's process: b9s me, b9s process.`,
675
699
  ];
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 }
700
+ let bindingResolution = null;
701
+ if (turnSink) {
702
+ try {
703
+ bindingResolution = await (dependencies.resolveWorkUnitBinding ?? resolveWatcherWorkUnitBinding)(name);
704
+ }
705
+ catch (error) {
706
+ log(`could not resolve the current work-unit binding: ${error.message}`);
707
+ bindingResolution = { binding: null, reason: "current work-unit assignment event is unavailable" };
708
+ }
709
+ }
710
+ const assignmentDelivery = u ? formatUpdates(omitMeasuresAlreadyIn(recoveryPrompt, u), wakePrefix, wakeSuffix) : null;
711
+ // Telemetry is bound only by the authoritative unique-assignment resolver. Worktree
712
+ // preparation can also follow a server-linked assignment delivered in this wake: when
713
+ // multiple units are active, the turn remains unbound, but the explicitly delivered unit
714
+ // still determines its checkout (prepareTurnWorktree revalidates owner and event).
715
+ const deliveredBinding = u
716
+ ? deliveredAssignmentBinding(u.turn_binding_candidates ?? [], assignmentDelivery?.delivery.selected_direct_ids ?? [])
680
717
  : null;
681
- const bindingToPrepare = eventBinding ?? savedBinding;
718
+ const bindingToPrepare = bindingResolution?.binding ?? deliveredBinding;
682
719
  let preparedWorktree = null;
683
720
  if (turnSink && bindingToPrepare) {
684
- preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare, !eventBinding && Boolean(savedBinding));
721
+ preparedWorktree = await (dependencies.prepareWorktree ?? prepareTurnWorktree)(name, bindingToPrepare);
685
722
  if (preparedWorktree) {
686
723
  wakePrefix.push(preparedWorktree.status === "assigned"
687
724
  ? `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.`
@@ -696,7 +733,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
696
733
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
697
734
  const line = wake;
698
735
  debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
699
- const workUnitBinding = deliveredAssignmentBinding(u?.turn_binding_candidates ?? [], payload?.delivery.selected_direct_ids ?? []) ?? (preparedWorktree ? bindingToPrepare : null);
736
+ const workUnitBinding = bindingResolution?.binding ?? null;
700
737
  let turnExec = exec;
701
738
  let turnCwd;
702
739
  if (turnSink && provider && dependencies.claudeRuntime?.sandbox === "workspace-write")
@@ -707,7 +744,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
707
744
  const args = claudeSettings(runtime.sandbox, model, runtime.effort, cwd, configRoot(), runtime.writableRoots);
708
745
  turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
709
746
  }
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))) {
747
+ 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, workUnitBindingReason: bindingResolution?.reason ?? null, ...(turnCwd ? { cwd: turnCwd } : {}) }, allowTurn))) {
711
748
  debug("no wake: delivery failed or turn guard denied the launch");
712
749
  return { sent: false, recoveryBriefDelivered: false };
713
750
  }
@@ -759,7 +796,7 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
759
796
  beforeTurn?.();
760
797
  const launchedAt = new Date().toISOString();
761
798
  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 } }));
799
+ 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, reason: binding ? null : dependencies.workUnitBindingReason ?? "agent has no in-progress work unit" } }));
763
800
  const startedTurn = (dependencies.startTurn ?? startTurn)(cmd, {
764
801
  ...env,
765
802
  BSCHAT_AGENT: name,
@@ -12,7 +12,7 @@ import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sess
12
12
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
13
13
  import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
14
14
  import { join, resolve } from "node:path";
15
- import { table } from "../output.js";
15
+ import { formatStepRules, table } from "../output.js";
16
16
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
17
17
  import { createRecoveryArchive } from "../recovery-archive.js";
18
18
  import { tmpdir } from "node:os";
@@ -569,7 +569,12 @@ export async function wu(p, out) {
569
569
  return n;
570
570
  };
571
571
  const tags = (u) => (u.tags.length ? u.tags.map((t) => `#${t}`).join(" ") : "(untagged)");
572
- const createdReceipt = (u) => ({ number: u.number, title: u.title, status: u.status, owner: u.owner_name ?? null });
572
+ const ruleText = (response, step) => formatStepRules(response, step);
573
+ const withRuleText = (text, response, step) => {
574
+ const rules = ruleText(response, step);
575
+ return rules ? `${text}\n${rules}` : text;
576
+ };
577
+ const createdReceipt = (u, response) => ({ number: u.number, title: u.title, status: u.status, owner: u.owner_name ?? null, ...(Array.isArray(response?.step_rules) ? { step_rules: response.step_rules } : {}) });
573
578
  const createdReceiptLine = (u) => `WU #${u.number} created: ${u.title}`;
574
579
  const fmt = (u) => {
575
580
  const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
@@ -638,14 +643,14 @@ export async function wu(p, out) {
638
643
  throw new CliError("usage", "--priority must be urgent or normal");
639
644
  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
645
  const n = r.unit.number;
641
- const created = createdReceipt(r.unit);
646
+ const created = createdReceipt(r.unit, r);
642
647
  if (r.unit.waiting_on != null) {
643
- out.print(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\nWait until ${r.unit.waits_on.map((on) => `WU #${on}`).join(", ")} closes, then start with: b9s wu start ${n}`, created);
648
+ out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\nWait until ${r.unit.waits_on.map((on) => `WU #${on}`).join(", ")} closes, then start with: b9s wu start ${n}`, r, "cut"), created);
644
649
  return;
645
650
  }
646
651
  // Report the irreversible create before any local worktree or start step can fail. JSON
647
652
  // callers receive this compact, stable receipt instead of the later start envelope.
648
- out.print(createdReceiptLine(r.unit), created);
653
+ out.print(withRuleText(createdReceiptLine(r.unit), r, "cut"), created);
649
654
  const contextDecision = await contextDecisionForStart(client, base, r.unit, name, p);
650
655
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
651
656
  const where = symbolicBranchAndHead(path);
@@ -680,7 +685,7 @@ export async function wu(p, out) {
680
685
  if (p.flags.after !== undefined)
681
686
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
682
687
  const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
683
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r);
688
+ out.print(withRuleText(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r, "cut"), r);
684
689
  return;
685
690
  }
686
691
  const title = p.positionals.slice(2).join(" ").trim();
@@ -692,7 +697,7 @@ export async function wu(p, out) {
692
697
  const replay = str(p.flags, "replay-of");
693
698
  const clientId = randomUUID();
694
699
  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
- out.print(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, createdReceipt(r.unit));
700
+ out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput(r.warnings ?? [])}`, r, "cut"), createdReceipt(r.unit, r));
696
701
  return;
697
702
  }
698
703
  case "park": {
@@ -773,7 +778,7 @@ export async function wu(p, out) {
773
778
  }
774
779
  throw error;
775
780
  }
776
- out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
781
+ out.print(withRuleText(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, r, "start"), { ...r, worktree: path, branch, mode });
777
782
  if (readState(name).pending_context_clear?.work_unit_number === n) {
778
783
  updateState(name, (onDisk) => {
779
784
  const clear = onDisk.pending_context_clear;
@@ -850,7 +855,7 @@ export async function wu(p, out) {
850
855
  const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
851
856
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
852
857
  const u = r.unit;
853
- 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);
858
+ out.print(withRuleText(`${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, "submit"), r);
854
859
  return;
855
860
  }
856
861
  case "reopen": {
@@ -1001,7 +1006,7 @@ export async function wu(p, out) {
1001
1006
  if (sub === "changes" && !plainSummary?.trim())
1002
1007
  throw new CliError("usage", 'wu changes <n> --summary "plain explanation of the revision" --cause <cause> --unmet "<cited clause>" --note "what must change"');
1003
1008
  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") } : {}) });
1004
- out.print(fmt(r.unit), r);
1009
+ out.print(withRuleText(fmt(r.unit), r, sub === "approve" ? "merge" : "verdict"), r);
1005
1010
  return;
1006
1011
  }
1007
1012
  case "classify": {
@@ -1028,8 +1033,10 @@ export async function wu(p, out) {
1028
1033
  return;
1029
1034
  }
1030
1035
  case "done": {
1036
+ if (str(p.flags, "gate-override-note") !== undefined)
1037
+ throw new CliError("forbidden", "only the operator can override a missing gate receipt; use b9s-admin wu done with --gate-override-note");
1031
1038
  const def = await processDef();
1032
- const merged = str(p.flags, "merged") ?? null;
1039
+ let merged = str(p.flags, "merged") ?? null;
1033
1040
  const noSource = bool(p.flags, "no-source");
1034
1041
  const evidence = list("evidence");
1035
1042
  if (noSource && merged)
@@ -1079,6 +1086,14 @@ export async function wu(p, out) {
1079
1086
  if (!checked.on)
1080
1087
  throw new CliError("not_merged", `${merged} is not on ${checked.ref}`, "Merge first, then pass the merge commit (or the branch head once it is on the target).");
1081
1088
  }
1089
+ // Receipts are keyed by the full commit identity. Keep abbreviated input convenient while
1090
+ // ensuring the server checks the same SHA the complete gate records.
1091
+ if (def.merge.require_gate_receipt) {
1092
+ const canonical = fullSha(merged);
1093
+ if (!canonical)
1094
+ throw new CliError("unknown_commit", `cannot resolve ${merged} to a full commit SHA`, "Fetch the merged commit and retry.");
1095
+ merged = canonical;
1096
+ }
1082
1097
  }
1083
1098
  else if (def.merge.require_merge_commit) {
1084
1099
  throw new CliError("usage", `this project's process requires the merge commit: b9s wu done ${num()} --merged <sha>`);
@@ -1089,7 +1104,7 @@ export async function wu(p, out) {
1089
1104
  ? await telemetryFromEvents(name, Array.isArray(doneRecord.events) ? doneRecord.events : [])
1090
1105
  : null;
1091
1106
  const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged, ...(telemetry ? { context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason } : {}), ...(noSource ? { no_source: true, evidence, no_commits_beyond_target: noCommitsBeyondTarget } : {}) });
1092
- out.print(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r);
1107
+ out.print(withRuleText(fmt(r.unit) + (verifiedRemoteTarget ? `\nverified on ${verifiedRemoteTarget}` : "") + cleanupUnitWorktree(r.unit.worktree, def, !!p.flags["keep-worktree"]), r, "close"), r);
1093
1108
  return;
1094
1109
  }
1095
1110
  case "merge": {
@@ -1191,7 +1206,7 @@ export async function wu(p, out) {
1191
1206
  const made = ensureReviewWorktree(path, remote);
1192
1207
  const ev = unit.evidence.map((e) => `evidence:${e}`).join(" ") || "(none)";
1193
1208
  const context = measureContextOutput(reviewDetail.measure_context, unit.expected_effect, unit.measured_effect);
1194
- out.print(`${fmt(unit)}${context ? `\n${context}` : ""}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (b9s evidence get <id>)\nVerdict: b9s wu approve ${n} --note "..." | b9s wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote, measure_context: reviewDetail.measure_context });
1209
+ out.print(withRuleText(`${fmt(unit)}${context ? `\n${context}` : ""}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (b9s evidence get <id>)\nVerdict: b9s wu approve ${n} --note "..." | b9s wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, reviewDetail, "verdict"), { ...reviewDetail, unit, worktree: path, head: remote, measure_context: reviewDetail.measure_context });
1195
1210
  return;
1196
1211
  }
1197
1212
  case "recovery": {
package/dist/help.js CHANGED
@@ -68,8 +68,8 @@ Agent commands
68
68
  b9s process the project's process: tag vocabulary, reviewers, wake-path warnings, scope templates, agreements and active standing rules
69
69
  b9s rule list [--project <p>] list authorized project rules; assigner history uses API WU #459
70
70
  b9s rule show <rule-id> [--project <p>]
71
- b9s rule add --scope account|project|role:<name>|agent:<name> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
72
- b9s rule supersede <rule-id> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
71
+ b9s rule add --scope account|project|role:<name>|agent:<name> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
72
+ b9s rule supersede <rule-id> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
73
73
  b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
74
74
  review current charter/agreements before --confirm-compatible; no rule is inferred from chat
75
75
  b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
@@ -131,7 +131,7 @@ Agent commands
131
131
  acquisition queues through a machine maintenance drain/window and resumes after it
132
132
  machine identity is this host's hostname plus its registered label, shared by all agents here
133
133
  save the returned job token; reuse --token to check/retry the same job
134
- b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run the command, then release; exits with its code
134
+ b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run the command, then release; exits with its code and records configured gate completion
135
135
  polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
136
136
  b9s locks shows waiter poll age; reported-command holders do not expire
137
137
  b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
@@ -189,7 +189,7 @@ Machine placement enforces configured session slots and reports machine pressure
189
189
  b9s wu hold <n> --note ".." operator or assigner: no verdict and no merge until the owner resubmits;
190
190
  wu release <n> [--note ..] lifts it earlier
191
191
  b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
192
- b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; no-source closes an evidence-only unit without a merge SHA and checks its branch has no commits beyond the target
192
+ 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
193
193
  b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
194
194
  b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
195
195
  b9s wu show <n> [--scope-only] show the full unit (including route/review explanation when recorded) or only its scope for scripts
@@ -394,6 +394,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
394
394
  b9s-admin role edit <name> [--project p] [--projects a,b|*] [--post c1,c2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]
395
395
  b9s-admin role list [--project p]
396
396
  b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] operator: reassign a unit in place
397
+ b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
398
+ b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
397
399
  b9s-admin wu required-class <project> <n> (--class <p/h/m/e> | --clear) --reason "why" set or clear an operator hard routing-class lock
398
400
  b9s-admin routing show <project> [--mode build|review] [--tag <tag>] inspect confidence matrix, exploration spend, and recent decisions
399
401
  b9s-admin routing policy <project> [--weights q,t,c] [--quality-target <0..100|none>] [--half-life <days>] [--min-samples <n>] [--build-explore <0..20>] [--review-explore <0..20>] [--pause-build yes|no] [--pause-review yes|no] [--reason "why"]
@@ -412,14 +414,14 @@ Use --admin <nickname> to select one of this machine's saved operator identities
412
414
  legacy project-first order also accepted; for operation-first with a project named add, edit, or remove:
413
415
  b9s-admin process tag <op> <tag> --project <project>
414
416
  b9s-admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
415
- b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no] [--gate-command "<one command>"|none]
417
+ b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no] [--gate-command "<one command>"|none] [--require-gate-receipt yes|no]
416
418
  b9s-admin process assigners <project> role1,role2
417
419
  b9s-admin process agreements <project> --file agreements.md
418
420
  b9s-admin process charter <project> --file charter.md how the project weighs trade-offs; sent with every expert question
419
421
  b9s-admin process steward <project> on|off [--quiet m] [--summary m] [--churn n] (--churn: ask the operator when a goal is sent back or handed over n times; 0 off)
420
422
  b9s-admin rule list <project> | show <project> <rule-id>
421
- b9s-admin rule add <project> --scope account|project|role:<name>|agent:<name> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
422
- b9s-admin rule supersede <project> <rule-id> --text "..." [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible | retire <project> <rule-id>
423
+ b9s-admin rule add <project> --scope account|project|role:<name>|agent:<name> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] [--source-channel-id <id> --source-message-id <id>] --confirm-compatible
424
+ b9s-admin rule supersede <project> <rule-id> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible | retire <project> <rule-id>
423
425
  rules are audited revisions; review charter and agreements first. Console promotion is the primary management surface.
424
426
  b9s-admin milestones <project> the plan's slices: list
425
427
  b9s-admin milestones <project> export [--out plan.json] the editable JSON
package/dist/output.js CHANGED
@@ -1,3 +1,15 @@
1
+ /** Human-readable step rules are additive; older servers omit them and remain silent. */
2
+ export function formatStepRules(data, step) {
3
+ if (!data || typeof data !== "object")
4
+ return "";
5
+ const rules = data.step_rules;
6
+ if (!Array.isArray(rules))
7
+ return "";
8
+ return rules.slice(0, 3)
9
+ .filter((rule) => !!rule && typeof rule === "object" && typeof rule.text === "string" && !!rule.text.trim())
10
+ .map((rule) => `Project rule for ${step}: ${rule.text.replace(/[\r\n]+/g, " ").replace(/\s{2,}/g, " ").trim()}`)
11
+ .join("\n");
12
+ }
1
13
  export function printWrittenReceiptMismatch(out, response, detail, actionResult) {
2
14
  const record = response && typeof response === "object" ? response : { response };
3
15
  const unit = record.unit && typeof record.unit === "object" ? record.unit : null;
@@ -4,6 +4,16 @@ export function bindingForObservedTurn(startedAt, saved) {
4
4
  return null;
5
5
  return { work_unit_number: Number(saved.work_unit_number), assignment_event_id: saved.assignment_event_id };
6
6
  }
7
+ /** Emit the daemon's explicit binding (or its non-attribution reason) only for this exact turn start. */
8
+ export function observedTurnBindingFields(startedAt, saved) {
9
+ const binding = bindingForObservedTurn(startedAt, saved);
10
+ const sameTurn = !!startedAt && saved?.started_at === startedAt;
11
+ return {
12
+ work_unit_number: binding?.work_unit_number ?? null,
13
+ assignment_event_id: binding?.assignment_event_id ?? null,
14
+ work_unit_binding_reason: binding ? null : sameTurn ? saved?.reason ?? null : null,
15
+ };
16
+ }
7
17
  /** Accept only server-linked assignment events whose message IDs the final budget retained. */
8
18
  export function deliveredAssignmentBinding(messages, selectedMessageIds) {
9
19
  const selected = new Set(selectedMessageIds);
@@ -14,7 +24,11 @@ export function deliveredAssignmentBinding(messages, selectedMessageIds) {
14
24
  if (!Number.isSafeInteger(message.work_unit_number) || Number(message.work_unit_number) < 1
15
25
  || typeof message.assignment_event_id !== "string" || !message.assignment_event_id)
16
26
  continue;
17
- const binding = { work_unit_number: Number(message.work_unit_number), assignment_event_id: message.assignment_event_id };
27
+ const binding = {
28
+ work_unit_number: Number(message.work_unit_number),
29
+ assignment_event_id: message.assignment_event_id,
30
+ ...(typeof message.project === "string" && message.project ? { project: message.project } : {}),
31
+ };
18
32
  candidates.set(`${binding.work_unit_number}\0${binding.assignment_event_id}`, binding);
19
33
  }
20
34
  return candidates.size === 1 ? [...candidates.values()][0] : null;
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.131";
1
+ export const CLI_VERSION = "0.12.133";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.131",
3
+ "version": "0.12.133",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {