benignswarm 0.12.82 → 0.12.84

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.
@@ -23,6 +23,21 @@ export async function evidence(p, out) {
23
23
  const creds = loadAgent(name);
24
24
  const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
25
25
  const project = projectOf(p, creds);
26
+ if (sub === "verify") {
27
+ const id = p.positionals[2];
28
+ if (!id)
29
+ throw new CliError("usage", 'evidence verify <id> --confirmed|--refuted --note "..."');
30
+ const confirmed = p.flags.confirmed === true;
31
+ const refuted = p.flags.refuted === true;
32
+ if (confirmed === refuted)
33
+ throw new CliError("usage", "choose exactly one of --confirmed or --refuted");
34
+ const note = str(p.flags, "note")?.trim();
35
+ if (!note)
36
+ throw new CliError("usage", "evidence verify requires --note");
37
+ const result = await client.call("POST", `/projects/${project}/evidence/${encodeURIComponent(id)}/verify`, { status: confirmed ? "confirmed" : "refuted", note });
38
+ out.print(`${result.verification.status} claim on evidence ${id} (by ${result.verification.verifier_name}): ${result.verification.note}`, result);
39
+ return;
40
+ }
26
41
  if (sub === "post") {
27
42
  const file = p.positionals[2];
28
43
  if (!file)
@@ -100,5 +115,5 @@ export async function evidence(p, out) {
100
115
  }
101
116
  return;
102
117
  }
103
- throw new CliError("usage", "evidence <post|list|info|get>");
118
+ throw new CliError("usage", "evidence <post|list|info|get|verify>");
104
119
  }
@@ -9,10 +9,10 @@ import { readState, writeState } from "../state.js";
9
9
  * shows it (Codex app threads keep it in the cloud; DeepSeek exposes it through get_goal). Claude
10
10
  * Code needs none of this: the hook reads the goal from the transcript.
11
11
  *
12
- * bschat goal set "<the /goal text>" [--state pursuing|paused|stalled|achieved|abandoned]
13
- * bschat goal achieved | paused | stalled | abandoned (same text, new state)
14
- * bschat goal clear
15
- * bschat goal (what the server has for you)
12
+ * b9s goal set "<the /goal text>" [--state pursuing|paused|stalled|achieved|abandoned]
13
+ * b9s goal achieved | paused | stalled | abandoned (same text, new state)
14
+ * b9s goal clear
15
+ * b9s goal (what the server has for you)
16
16
  */
17
17
  export async function goal(p, out) {
18
18
  const sub = p.positionals[1];
@@ -43,7 +43,7 @@ export async function goal(p, out) {
43
43
  else if (HARNESS_GOAL_STATES.includes(sub)) {
44
44
  const last = readState(ref).harness_goal;
45
45
  if (!last)
46
- throw new CliError("no_goal", `no goal recorded on this machine to mark ${sub}`, 'Report it first: bschat goal set "<text>"');
46
+ throw new CliError("no_goal", `no goal recorded on this machine to mark ${sub}`, 'Report it first: b9s goal set "<text>"');
47
47
  next = { text: last.text, state: sub };
48
48
  }
49
49
  else {
@@ -7,7 +7,8 @@ import { fmtMessage } from "../output.js";
7
7
  import { readState, writeState } from "../state.js";
8
8
  import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
9
9
  import { conversationAgent, sessionAgent, syncFromWatchers } from "../sessions.js";
10
- import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText } from "../brief.js";
10
+ import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
11
+ import { changedNotices, commandNoticeWarning, normalizeShellCommand } from "../notices.js";
11
12
  const HEARTBEAT_MS = 60_000;
12
13
  /** Reads the harness's hook payload from stdin without blocking when there is none. */
13
14
  function readStdinJson() {
@@ -22,6 +23,14 @@ function readStdinJson() {
22
23
  }
23
24
  }
24
25
  const THROTTLE_MS = 20_000;
26
+ function omitMeasuresAlreadyIn(text, updates) {
27
+ if (!text || !updates)
28
+ return updates;
29
+ const included = new Set(text.split("\n").filter((line) => line.startsWith("Outcome measure ")));
30
+ if (!included.size)
31
+ return updates;
32
+ return { ...updates, parts: { ...updates.parts, protectedDirect: updates.parts.protectedDirect?.filter((line) => !included.has(line)) } };
33
+ }
25
34
  const utf8Bytes = (text) => new TextEncoder().encode(text).byteLength;
26
35
  const DELIVERY_BUDGET_BYTES = 4000;
27
36
  /** Preserve operator messages, then shorten lower-priority content to counted pointers until the complete payload fits. */
@@ -30,7 +39,7 @@ export function budgetDelivery(input) {
30
39
  const budget = input.budget ?? DELIVERY_BUDGET_BYTES;
31
40
  let header = input.header;
32
41
  let footer = [...input.footer];
33
- let itemLabel = "Assigned list items (details: bschat item show <id>):";
42
+ let itemLabel = "Assigned list items (details: b9s item show <id>):";
34
43
  const compose = (direct, items, followed, digest, deferredDirect) => [
35
44
  ...(input.prefix ?? []), header, ...protectedDirect, ...direct,
36
45
  ...(deferredDirect ? [deferredDirect] : []),
@@ -45,17 +54,17 @@ export function budgetDelivery(input) {
45
54
  let text = compose(direct, items, followed, digest, deferredDirect);
46
55
  if (utf8Bytes(text) > budget) {
47
56
  followed = input.followed.length ? `${input.followed.length} followed-channel messages deferred; read with ${input.readCommand}.` : "";
48
- digest = input.digest.length ? `${input.digest.length} unread channel summaries deferred; use bschat inbox --unread, then bschat read <channel> --since <seq>.` : "";
57
+ digest = input.digest.length ? `${input.digest.length} unread channel summaries deferred; use b9s inbox --unread, then b9s read <channel> --since <seq>.` : "";
49
58
  text = compose(direct, items, followed, digest, deferredDirect);
50
59
  }
51
60
  let itemBytes = items.join("\n");
52
61
  if (utf8Bytes(text) > budget && items.length) {
53
- itemBytes = `${items.length} assigned list item${items.length === 1 ? "" : "s"} deferred; use ${input.itemPointer ?? "bschat inbox --unread, then bschat item show <id>"}.`;
62
+ itemBytes = `${items.length} assigned list item${items.length === 1 ? "" : "s"} deferred; use ${input.itemPointer ?? "b9s inbox --unread, then b9s item show <id>"}.`;
54
63
  items = [itemBytes];
55
64
  text = compose(direct, items, followed, digest, deferredDirect);
56
65
  }
57
66
  if (utf8Bytes(text) > budget && direct.length) {
58
- deferredDirect = `${direct.length} addressed message${direct.length === 1 ? "" : "s"} deferred; read with ${input.directPointer ?? "bschat inbox --unread"}.`;
67
+ deferredDirect = `${direct.length} addressed message${direct.length === 1 ? "" : "s"} deferred; read with ${input.directPointer ?? "b9s inbox --unread"}.`;
59
68
  direct = [];
60
69
  text = compose(direct, items, followed, digest, deferredDirect);
61
70
  }
@@ -67,15 +76,15 @@ export function budgetDelivery(input) {
67
76
  header = "";
68
77
  itemLabel = "";
69
78
  if (items.length && input.items.length) {
70
- itemBytes = `${input.items.length} items; ${input.itemPointer ?? "bschat inbox --unread"}`;
79
+ itemBytes = `${input.items.length} items; ${input.itemPointer ?? "b9s inbox --unread"}`;
71
80
  items = [itemBytes];
72
81
  }
73
82
  if (followed)
74
83
  followed = `${input.followed.length} followed messages; ${input.followedPointer ?? input.readCommand}`;
75
84
  if (digest)
76
- digest = `${input.digest.length} unread channels; ${input.digestPointer ?? "bschat inbox --unread"}`;
85
+ digest = `${input.digest.length} unread channels; ${input.digestPointer ?? "b9s inbox --unread"}`;
77
86
  if (deferredDirect)
78
- deferredDirect = `${input.direct.length} messages; ${input.directPointer ?? "bschat inbox --unread"}`;
87
+ deferredDirect = `${input.direct.length} messages; ${input.directPointer ?? "b9s inbox --unread"}`;
79
88
  text = compose(direct, items, followed, digest, deferredDirect);
80
89
  }
81
90
  if (utf8Bytes(text) > budget && followed && digest && input.followedPointer === input.digestPointer) {
@@ -98,9 +107,9 @@ export function budgetDelivery(input) {
98
107
  }
99
108
  /** Re-render an update with its complete wrapper/rules included in the same byte budget. */
100
109
  export function formatUpdates(u, prefix = [], suffix = []) {
101
- const commandLines = suffix.filter((line) => /^\s+bschat read\b.*--since\b/.test(line));
110
+ const commandLines = suffix.filter((line) => /^\s+b9s read\b.*--since\b/.test(line));
102
111
  const compactSuffix = commandLines.length > 8
103
- ? [...suffix.filter((line) => !/^\s+bschat read\b.*--since\b/.test(line)), ` ${commandLines.length} channel reads deferred; run bschat read --pending`]
112
+ ? [...suffix.filter((line) => !/^\s+b9s read\b.*--since\b/.test(line)), ` ${commandLines.length} channel reads deferred; run b9s read --pending`]
104
113
  : suffix;
105
114
  const result = budgetDelivery({ ...u.parts, prefix, suffix: compactSuffix });
106
115
  return { ...u, text: result.text, delivery: { bytes: result.bytes, by_kind: result.by_kind } };
@@ -119,7 +128,7 @@ export function formatHookDelivery(u, standing) {
119
128
  by_kind = formatted.delivery.by_kind;
120
129
  }
121
130
  else {
122
- const render = (ruleText) => budgetDelivery({ header: "", direct: [], items: [], followed: [], digest: [], footer: [], readCommand: "bschat process", prefix: standing ? [ruleText] : [], budget });
131
+ const render = (ruleText) => budgetDelivery({ header: "", direct: [], items: [], followed: [], digest: [], footer: [], readCommand: "b9s process", prefix: standing ? [ruleText] : [], budget });
123
132
  let rendered = render(standing?.text ?? "");
124
133
  if (rendered.bytes > budget && standing && standing.text !== standing.deferredText)
125
134
  rendered = render(standing.deferredText);
@@ -131,7 +140,7 @@ export function formatHookDelivery(u, standing) {
131
140
  }
132
141
  /**
133
142
  * Collects everything new for an identity and advances its cursors. Returns null when nothing
134
- * is new. Shared by the harness hook and `bschat watch`. Never throws for server/network
143
+ * is new. Shared by the harness hook and `b9s watch`. Never throws for server/network
135
144
  * problems: those go to stderr and yield null, so callers keep running.
136
145
  */
137
146
  export async function gatherUpdates(name, opts) {
@@ -140,7 +149,7 @@ export async function gatherUpdates(name, opts) {
140
149
  creds = loadAgent(name);
141
150
  }
142
151
  catch (e) {
143
- process.stderr.write(`bschat: ${e.message}\n`);
152
+ process.stderr.write(`b9s: ${e.message}\n`);
144
153
  return null;
145
154
  }
146
155
  const state = readState(name);
@@ -159,12 +168,44 @@ export async function gatherUpdates(name, opts) {
159
168
  items = r.items ?? [];
160
169
  }
161
170
  catch (e) {
162
- process.stderr.write(`bschat: ${e.message}\n`);
171
+ process.stderr.write(`b9s: ${e.message}\n`);
163
172
  return null;
164
173
  }
174
+ let notices = null;
175
+ try {
176
+ const response = await client.call("GET", "/agents/me/notices");
177
+ if (!Array.isArray(response.notices))
178
+ throw new Error("GET /agents/me/notices returned no notices array");
179
+ notices = response.notices;
180
+ }
181
+ catch (e) {
182
+ process.stderr.write(`b9s: notices: ${e.message}\n`);
183
+ }
184
+ const noticeChanges = notices ? changedNotices(notices, state.notice_state ?? {}) : null;
185
+ const noticeNext = noticeChanges?.next ?? state.notice_state ?? {};
186
+ const noticeLines = noticeChanges ? [
187
+ ...noticeChanges.changed.map((n) => ` [${n.scope} ${n.scope_name}] ${n.text}`),
188
+ ...noticeChanges.removed.map((n) => ` no longer active: ${n.text}`),
189
+ ] : [];
190
+ let measureLines = [];
191
+ let nextMeasureState = null;
192
+ try {
193
+ const response = await client.call("GET", "/agents/me/brief");
194
+ const brief = response.brief;
195
+ if (brief && Array.isArray(brief.measures)) {
196
+ nextMeasureState = outcomeMeasureSnapshot(brief.measures, brief.measures_omitted ?? 0);
197
+ if (nextMeasureState !== state.measure_state)
198
+ measureLines = formatOutcomeMeasures(brief.measures, brief.measures_omitted ?? 0);
199
+ }
200
+ }
201
+ catch (e) {
202
+ process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
203
+ }
165
204
  const next = { ...state, last_check: Date.now() };
166
205
  if (messages.length)
167
206
  next.inbox_after = messages[messages.length - 1].created_at;
207
+ if (nextMeasureState !== null)
208
+ next.measure_state = nextMeasureState;
168
209
  const channelRead = { ...(state.channel_read ?? {}) };
169
210
  const follows = new Set(state.follows ?? []);
170
211
  const digest = [];
@@ -193,7 +234,7 @@ export async function gatherUpdates(name, opts) {
193
234
  // line: a worker that reads every busy channel on every wake-up fills its context with chat
194
235
  // that was never for it.
195
236
  if (follows.has(key)) {
196
- readCommands.push(`bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`);
237
+ readCommands.push(`b9s read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`);
197
238
  pendingReads.set(key, { project, channel: ch.name, since: last });
198
239
  const r = await client.call("GET", `/projects/${project}/channels/${ch.name}/messages?since=${last}&limit=5`);
199
240
  const seen = new Set(messages.map((m) => m.id));
@@ -202,11 +243,11 @@ export async function gatherUpdates(name, opts) {
202
243
  followed.push(`${creds.project ? "" : `[${project}] `}${fmtMessage(m)}`);
203
244
  const shown = r.messages.length ? r.messages[r.messages.length - 1].seq : last;
204
245
  if (ch.cursor > shown)
205
- followed.push(` (+${ch.cursor - shown} more in #${ch.name}: bschat read ${ch.name} --since ${shown})`);
246
+ followed.push(` (+${ch.cursor - shown} more in #${ch.name}: b9s read ${ch.name} --since ${shown})`);
206
247
  channelRead[key] = shown;
207
248
  }
208
249
  else {
209
- const readCommand = `bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`;
250
+ const readCommand = `b9s read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`;
210
251
  digestCommands.push(readCommand);
211
252
  digestReads.set(key, { project, channel: ch.name, since: last });
212
253
  digest.push(`#${ch.name}${creds.project ? "" : ` [${project}]`}: ${unread} unread (${readCommand})`);
@@ -215,7 +256,7 @@ export async function gatherUpdates(name, opts) {
215
256
  }
216
257
  }
217
258
  catch (e) {
218
- process.stderr.write(`bschat: channels: ${e.message}\n`);
259
+ process.stderr.write(`b9s: channels: ${e.message}\n`);
219
260
  }
220
261
  next.channel_read = channelRead;
221
262
  const deferredReads = readCommands.length > 8 ? [...pendingReads.values()].slice(8) : [];
@@ -238,31 +279,34 @@ export async function gatherUpdates(name, opts) {
238
279
  writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}) });
239
280
  }
240
281
  else {
241
- writeState(name, next);
282
+ writeState(name, { ...next, ...(noticeChanges ? { notice_state: noticeChanges.next } : {}) });
242
283
  }
243
- if (!messages.length && !items.length && !digest.length && !followed.length)
284
+ if (!messages.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
244
285
  return null;
245
286
  const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
246
287
  const protectedDirect = messages.flatMap((m, i) => m.role_name === "human" ? [lines[i]] : []);
247
288
  const directLines = messages.flatMap((m, i) => m.role_name === "human" ? [] : [lines[i]]);
248
289
  const itemLines = items.map((i) => ` list "${i.list}"${i.project && !creds.project ? ` [${i.project}]` : ""}: [${i.status}] ${i.title} (item ${i.id}, by ${i.updated_by})`);
290
+ const noticeBlock = noticeLines.length ? [`Notices for this machine or project:`, ...noticeLines].join("\n") : "";
249
291
  const head = [
250
292
  messages.length ? `${messages.length} message${messages.length === 1 ? "" : "s"} for you` : null,
251
293
  items.length ? `${items.length} list item${items.length === 1 ? "" : "s"} assigned to you` : null,
252
294
  followed.length ? `new messages in followed channels` : null,
253
295
  digest.length ? `unread channels` : null,
296
+ noticeLines.length ? `${noticeLines.length} notice change${noticeLines.length === 1 ? "" : "s"}` : null,
297
+ measureLines.length ? `${measureLines.length} outcome measure change${measureLines.length === 1 ? "" : "s"}` : null,
254
298
  ].filter(Boolean).join(", ");
255
299
  const proj = creds.project ? "" : "--project <project> ";
256
300
  const footer = [];
257
301
  if (messages.length)
258
- footer.push(`These agents addressed you directly. Answer them in chat: bschat send ${proj}<channel> --reply-to <seq> "...".`);
302
+ footer.push(`These agents addressed you directly. Answer them in chat: b9s send ${proj}<channel> --reply-to <seq> "...".`);
259
303
  if (followed.length && !messages.length)
260
- footer.push(`Nobody addressed you. Reply in chat only if you have something to contribute: bschat send ${proj}<channel> --reply-to <seq> "...".`);
304
+ footer.push(`Nobody addressed you. Reply in chat only if you have something to contribute: b9s send ${proj}<channel> --reply-to <seq> "...".`);
261
305
  if (messages.length || followed.length)
262
- footer.push(`Other agents cannot see what you write in this session; only bschat messages reach them.`);
306
+ footer.push(`Other agents cannot see what you write in this session; only b9s messages reach them.`);
263
307
  const header = opts.delivery === "watch"
264
- ? `[bschat] Delivered by your BenignSwarm watcher, not typed by the user. ${head} (${name}):`
265
- : `[bschat] ${head} (${name}) on BenignSwarm:`;
308
+ ? `[b9s] Delivered by your BenignSwarm watcher, not typed by the user. ${head} (${name}):`
309
+ : `[b9s] ${head} (${name}) on BenignSwarm:`;
266
310
  const budget = opts.delivery === "watch" ? 3500 : opts.continuation ? 3900 : DELIVERY_BUDGET_BYTES;
267
311
  // The inbox cursor was advanced when gathering these items. A single explicit time cursor
268
312
  // retrieves every deferred addressed message across channels and keeps the pointer within
@@ -270,31 +314,40 @@ export async function gatherUpdates(name, opts) {
270
314
  const firstDeferred = messages.filter((m) => m.role_name !== "human").map((m) => m.created_at).sort()[0];
271
315
  const firstItemDeferred = items.map((item) => item.updated_at).filter((at) => !!at).sort()[0];
272
316
  const firstInboxDeferred = [firstDeferred, firstItemDeferred].filter((at) => !!at).sort()[0];
273
- const inboxPointer = firstInboxDeferred ? `bschat inbox --after ${new Date(Date.parse(firstInboxDeferred) - 1).toISOString()}` : "bschat inbox --unread";
274
- const directPointer = firstDeferred ? inboxPointer : "bschat inbox --unread";
275
- const itemPointer = firstItemDeferred ? inboxPointer : "bschat inbox --unread";
276
- const followedPointer = pendingReads.size ? "bschat read --pending" : readCommands.join("; ") || "bschat read --pending";
277
- const parts = { header, protectedDirect, direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "bschat read --pending" : "bschat inbox --unread", items: itemLines, followed, digest, footer, readCommand: `bschat read <channel> --since <seq>`, budget };
317
+ const inboxPointer = firstInboxDeferred ? `b9s inbox --after ${new Date(Date.parse(firstInboxDeferred) - 1).toISOString()}` : "b9s inbox --unread";
318
+ const directPointer = firstDeferred ? inboxPointer : "b9s inbox --unread";
319
+ const itemPointer = firstItemDeferred ? inboxPointer : "b9s inbox --unread";
320
+ const followedPointer = pendingReads.size ? "b9s read --pending" : readCommands.join("; ") || "b9s read --pending";
321
+ const parts = { header, protectedDirect: [...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 };
278
322
  const delivery = budgetDelivery(parts);
279
323
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
280
324
  const visibleReadCommands = readCommands.slice(0, 8);
281
325
  if (deferredReads.length)
282
- visibleReadCommands.push("bschat read --pending");
283
- const cmds = [...(messages.length || items.length ? ["bschat inbox --unread"] : []), ...visibleReadCommands];
284
- const direct = items.length > 0 || messages.some((m) => m.role_name === "human" || !!m.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(m.body));
326
+ visibleReadCommands.push("b9s read --pending");
327
+ const cmds = [...(messages.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
328
+ const direct = items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some((m) => m.role_name === "human" || !!m.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(m.body));
285
329
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
286
- return { text: delivery.text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length }, latestOperatorAt: operator, readCommands: cmds, tier, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
330
+ return { text: delivery.text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
331
+ }
332
+ /** Command patterns warn without blocking; errors remain visible to the caller. */
333
+ export async function commandWarnings(name, command) {
334
+ const client = Client.forAgent(loadAgent(name), undefined, { presence: false });
335
+ const response = await client.call("GET", "/agents/me/notices");
336
+ if (!Array.isArray(response.notices))
337
+ throw new Error("GET /agents/me/notices returned no notices array");
338
+ const normalizedCommand = normalizeShellCommand(command);
339
+ return response.notices.map((notice) => commandNoticeWarning(notice, normalizedCommand)).filter((warning) => warning !== null);
287
340
  }
288
341
  export async function reportDelivery(name, text, kinds, source = "hook") {
289
342
  try {
290
343
  const client = Client.forAgent(loadAgent(name), undefined, { presence: false });
291
344
  await client.call("POST", "/agents/me/heartbeat", {
292
- active_at: new Date().toISOString(), source: `bschat-${source}-delivery`, activity: null,
345
+ active_at: new Date().toISOString(), source: `b9s-${source}-delivery`, activity: null,
293
346
  delivery: { bytes: utf8Bytes(text), by_kind: { ...kinds, rules: Math.max(0, utf8Bytes(text) - Object.values(kinds).reduce((a, b) => a + b, 0)) } },
294
347
  });
295
348
  }
296
349
  catch (e) {
297
- process.stderr.write(`bschat: delivery metric failed: ${e.message}\n`);
350
+ process.stderr.write(`b9s: delivery metric failed: ${e.message}\n`);
298
351
  }
299
352
  }
300
353
  /**
@@ -328,6 +381,21 @@ export async function hook(p) {
328
381
  noteSession(name, "claude-code", input.transcript_path, typeof input.session_id === "string" ? input.session_id : null);
329
382
  if (event === "PostModelSwitch")
330
383
  return;
384
+ if (harness === "claude-code" && event === "PreToolUse") {
385
+ const toolInput = input?.tool_input;
386
+ if (input?.tool_name === "Bash" && typeof toolInput?.command === "string") {
387
+ let warnings;
388
+ try {
389
+ warnings = await commandWarnings(name, toolInput.command);
390
+ }
391
+ catch (e) {
392
+ warnings = [`Could not check command notices: ${e.message}`];
393
+ }
394
+ if (warnings.length)
395
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: warnings.map((w) => `[b9s] ${w}`).join("\n") } }) + "\n");
396
+ }
397
+ return;
398
+ }
331
399
  // Standing rules die with the context. On SessionStart (startup, resume, and after a compaction)
332
400
  // re-deliver the role description and the project's process when the agent has not seen this
333
401
  // version, and record that it was shown.
@@ -348,12 +416,12 @@ export async function hook(p) {
348
416
  writeState(name, { ...cur, heartbeat_at: Date.now(), ...(goalChanged ? { harness_goal: observedGoal ?? undefined, harness_goal_reported: true } : {}) });
349
417
  }
350
418
  catch (e) {
351
- process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
419
+ process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
352
420
  }
353
421
  }
354
422
  }
355
- const u = await gatherUpdates(name, { force: !!p.flags.force, model: str(p.flags, "model") });
356
- const formatted = formatHookDelivery(u, standing);
423
+ const u = await gatherUpdates(name, { force: !!p.flags.force || (harness === "claude-code" && event === "SessionStart"), model: str(p.flags, "model") });
424
+ const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
357
425
  const text = formatted.text;
358
426
  if (!text)
359
427
  return;
@@ -373,7 +441,7 @@ export async function recoveryBrief(name) {
373
441
  return { text, deferredText: text, acknowledge: false, version: 0, project: null };
374
442
  }
375
443
  catch (e) {
376
- process.stderr.write(`bschat: could not fetch recovery brief: ${e.message}\n`);
444
+ process.stderr.write(`b9s: could not fetch recovery brief: ${e.message}\n`);
377
445
  return { text: recoveryBriefUnavailableText, deferredText: recoveryBriefUnavailableText, acknowledge: false, version: 0, project: null };
378
446
  }
379
447
  }
@@ -394,7 +462,7 @@ async function standingRules(name, compacted) {
394
462
  return { ...rendered, version: proc.version, project: creds.project };
395
463
  }
396
464
  catch (e) {
397
- process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
465
+ process.stderr.write(`b9s: could not fetch role/process: ${e.message}\n`);
398
466
  return null;
399
467
  }
400
468
  }
@@ -406,33 +474,33 @@ async function acknowledgeStanding(name, standing, emittedFullRules) {
406
474
  await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
407
475
  }
408
476
  catch (e) {
409
- process.stderr.write(`bschat: could not acknowledge process rules: ${e.message}\n`);
477
+ process.stderr.write(`b9s: could not acknowledge process rules: ${e.message}\n`);
410
478
  }
411
479
  }
412
480
  export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
413
481
  const shortRole = roleIdentity ?? (/^Your role: [^.]+\./.exec(roleLine)?.[0] ?? roleLine.slice(0, 300));
414
- const deferredText = `[bschat] Process v${proc.version}. ${shortRole}\nRole details: bschat me\nRead the current rules: bschat process`;
482
+ const deferredText = `[b9s] Process v${proc.version}. ${shortRole}\nRole details: b9s me\nRead the current rules: b9s process`;
415
483
  const fit = (text, acknowledge) => utf8Bytes(text) > DELIVERY_BUDGET_BYTES
416
484
  ? { text: deferredText, acknowledge: false, deferredText }
417
485
  : { text, acknowledge, deferredText };
418
486
  if (compacted)
419
- return fit(`${roleLine}\nRead the current rules: bschat process`, false);
487
+ return fit(`${roleLine}\nRead the current rules: b9s process`, false);
420
488
  if (proc.seen_version === proc.version)
421
- return fit(`[bschat] Process v${proc.version}. ${roleLine}`, false);
489
+ return fit(`[b9s] Process v${proc.version}. ${roleLine}`, false);
422
490
  if (proc.seen_version !== null) {
423
491
  const changed = (proc.changes_since_seen ?? []).map((line) => `- ${line}`);
424
492
  const rulesChanged = proc.rules_changed_since_seen === true || (proc.changes_since_seen ?? []).some((line) => /^(working agreements|charter) (edited|added|removed)$/.test(line));
425
493
  return fit([
426
- `[bschat] Process v${proc.version}. ${roleLine}`,
494
+ `[b9s] Process v${proc.version}. ${roleLine}`,
427
495
  `Changed since you read v${proc.seen_version}:`,
428
- ...(changed.length ? changed : ["- Details: bschat process"]),
496
+ ...(changed.length ? changed : ["- Details: b9s process"]),
429
497
  rulesChanged && proc.agreements ? `Current working agreements:\n${proc.agreements}` : null,
430
498
  rulesChanged && proc.charter ? `Current charter:\n${proc.charter}` : null,
431
499
  ].filter(Boolean).join("\n"), true);
432
500
  }
433
501
  const lines = [
434
- `[bschat] Your standing role and process.`, roleLine,
435
- `Process v${proc.version}: work goes through bschat wu open --tags <from the vocabulary> / submit; reviewers are whoever is qualified for the tags; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units; nothing is done until every tag is approved. Details: bschat process.`,
502
+ `[b9s] Your standing role and process.`, roleLine,
503
+ `Process v${proc.version}: work goes through b9s wu open --tags <from the vocabulary> / submit; reviewers are whoever is qualified for the tags; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units; nothing is done until every tag is approved. Details: b9s process.`,
436
504
  proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
437
505
  proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
438
506
  ].filter(Boolean);
@@ -457,7 +525,7 @@ async function antigravityHook(p) {
457
525
  syncFromWatchers();
458
526
  }
459
527
  catch (e) {
460
- process.stderr.write(`bschat: could not read watchers: ${e.message}\n`);
528
+ process.stderr.write(`b9s: could not read watchers: ${e.message}\n`);
461
529
  }
462
530
  ref = conversationAgent(conv);
463
531
  }
@@ -484,7 +552,7 @@ async function antigravityHook(p) {
484
552
  writeState(name, { ...readState(name), heartbeat_at: Date.now() });
485
553
  }
486
554
  catch (e) {
487
- process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
555
+ process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
488
556
  }
489
557
  }
490
558
  if (event === "PostToolUse")
@@ -508,19 +576,19 @@ async function antigravityHook(p) {
508
576
  return out({});
509
577
  const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
510
578
  const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
511
- const formatted = formatHookDelivery(u, standing);
579
+ const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
512
580
  if (formatted.text)
513
581
  await reportDelivery(name, formatted.text, formatted.by_kind);
514
582
  out(formatted.text ? { injectSteps: [{ systemMessage: { systemMessage: formatted.text } }] } : {});
515
583
  await acknowledgeStanding(name, standing, formatted.acknowledge);
516
584
  }
517
585
  /**
518
- * Codex's hooks (~/.codex/hooks.json, written by `bschat codex hooks`; Claude Code's format):
586
+ * Codex's hooks (~/.codex/hooks.json, written by `b9s codex hooks`; Claude Code's format):
519
587
  * SessionStart injects the standing rules and anything unread, UserPromptSubmit new items,
520
588
  * PostToolUse is a liveness heartbeat, and Stop with something addressed to the agent returns
521
589
  * "block" with it, which Codex takes as the next input instead of stopping. The hooks file is the
522
590
  * machine's, so the agent is found by the session id (the Codex thread a watcher wakes, or
523
- * `bschat codex bind`); any other Codex session (the user's own chats) gets nothing.
591
+ * `b9s codex bind`); any other Codex session (the user's own chats) gets nothing.
524
592
  * Always exits 0 with valid output: a hook must never break the session.
525
593
  */
526
594
  async function codexHook(p) {
@@ -533,7 +601,7 @@ async function codexHook(p) {
533
601
  syncFromWatchers();
534
602
  }
535
603
  catch (e) {
536
- process.stderr.write(`bschat: could not read watchers: ${e.message}\n`);
604
+ process.stderr.write(`b9s: could not read watchers: ${e.message}\n`);
537
605
  }
538
606
  ref = sessionAgent("codex", sid);
539
607
  }
@@ -559,7 +627,7 @@ async function codexHook(p) {
559
627
  writeState(name, { ...readState(name), heartbeat_at: Date.now() });
560
628
  }
561
629
  catch (e) {
562
- process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
630
+ process.stderr.write(`b9s: heartbeat failed: ${e.message}\n`);
563
631
  }
564
632
  }
565
633
  const context = (text) => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
@@ -583,7 +651,7 @@ async function codexHook(p) {
583
651
  return;
584
652
  const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
585
653
  const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
586
- const formatted = formatHookDelivery(u, standing);
654
+ const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
587
655
  if (formatted.text)
588
656
  await reportDelivery(name, formatted.text, formatted.by_kind);
589
657
  if (formatted.text)