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.
@@ -9,6 +9,7 @@ import { CLI_VERSION } from "./version.js";
9
9
  import { applyEnvAliases } from "./env-aliases.js";
10
10
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
11
11
  import { runCommandSafely } from "./command-runner.js";
12
+ import { validateCommandFlags } from "./command-flags.js";
12
13
  /** b9s-admin: the operator binary. Agents use b9s, whose help never lists these. */
13
14
  async function main(argv) {
14
15
  warnLegacyAlias();
@@ -16,10 +17,13 @@ async function main(argv) {
16
17
  // For an AI agent driving this tool: what it is, and how to load the operator skill. Checked
17
18
  // before parsing because --agent also takes a value elsewhere (notifier --agent <name>).
18
19
  if (argv[0] === "--agent") {
20
+ if (argv.length !== 1)
21
+ throw new CliError("usage", "--agent does not accept additional options or arguments");
19
22
  process.stdout.write(AGENT_ORIENTATION);
20
23
  return 0;
21
24
  }
22
25
  const p = parse(argv);
26
+ validateCommandFlags(p, ADMIN_HELP, argv, new Set(["admin", "as", "help", "json", "version"]));
23
27
  const out = makeOut(bool(p.flags, "json"));
24
28
  if (bool(p.flags, "version")) {
25
29
  process.stdout.write(`${versionLine(CLI_VERSION, true)}\n`);
package/dist/args.js CHANGED
@@ -33,10 +33,10 @@ export const STRING_FLAGS = [
33
33
  "root", "signing-key", "catalog", "context", "context-action", "context-checkpoint-ref", "context-old-thread", "context-new-thread", "source-commit", "component", "normalized-key",
34
34
  "drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
- "machine-session-id", "pool-sessions", "registry", "detail", "worktree",
36
+ "machine-session-id", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime",
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
- "expires-at", "conflicts-with", "source-channel-id", "source-message-id",
39
+ "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
40
  "metadata-file", "confirm-agent", "confirm-parked",
41
41
  ];
42
42
  export const BOOL_FLAGS = [
package/dist/client.js CHANGED
@@ -66,6 +66,8 @@ function expectedTextReceiptFields(method, path, body, response) {
66
66
  return strings("answer");
67
67
  if (verb === "POST" && /^\/account\/watch\/needs\/[^/]+\/action$/.test(route))
68
68
  return fields.action === "answer" ? strings("answer") : [];
69
+ if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route))
70
+ return typeof fields.answer === "string" && fields.answer.trim() ? ["answer"] : [];
69
71
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/submit$/.test(route)) {
70
72
  const required = strings("expect", "lesson");
71
73
  if (Array.isArray(fields.disputes))
@@ -84,9 +86,9 @@ function expectedTextReceiptFields(method, path, body, response) {
84
86
  ? ["required_class.reason"]
85
87
  : [];
86
88
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units$/.test(route))
87
- return [...strings("title", "scope"), ...reqClassReason];
89
+ return [...strings("title", "scope", "plain_summary"), ...reqClassReason];
88
90
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/assign$/.test(route))
89
- return [...strings("title", "scope", "reason"), ...reqClassReason];
91
+ return [...strings("title", "scope", "reason", "plain_summary"), ...reqClassReason];
90
92
  const wu = workUnits.exec(route);
91
93
  if (wu?.[1] && wu[2]) {
92
94
  const action = wu[2];
@@ -104,6 +106,10 @@ function expectedTextReceiptFields(method, path, body, response) {
104
106
  return strings("reason");
105
107
  if (action === "take")
106
108
  return strings("reason");
109
+ if (action === "target")
110
+ return strings("plain_summary");
111
+ if (action === "changes")
112
+ return strings("note", "unmet", "plain_summary");
107
113
  if (action === "compare")
108
114
  return strings("note", "primary_note", "twin_note");
109
115
  if (action === "ask")
@@ -115,7 +121,7 @@ function expectedTextReceiptFields(method, path, body, response) {
115
121
  if (action === "question/explanation")
116
122
  return strings("text");
117
123
  if (action === "scope") {
118
- const required = strings("scope", "append", "note");
124
+ const required = strings("scope", "append", "note", "plain_summary");
119
125
  const replacement = fields.replace;
120
126
  if (replacement && typeof replacement === "object" && !Array.isArray(replacement) && typeof replacement.new === "string")
121
127
  required.push("replace.new");
@@ -152,8 +158,6 @@ function expectedTextReceiptFields(method, path, body, response) {
152
158
  return strings("note");
153
159
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/explanation$/.test(route))
154
160
  return strings("text");
155
- if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route))
156
- return typeof fields.answer === "string" && fields.answer.trim() ? ["answer"] : [];
157
161
  if (verb === "POST" && (/^\/projects\/[^/]+\/lists$/.test(route) || route === "/lists"))
158
162
  return strings("description");
159
163
  if (verb === "PATCH" && /^\/lists\/[^/]+$/.test(route))
@@ -214,7 +218,7 @@ function expectedTextReceiptFields(method, path, body, response) {
214
218
  return strings("note", "reason");
215
219
  return [];
216
220
  }
217
- export function verifyTextReceipts(response, body, requiredFields = [], allowedRedactedFields = [], allowedDiscardedFields = []) {
221
+ export function verifyTextReceipts(response, body, requiredFields = [], allowedRedactedFields = [], allowedDiscardedFields = [], storedText = {}) {
218
222
  const receipts = Array.isArray(response?.receipts)
219
223
  ? response.receipts
220
224
  : response?.receipt ? [response.receipt] : [];
@@ -230,6 +234,7 @@ export function verifyTextReceipts(response, body, requiredFields = [], allowedR
230
234
  expected = expected && typeof expected === "object" ? expected[part] : undefined;
231
235
  if (typeof expected !== "string")
232
236
  throw new CliError("text_receipt_mismatch", `${field}: response included a text receipt but the CLI cannot find the sent text field`);
237
+ const expectedStored = storedText[field] ?? expected;
233
238
  if (typeof receipt.id !== "string" || !receipt.id)
234
239
  throw new CliError("text_receipt_mismatch", `${field}: server receipt is missing its id`);
235
240
  const bytes = new TextEncoder().encode(expected).byteLength;
@@ -255,11 +260,80 @@ export function verifyTextReceipts(response, body, requiredFields = [], allowedR
255
260
  }
256
261
  continue;
257
262
  }
258
- if (receipt.bytes_stored !== bytes)
259
- throw new CliError("text_receipt_mismatch", `${field}: server stored ${receipt.bytes_stored} of ${bytes} sent bytes`);
260
- if (receipt.sha256 !== sha256)
261
- throw new CliError("text_receipt_mismatch", `${field}: stored text SHA-256 does not match the sent text`);
263
+ const storedBytes = new TextEncoder().encode(expectedStored).byteLength;
264
+ if (receipt.bytes_stored !== storedBytes) {
265
+ const detail = storedBytes === bytes
266
+ ? `${field}: server stored ${receipt.bytes_stored} of ${bytes} sent bytes`
267
+ : `${field}: server stored ${receipt.bytes_stored} bytes; expected ${storedBytes} stored bytes`;
268
+ throw new CliError("text_receipt_mismatch", detail);
269
+ }
270
+ const storedHash = createHash("sha256").update(expectedStored, "utf8").digest("hex");
271
+ if (receipt.sha256 !== storedHash) {
272
+ const detail = expectedStored === expected
273
+ ? `${field}: stored text SHA-256 does not match the sent text`
274
+ : `${field}: stored text SHA-256 does not match the expected stored text`;
275
+ throw new CliError("text_receipt_mismatch", detail);
276
+ }
277
+ }
278
+ }
279
+ /** Resolve documented server transformations, validating response text when it is authoritative. */
280
+ function expectedStoredText(method, path, body, response) {
281
+ if (!body)
282
+ return {};
283
+ const fields = body;
284
+ const route = path.split("?", 1)[0];
285
+ const verb = method.toUpperCase();
286
+ const stored = {};
287
+ if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route) && typeof fields.answer === "string" && fields.answer.trim()) {
288
+ const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
289
+ if (!receipts.some((receipt) => receipt?.field === "answer"))
290
+ return stored;
291
+ const note = fields.answer.trim();
292
+ const proposal = response?.ask?.proposal;
293
+ const answer = response?.ask?.answer;
294
+ if (typeof answer !== "string")
295
+ throw new CliError("text_receipt_mismatch", "answer: response omitted the server-stored answer");
296
+ const intended = fields.approve === true
297
+ ? typeof proposal === "string" ? `Approved as proposed: ${proposal}${note ? `\nNote: ${note}` : ""}` : undefined
298
+ : note;
299
+ if (intended === undefined || answer !== intended)
300
+ throw new CliError("text_receipt_mismatch", "answer: server response does not match the submitted answer or approved proposal and note");
301
+ stored.answer = answer;
302
+ }
303
+ if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/scope$/.test(route)) {
304
+ const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
305
+ if (typeof fields.scope === "string") {
306
+ const expectedBaseScope = fields.scope.trim();
307
+ if (receipts.some((receipt) => receipt?.field === "scope")) {
308
+ const baseScope = response?.unit?.base_scope;
309
+ if (typeof baseScope !== "string" || baseScope !== expectedBaseScope) {
310
+ throw new CliError("text_receipt_mismatch", "scope: returned base scope does not match the complete submitted scope");
311
+ }
312
+ stored.scope = baseScope;
313
+ }
314
+ else {
315
+ stored.scope = expectedBaseScope;
316
+ }
317
+ }
318
+ if (typeof fields.append === "string") {
319
+ const appended = fields.append.trim();
320
+ if (receipts.some((receipt) => receipt?.field === "append")) {
321
+ const amendment = response?.scope_amendment;
322
+ if (typeof amendment?.id !== "string" || amendment.text !== appended) {
323
+ throw new CliError("text_receipt_mismatch", "append: response does not confirm the complete newly persisted amendment");
324
+ }
325
+ stored.append = amendment.text;
326
+ }
327
+ else {
328
+ stored.append = appended;
329
+ }
330
+ }
331
+ if (typeof fields.note === "string")
332
+ stored.note = fields.note.trim();
333
+ if (typeof fields.plain_summary === "string")
334
+ stored.plain_summary = fields.plain_summary.trim();
262
335
  }
336
+ return stored;
263
337
  }
264
338
  export class Client {
265
339
  url;
@@ -385,7 +459,7 @@ export class Client {
385
459
  }
386
460
  const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
387
461
  try {
388
- verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : []);
462
+ verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : [], expectedStoredText(method, path, body, json));
389
463
  }
390
464
  catch (error) {
391
465
  if (res.status >= 200 && res.status < 300 && error instanceof CliError && !["GET", "HEAD"].includes(method.toUpperCase())) {
@@ -0,0 +1,125 @@
1
+ import { CliError } from "./errors.js";
2
+ const AGENT_GLOBAL_FLAGS = new Set(["as", "effort", "help", "json", "model", "version"]);
3
+ const ADMIN_GLOBAL_FLAGS = new Set(["admin", "as", "help", "json", "version"]);
4
+ const OPTION_CONTRACT_ALIASES = new Map([["ask", "ask-operator"]]);
5
+ const INHERITED_OPTION_CONTRACTS = new Map([["codex start", ["start"]]]);
6
+ const PROJECT_COMMANDS = new Set([
7
+ "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
8
+ "wu", "process", "record", "milestones", "milestone", "lock", "unlock", "locks", "ask", "ask-operator",
9
+ "explain", "worktrees", "measures", "measure", "environment", "test-results",
10
+ ]);
11
+ function supportsProject(command) {
12
+ return PROJECT_COMMANDS.has(command[0] ?? "") || (command[0] === "status" && command[1] === "history");
13
+ }
14
+ function commandUsageLines(help) {
15
+ const lines = help.split("\n");
16
+ const result = [];
17
+ for (let i = 0; i < lines.length; i++) {
18
+ if (!/^\s*b9s(?:-admin)?\s/.test(lines[i]))
19
+ continue;
20
+ // The synopsis ends at its aligned description column. Never treat flags mentioned only in
21
+ // prose as accepted options; the handler's accepted options belong in the synopsis.
22
+ result.push(lines[i].trim().split(/\s{2,}/, 1)[0]);
23
+ }
24
+ return result;
25
+ }
26
+ function commandAlternatives(line) {
27
+ const text = line.trim().replace(/^b9s(?:-admin)?\s+/, "");
28
+ const words = text.split(/\s+/);
29
+ const paths = [[]];
30
+ for (const word of words) {
31
+ if (word.startsWith("-") || word === "|" || word.startsWith("("))
32
+ break;
33
+ // Position placeholders can precede a subcommand (for example, `project secrets <p> list`).
34
+ // Skip them while continuing to collect the literal command path. Optional option groups end
35
+ // the command path; optional positional arguments do not.
36
+ if (word.startsWith("<") || word.startsWith("\"")) {
37
+ for (const path of paths)
38
+ path.push("*");
39
+ continue;
40
+ }
41
+ if (word.startsWith("[") && !word.includes("--")) {
42
+ for (const path of paths)
43
+ path.push("*?");
44
+ continue;
45
+ }
46
+ if (word.startsWith("["))
47
+ break;
48
+ const alternatives = word.split("|").filter((part) => /^[a-z][a-z0-9-]*$/.test(part));
49
+ if (!alternatives.length)
50
+ break;
51
+ const next = paths.flatMap((path) => alternatives.map((part) => [...path, part]));
52
+ paths.splice(0, paths.length, ...next);
53
+ }
54
+ return paths.filter((path) => path.length > 0);
55
+ }
56
+ function pathMatches(path, command) {
57
+ let index = 0;
58
+ for (const part of path) {
59
+ if (part === "*?") {
60
+ if (index < command.length)
61
+ index++;
62
+ continue;
63
+ }
64
+ if (part === "*") {
65
+ if (index >= command.length)
66
+ return false;
67
+ index++;
68
+ continue;
69
+ }
70
+ if (command[index] !== part)
71
+ return false;
72
+ index++;
73
+ }
74
+ return true;
75
+ }
76
+ function optionNames(text) {
77
+ return new Set([...text.matchAll(/--([a-z][a-z0-9-]*)/g)].map((match) => match[1]));
78
+ }
79
+ export function validateCommandFlags(parsed, help, argv, globalFlags = AGENT_GLOBAL_FLAGS) {
80
+ const command = parsed.positionals;
81
+ if (!command.length)
82
+ return;
83
+ const aliasTarget = OPTION_CONTRACT_ALIASES.get(command[0]);
84
+ const contractCommand = [aliasTarget ?? command[0], ...command.slice(1)];
85
+ const matching = commandUsageLines(help).flatMap((usage) => commandAlternatives(usage)
86
+ .filter((path) => pathMatches(path, contractCommand))
87
+ .map((path) => ({ path, usage })));
88
+ const specificity = Math.max(0, ...matching.map(({ path }) => path.length));
89
+ const applicable = matching.filter(({ path }) => path.length === specificity);
90
+ const allowed = new Set(globalFlags);
91
+ for (const { usage } of applicable)
92
+ for (const flag of optionNames(usage))
93
+ allowed.add(flag);
94
+ for (const inheritedPath of INHERITED_OPTION_CONTRACTS.get(command.slice(0, 2).join(" ")) ?? []) {
95
+ const inherited = commandUsageLines(help).flatMap((usage) => commandAlternatives(usage)
96
+ .filter((path) => pathMatches(path, [inheritedPath]))
97
+ .map((path) => ({ path, usage })));
98
+ const inheritedSpecificity = Math.max(0, ...inherited.map(({ path }) => path.length));
99
+ for (const { path, usage } of inherited.filter(({ path }) => path.length === inheritedSpecificity)) {
100
+ // A parent such as `start` may have aliases in its synopsis. Only inherit the exact parent
101
+ // command's contract, not a sibling alternative.
102
+ if (path.join(" ") === inheritedPath)
103
+ for (const flag of optionNames(usage))
104
+ allowed.add(flag);
105
+ }
106
+ }
107
+ // Account-scoped agents select a project for these project-context commands. This is a
108
+ // documented command-wide selector (or BSCHAT_PROJECT), even when a short help synopsis omits it.
109
+ if (supportsProject(command))
110
+ allowed.add("project");
111
+ // Parsing has established that these options are syntactically valid. This pass narrows the
112
+ // global option catalog to the selected command before its handler can make a server call.
113
+ const separator = argv.indexOf("--");
114
+ const ownArgv = separator < 0 ? argv : argv.slice(0, separator);
115
+ for (const arg of ownArgv) {
116
+ if (!arg.startsWith("--"))
117
+ continue;
118
+ const name = arg.slice(2).split("=", 1)[0];
119
+ const normalized = name.startsWith("no-") && !allowed.has(name) ? name.slice(3) : name;
120
+ if (!allowed.has(name) && !allowed.has(normalized)) {
121
+ const commandLabel = aliasTarget ? command[0] : command.slice(0, specificity || 1).join(" ");
122
+ throw new CliError("usage", `unknown option --${name} for ${commandLabel}`, "Use the command's documented options or run --help.");
123
+ }
124
+ }
125
+ }
@@ -128,6 +128,8 @@ export async function admin(p, out) {
128
128
  return notifierAdmin(p, out);
129
129
  case "account":
130
130
  return accountAdmin(p, out);
131
+ case "account-stores":
132
+ return accountStoresAdmin(action, rest, p, out);
131
133
  case "turn-judgment":
132
134
  case "turn-judgments":
133
135
  return turnJudgeAdmin(action, rest, p, out);
@@ -159,6 +161,56 @@ export async function admin(p, out) {
159
161
  throw new CliError("usage", `unknown admin command ${group ?? ""}`, "Run: b9s --help");
160
162
  }
161
163
  }
164
+ async function accountStoresAdmin(action, rest, p, out) {
165
+ if (!action || !["migrations"].includes(action) || rest.length > 1 || (rest.length && !["show", "run"].includes(rest[0]))) {
166
+ throw new CliError("usage", "b9s-admin account-stores migrations show|run [--json]");
167
+ }
168
+ const operation = rest[0] ?? "show";
169
+ const client = adminClient(p);
170
+ const pages = [];
171
+ let after = null;
172
+ do {
173
+ const path = after ? `/admin/tenant-migrations?after=${encodeURIComponent(after)}` : "/admin/tenant-migrations";
174
+ const result = operation === "run"
175
+ ? await client.call("POST", `${path.replace("/admin/tenant-migrations", "/admin/tenant-migrations/run")}`)
176
+ : await client.call("GET", path);
177
+ pages.push(result);
178
+ after = result.next_cursor ?? null;
179
+ } while (after);
180
+ if (operation === "show") {
181
+ const accounts = pages.flatMap((page) => page.accounts ?? []);
182
+ const summary = accounts.map((account) => ({
183
+ account: account.account_name,
184
+ schema_version: account.schema_version ?? "not initialized",
185
+ applied: account.applied.length,
186
+ pending: account.pending.length,
187
+ failed: account.failed.length,
188
+ }));
189
+ out.print(summary.length ? table(summary, ["account", "schema_version", "applied", "pending", "failed"]) : "No account stores found.", { accounts });
190
+ return;
191
+ }
192
+ const failures = pages.flatMap((page) => page.failed ?? []);
193
+ const reportPages = [];
194
+ after = null;
195
+ do {
196
+ const path = after ? `/admin/tenant-migrations?after=${encodeURIComponent(after)}` : "/admin/tenant-migrations";
197
+ const result = await client.call("GET", path);
198
+ reportPages.push(result);
199
+ after = result.next_cursor ?? null;
200
+ } while (after);
201
+ const accounts = reportPages.flatMap((page) => page.accounts ?? []);
202
+ const summary = accounts.map((account) => ({
203
+ account: account.account_name,
204
+ schema_version: account.schema_version ?? "not initialized",
205
+ applied: account.applied.length,
206
+ pending: account.pending.length,
207
+ failed: account.failed.length,
208
+ }));
209
+ const failureDetails = failures.map((failure) => `${failure.account_name} (${failure.account_id}) ${failure.migration_name}: ${failure.reason}`);
210
+ out.print(failures.length
211
+ ? `Account-store migrations finished with ${failures.length} failure(s); rerun after fixing the reported migration.\n${failureDetails.join("\n")}\n\n${table(summary, ["account", "schema_version", "applied", "pending", "failed"])}\n`
212
+ : `Account-store migrations are current for ${accounts.length} account store(s).\n${table(summary, ["account", "schema_version", "applied", "pending", "failed"])}\n`, { accounts, applied: pages.flatMap((page) => page.applied ?? []), pending: pages.flatMap((page) => page.pending ?? []), failed: failures });
213
+ }
162
214
  async function githubAdmin(action, rest, p, out) {
163
215
  const c = adminClient(p);
164
216
  if (action === "status" && !rest.length) {
@@ -20,13 +20,31 @@ function agentClient(p) {
20
20
  * BSCHAT_PROJECT, and an error naming the options otherwise.
21
21
  */
22
22
  export function projectOf(p, creds) {
23
- if (creds.project)
24
- return creds.project;
25
23
  const v = str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
24
+ if (creds.project) {
25
+ if (v && v !== creds.project) {
26
+ const selector = str(p.flags, "project") ? "--project" : "BSCHAT_PROJECT";
27
+ throw new CliError("project_forbidden", `project-scoped agent ${creds.project}/${creds.agent} cannot use ${selector} ${v}`);
28
+ }
29
+ return creds.project;
30
+ }
26
31
  if (!v)
27
32
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; this command needs --project <name> (or BSCHAT_PROJECT)`, "See your accessible projects with: b9s me");
28
33
  return v;
29
34
  }
35
+ /** Check explicit account-agent project selection before a command mutates anything. */
36
+ export async function assertProjectUsable(creds, project) {
37
+ if (creds.project) {
38
+ if (creds.project !== project) {
39
+ throw new CliError("project_forbidden", `project-scoped agent ${creds.project}/${creds.agent} cannot use --project ${project}`);
40
+ }
41
+ return;
42
+ }
43
+ const me = await Client.forAgent(creds, undefined, { presence: false }).call("GET", "/me");
44
+ const allowed = me.scope === "account" && Array.isArray(me.projects) && me.projects.some((entry) => entry.name === project);
45
+ if (!allowed)
46
+ throw new CliError("project_forbidden", `account-scoped agent ${creds.agent} cannot use --project ${project}`);
47
+ }
30
48
  export async function login(p, out) {
31
49
  const asFlag = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
32
50
  if (!asFlag)
@@ -313,6 +313,9 @@ export async function harnessStart(p, out, harness) {
313
313
  if (adopt)
314
314
  updateState(ref, (onDisk) => ({ ...onDisk, turn_unpaused_at: Date.now() }));
315
315
  // 4. The watcher, in turn mode: it runs each later turn itself.
316
+ const claudeTurnSettings = harness === "claude-code" && sandbox === "workspace-write"
317
+ ? "__B9S_CLAUDE_TURN_SETTINGS__"
318
+ : settings.map(shq).join(" ");
316
319
  const exec = harness === "codex"
317
320
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
318
321
  : harness === "dsh"
@@ -320,7 +323,7 @@ export async function harnessStart(p, out, harness) {
320
323
  : harness === "antigravity"
321
324
  ? antigravityResumeCommand(bin, session, model, effort, turnTimeout * 60, settings, antigravityLog(ref))
322
325
  // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
323
- : `${shq(bin)} -p {text} ${[...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
326
+ : `${shq(bin)} -p {text} ${[claudeTurnSettings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []).map(shq), "--resume", session, "--output-format", "json"].join(" ")} > ${shq(claudeResultFile(ref))}`;
324
327
  const watcherOut = [];
325
328
  // Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
326
329
  // work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
@@ -331,7 +334,9 @@ export async function harnessStart(p, out, harness) {
331
334
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
332
335
  const prune = bool(p.flags, "prune");
333
336
  watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
334
- const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model, ...(machineSessionId ? { machineSessionId } : {}) };
337
+ const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
338
+ ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd } } : {}),
339
+ ...(machineSessionId ? { machineSessionId } : {}) };
335
340
  if (inContainer) {
336
341
  const sess = sessionOfExec(exec);
337
342
  if (sess)
@@ -49,6 +49,7 @@ export function budgetDelivery(input) {
49
49
  ...(followed ? [followed] : []), ...(digest ? [digest] : []), ...footer, ...(input.suffix ?? []),
50
50
  ].filter(Boolean).join("\n");
51
51
  let direct = input.direct;
52
+ let directIds = [...(input.direct_ids ?? [])];
52
53
  let items = input.items;
53
54
  let followed = input.followed.length ? ["Followed channels:", ...input.followed].join("\n") : "";
54
55
  let digest = input.digest.length ? `Unread elsewhere: ${input.digest.join("; ")}` : "";
@@ -68,6 +69,7 @@ export function budgetDelivery(input) {
68
69
  if (utf8Bytes(text) > budget && direct.length) {
69
70
  deferredDirect = `${direct.length} addressed message${direct.length === 1 ? "" : "s"} deferred; read with ${input.directPointer ?? "b9s inbox --unread"}.`;
70
71
  direct = [];
72
+ directIds = [];
71
73
  text = compose(direct, items, followed, digest, deferredDirect);
72
74
  }
73
75
  // A large rules prefix leaves only a small allowance for the envelope. Apply the remaining
@@ -105,7 +107,7 @@ export function budgetDelivery(input) {
105
107
  followed: utf8Bytes(followed),
106
108
  digest: utf8Bytes(digest),
107
109
  };
108
- return { text, bytes: utf8Bytes(text), by_kind };
110
+ return { text, bytes: utf8Bytes(text), by_kind, selected_direct_ids: directIds };
109
111
  }
110
112
  /** Re-render an update with its complete wrapper/rules included in the same byte budget. */
111
113
  export function formatUpdates(u, prefix = [], suffix = []) {
@@ -114,7 +116,7 @@ export function formatUpdates(u, prefix = [], suffix = []) {
114
116
  ? [...suffix.filter((line) => !/^\s+b9s read\b.*--since\b/.test(line)), ` ${commandLines.length} channel reads deferred; run b9s read --pending`]
115
117
  : suffix;
116
118
  const result = budgetDelivery({ ...u.parts, prefix, suffix: compactSuffix });
117
- return { ...u, text: result.text, delivery: { bytes: result.bytes, by_kind: result.by_kind } };
119
+ return { ...u, text: result.text, delivery: { bytes: result.bytes, by_kind: result.by_kind, selected_direct_ids: result.selected_direct_ids } };
118
120
  }
119
121
  /** Budget standalone rules too, and defer their acknowledgement until the selected text is emitted. */
120
122
  export function formatHookDelivery(u, standing) {
@@ -357,7 +359,7 @@ export async function gatherUpdates(name, opts) {
357
359
  const directPointer = firstDeferred ? inboxPointer : "b9s inbox --unread";
358
360
  const itemPointer = firstItemDeferred ? inboxPointer : "b9s inbox --unread";
359
361
  const followedPointer = pendingReads.size ? "b9s read --pending" : readCommands.join("; ") || "b9s read --pending";
360
- const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
362
+ const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, direct_ids: messages.flatMap((message) => message.role_name === "human" ? [] : [String(message.id)]), directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
361
363
  const delivery = budgetDelivery(parts);
362
364
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
363
365
  const visibleReadCommands = readCommands.slice(0, 8);
@@ -368,6 +370,13 @@ export async function gatherUpdates(name, opts) {
368
370
  const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || message.mentions?.includes(creds.agent) || new RegExp(`(^|[^\\w@])@${escapedAgent}(?![\\w-])`).test(message.body);
369
371
  const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some(isDirectMessage);
370
372
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
373
+ const turnBindingCandidates = tier === "direct" ? messages.map((message, index) => ({
374
+ id: String(message.id),
375
+ direct: isDirectMessage(message),
376
+ rendered: lines[index],
377
+ work_unit_number: message.work_unit_number,
378
+ assignment_event_id: message.assignment_event_id,
379
+ })) : [];
371
380
  const directTimes = [
372
381
  ...messages.filter(isDirectMessage).map((message) => message.created_at),
373
382
  ...questions.map((question) => question.asked_at),
@@ -376,7 +385,7 @@ export async function gatherUpdates(name, opts) {
376
385
  const firstDirectAt = directTimes.sort()[0] ?? null;
377
386
  const urgent = messages.some((message) => message.urgent === true || message.priority === "urgent")
378
387
  || items.some((item) => item.urgent === true || item.priority === "urgent");
379
- return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
388
+ return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, turn_binding_candidates: turnBindingCandidates, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
380
389
  }
381
390
  /** Command patterns warn without blocking; errors remain visible to the caller. */
382
391
  export async function commandWarnings(name, command) {
@@ -25,6 +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
29
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
29
30
  import { imageCacheBaseDir, imageCacheProjectRoot, projectsWithImageCaches } from "../image-caches.js";
30
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";
@@ -114,8 +115,12 @@ const lastCapabilityProbe = new Map();
114
115
  const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
115
116
  const lastWorktreePrune = new Map();
116
117
  export function resetWorktreePrune() { lastWorktreePrune.clear(); }
117
- export function turnFaultSessionFields(fault) {
118
- return { turn_fault_at: new Date(fault.at).toISOString() };
118
+ export function turnFaultSessionFields(fault, agent) {
119
+ const binding = agent ? readState(agent).watch_turn_binding : undefined;
120
+ return {
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 } : {}),
123
+ };
119
124
  }
120
125
  const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
121
126
  export function bareDigestOf(imageRef) {
@@ -1359,7 +1364,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1359
1364
  removeAgentContainer(containerPrereqs.runtime, containerName, runner);
1360
1365
  log(`${s.agent}: turn mode fault; container ${containerName} removed`);
1361
1366
  }
1362
- out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error, ...turnFaultSessionFields(fault) });
1367
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error, ...turnFaultSessionFields(fault, s.agent) });
1363
1368
  continue;
1364
1369
  }
1365
1370
  if (local) {
@@ -2067,13 +2072,22 @@ export function stoppedSessionFacts(dir, thread, gitStatus = (path) => {
2067
2072
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
2068
2073
  function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
2069
2074
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
2075
+ const savedBinding = readState(agent).watch_turn_binding;
2070
2076
  const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
2071
2077
  if (!thread || !ph || "missing" in ph)
2072
- return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
2078
+ return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null, work_unit_number: null, assignment_event_id: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
2073
2079
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
2074
2080
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
2075
2081
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
2076
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, 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 } : {}) };
2082
+ const binding = bindingForObservedTurn(ph.startedAt, savedBinding);
2083
+ return { turn: {
2084
+ running: ph.running,
2085
+ since: ph.startedAt,
2086
+ work_unit_number: binding?.work_unit_number ?? null,
2087
+ assignment_event_id: binding?.assignment_event_id ?? null,
2088
+ ...(!ph.running && !ph.lastError && ph.startedAt ? { completed_at: ph.lastEventAt } : {}),
2089
+ ...(!ph.running && ph.lastError && ph.lastErrorAt ? { turn_fault_at: ph.lastErrorAt, error: ph.lastError } : {}),
2090
+ }, 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 } : {}) };
2077
2091
  }
2078
2092
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
2079
2093
  export function turnProcess(thread, harness = "codex", psOutput, agent) {
@@ -6,7 +6,7 @@ import { Client } from "../client.js";
6
6
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
7
7
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
8
8
  import { parseTestRunReport, summarizeTestRun } from "../test-results.js";
9
- import { projectOf } from "./agent.js";
9
+ import { assertProjectUsable, projectOf } from "./agent.js";
10
10
  function readFile(path, label) {
11
11
  try {
12
12
  const bytes = readFileSync(path);
@@ -69,6 +69,7 @@ export async function testResults(p, out) {
69
69
  const creds = loadAgent(agent);
70
70
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), agent));
71
71
  const project = projectOf(p, creds);
72
+ await assertProjectUsable(creds, project);
72
73
  if (sub === "show") {
73
74
  const runId = p.positionals[2];
74
75
  if (!runId)