@cohortapp/agent-sdk 2.18.37 → 2.19.0

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.
@@ -131,6 +131,297 @@ const PERSONA_FILES = Object.freeze({
131
131
  peers: "state/session/peers.json",
132
132
  });
133
133
 
134
+ /* ─────────────── machine internals and the agent's own sessions ──────────── */
135
+ // PERSONA_PATTERNS above is a PORT, pinned to the frozen shell hook by
136
+ // scripts/hooks/pre-send-audit.parity.test.mjs. It knew the product names of
137
+ // the machinery and nothing about the machine's own working state, so a body
138
+ // built from a session's end-of-turn notes — agent-local file paths, queue and
139
+ // inbox ids, "a reply from a concurrent session" — passed every layer of this
140
+ // gate and reached team channels under the seat's name.
141
+ //
142
+ // These rules are NEW, owe no shell parity, and are therefore a separate list
143
+ // applied by BOTH screens (`screenOutbound` and `screenHookPayload`) — the same
144
+ // arrangement as SCAFFOLD_MARKERS. Do not fold them into PERSONA_PATTERNS: that
145
+ // would change the ported verdicts the parity oracle pins.
146
+ //
147
+ // THE SEPARATING RULE IS WHOSE INTERNALS. The agent's own machine and working
148
+ // state (its state/ and audit-log trees, absolute machine paths, its queue and
149
+ // inbox ids, its sessions and their concurrency) is never something a colleague
150
+ // can open or needs to know. The product repos the desk discusses are the
151
+ // opposite: repo-relative paths, `file.ts:NNN`, commit shas, PR numbers, DI
152
+ // token and env var names are the SUBSTANCE of a code review and must pass. So
153
+ // every rule here is anchored on a shape only the agent produces, never on
154
+ // "looks like a path" or "mentions a session". `session` alone is an ordinary
155
+ // trading word (RTH session, one clean session, mid-session, session close) and
156
+ // no rule matches it bare.
157
+ //
158
+ // A MATCH IS A REFUSAL, NEVER A REDACTION. The caller gets the rule id and the
159
+ // exact span so the sender can restate it; nothing is rewritten on the way out,
160
+ // because the same words can be a legitimate answer in the wrong form (where
161
+ // evidence is held is a fair compliance question; a filesystem path is the wrong
162
+ // way to answer it) and a silent edit would send a meaning nobody wrote.
163
+ //
164
+ // The corpus that pins both directions is lib/comms/fallback-leak-corpus.test.mjs.
165
+
166
+ /** First-person verbs of an agent's own message and queue work. */
167
+ const AGENT_WORK_VERB = /\b(?:replied|responded|answered|wrote|written|queued|filed|logged|archived|re-?read|spawned|claimed|in-channel)\b/i;
168
+
169
+ /** Trailing sentence punctuation is not part of a path span. */
170
+ function trimSpan(s) {
171
+ return String(s).replace(/[.,:;!?]+$/, "");
172
+ }
173
+
174
+ /**
175
+ * A rule backed by one regex: every match, trimmed, with its index.
176
+ * @param {string} id @param {"persona"|"path"|"id"} kind @param {RegExp} re @param {string} hint
177
+ */
178
+ function regexRule(id, kind, re, hint) {
179
+ const flags = re.flags.includes("g") ? re.flags : `${re.flags}g`;
180
+ const global = new RegExp(re.source, flags);
181
+ return Object.freeze({
182
+ id,
183
+ kind,
184
+ hint,
185
+ find(text) {
186
+ const out = [];
187
+ global.lastIndex = 0;
188
+ let m;
189
+ while ((m = global.exec(text)) !== null) {
190
+ const match = kind === "path" ? trimSpan(m[0]) : m[0];
191
+ if (match) out.push({ match, index: m.index });
192
+ if (m[0] === "") global.lastIndex++;
193
+ }
194
+ return out;
195
+ },
196
+ });
197
+ }
198
+
199
+ const HINT_PERSONA = "Own the work in the first person, or say \"my team\" / \"a colleague\"; never name this agent's sessions or their concurrency.";
200
+ const HINT_PATH = "Describe what it is and where it stands (\"the follow-up I filed\", \"the only copy is on one machine\"), not this machine's files.";
201
+ const HINT_ID = "Name the item the way the reader knows it (\"your ask from this morning\", \"the freeze item\"), not by its queue or inbox id.";
202
+
203
+ /** The rest of a path once its root is known: up to whitespace, a quote, a backtick or a bracket. */
204
+ const PATH_TAIL = "[^\\s\\x60'\"()<>|,;]+";
205
+
206
+ /**
207
+ * The agent directory's own name (`/Users/x/jacob` → `jacob`), for `~/jacob/…`.
208
+ * Null when it is missing or too generic to be a safe anchor.
209
+ * @param {unknown} agentRoot
210
+ * @returns {string|null}
211
+ */
212
+ function agentDirName(agentRoot) {
213
+ const parts = String(agentRoot || "").replace(/\/+$/, "").split("/");
214
+ const base = parts[parts.length - 1] || "";
215
+ if (!/^[\w.-]{3,}$/.test(base)) return null;
216
+ if (["src", "lib", "app", "repo", "home", "tmp", "maestro"].includes(base.toLowerCase())) return null;
217
+ return base;
218
+ }
219
+
220
+ /**
221
+ * The machine-leak rules, in report order. Each carries an `id` (returned to
222
+ * the sender with the span), a `kind` and a rewrite `hint`.
223
+ *
224
+ * ID SHAPES ARE READ FROM THE QUEUES, NOT GUESSED. `maestro init` scaffolds the
225
+ * queue files named in `queue-file`; the item ids seats actually write into them
226
+ * have the shapes `FU-123`, `IMP-0042`, `DQ-012`/`TD-012`/`PB-012`/`LO-012`/`AR-012`,
227
+ * `CS-0927-04`/`MB-0927-01`, `WK-01`/`WK2-03`, and the dated slug form
228
+ * `fu-YYYY-MM-DD-<slug>` (also `cw-…`, `ib-…`). Shared register ids that also
229
+ * appear in those queues (`ACT-…`, `RSK-…`, `HR-…`) belong to the org, are used
230
+ * by people, and are deliberately NOT matched.
231
+ *
232
+ * @type {ReadonlyArray<{id:string, kind:string, hint:string, find:(text:string, ctx?:object)=>{match:string,index:number}[]}>}
233
+ */
234
+ export const MACHINE_LEAK_RULES = Object.freeze([
235
+ // "a concurrent session", "a parallel session", "another peer session". A
236
+ // determiner is required so a count ("100 concurrent sessions" on a pooler)
237
+ // reads as the engineering it is.
238
+ regexRule(
239
+ "session-concurrency",
240
+ "persona",
241
+ /\b(?:a|an|the|another|one|some|each|my|our|this|that|its)\s+(?:other\s+)?(?:concurrent|parallel|sibling|peer|spawned|forked|background)\s+(?:claude\s+|working\s+|agent\s+)?sessions?\b/i,
242
+ HINT_PERSONA,
243
+ ),
244
+ // A session as the subject of an agent's own act. Trading sessions open,
245
+ // close, rally and fade; they do not reply, draft or claim.
246
+ regexRule(
247
+ "session-agency",
248
+ "persona",
249
+ /\b(?:a|an|another|the\s+other|that|one|my|this)\s+sessions?\s+(?:(?:has|had|have)\s+)?(?:already\s+)?(?:replied|answered|responded|drafted|claimed|queued|spawned|wrote)\b/i,
250
+ HINT_PERSONA,
251
+ ),
252
+ regexRule(
253
+ "reply-from-another-session",
254
+ "persona",
255
+ /\b(?:repl(?:y|ies)|answers?|messages?|posts?|responses?|drafts?)\s+(?:\w+\s+){0,2}(?:from|by)\s+(?:another|a\s+different|the\s+other)\s+sessions?\b/i,
256
+ HINT_PERSONA,
257
+ ),
258
+ // "my session log", "my session on this was interrupted", "my sessions". A
259
+ // meeting ("my session with the auditors") is not the machinery.
260
+ regexRule(
261
+ "my-session",
262
+ "persona",
263
+ /\bmy\s+(?:own\s+|working\s+|earlier\s+|last\s+|previous\s+|other\s+|current\s+)?sessions?\b(?!\s+with\b)/i,
264
+ HINT_PERSONA,
265
+ ),
266
+ // "this session" is ordinary desk language ("weakest name in the book this
267
+ // session"). It is the agent's own run only when the same sentence narrates
268
+ // the agent's message or queue work, so the rule needs both.
269
+ Object.freeze({
270
+ id: "this-session-agent-work",
271
+ kind: "persona",
272
+ hint: HINT_PERSONA,
273
+ find(text) {
274
+ const out = [];
275
+ const sentence = /[^.!?\n]+[.!?]?/g;
276
+ let m;
277
+ while ((m = sentence.exec(text)) !== null) {
278
+ if (/\bthis\s+session\b/i.test(m[0]) && AGENT_WORK_VERB.test(m[0])) {
279
+ const s = m[0].trim();
280
+ out.push({ match: s, index: m.index + m[0].indexOf(s) });
281
+ }
282
+ }
283
+ return out;
284
+ },
285
+ }),
286
+ // The persona rule names "subagent" outright; the ported list above only
287
+ // blocks it when it is said to have spoken, so the bare noun gets its own rule.
288
+ // As a WORD only: inside an identifier or a path (`check-subagent-frontmatter`,
289
+ // `sections/subagents.test.mjs`) it is the name of a file or a CI guard in a
290
+ // code review, which is substance. A sentence-final "subagents." still matches.
291
+ regexRule("subagent", "persona", /(?<![\w./-])sub-?agents?(?![\w-]|[./]\w)/i, HINT_PERSONA),
292
+ // The agent's own state and audit trees, as a relative path. Anchored so a
293
+ // product path that merely CONTAINS a `state/` directory
294
+ // (`engine/src/state/…`) is not matched, and requiring a second segment or a
295
+ // file extension so prose like "state/action pairs" or "logs/metrics/traces"
296
+ // reads as prose.
297
+ regexRule(
298
+ "agent-state-path",
299
+ "path",
300
+ /(?<![\w./~$-])(?:state\/(?:[\w.-]+\/[\w.*-]*|[\w-]+\.(?:ya?ml|jsonl?|md|txt|db|lock|pid|tsv))|logs\/audit\b[\w./-]*|logs\/[\w./-]+\.jsonl\b)/,
301
+ HINT_PATH,
302
+ ),
303
+ // Anything spelled from the agent root: `$AGENT_DIR/…`, `$AGENT_ROOT/…`, and
304
+ // — when the caller knows the root — `~/<agent-dir>/…`.
305
+ Object.freeze({
306
+ id: "agent-root-path",
307
+ kind: "path",
308
+ hint: HINT_PATH,
309
+ find(text, ctx = {}) {
310
+ const res = [new RegExp("\\$\\{?AGENT_(?:DIR|ROOT)\\}?\\/" + PATH_TAIL, "g")];
311
+ const base = agentDirName(ctx && ctx.agentRoot);
312
+ if (base) res.push(new RegExp("~\\/" + escapeRe(base) + "\\/" + PATH_TAIL, "g"));
313
+ const out = [];
314
+ for (const re of res) {
315
+ let m;
316
+ while ((m = re.exec(text)) !== null) {
317
+ const match = trimSpan(m[0]);
318
+ if (match) out.push({ match, index: m.index });
319
+ }
320
+ }
321
+ return out;
322
+ },
323
+ }),
324
+ // An absolute path on THIS machine: a macOS user home, a mounted volume, the
325
+ // per-user temp tree. Not `/tmp/…` or `/home/…`, which in an engineering post
326
+ // are almost always a container's paths and mean the same thing on every box.
327
+ // The lookbehind keeps a URL path (`github.com/Users/…`) and a product path
328
+ // segment from matching; `file:///Users/…` still matches.
329
+ regexRule(
330
+ "absolute-machine-path",
331
+ "path",
332
+ new RegExp("(?<![\\w.-])\\/(?:Users|Volumes|private\\/(?:var|tmp|etc)|var\\/folders)\\/" + PATH_TAIL),
333
+ HINT_PATH,
334
+ ),
335
+ regexRule(
336
+ "queue-item-id",
337
+ "id",
338
+ /\b(?:FU-\d{3,4}|IMP-\d{4}|(?:DQ|TD|PB|LO|AR)-\d{3}|CS-\d{4}-\d{2}|MB-\d{4}-\d{2}|WK\d?-\d{2})\b|\b(?:fu|cw|ib)-\d{4}-\d{2}-\d{2}(?:-[a-z0-9]+)+/,
339
+ HINT_ID,
340
+ ),
341
+ // The queue files themselves, named bare — a backup or a "last row in…". As a
342
+ // path (`state/queues/…`) they are already `agent-state-path`, so this one
343
+ // only fires when the name stands alone. The list is `maestro init`'s queue
344
+ // scaffold (bin/maestro.mjs) plus the inbound queue.
345
+ regexRule(
346
+ "queue-file",
347
+ "path",
348
+ /(?<![\w/.-])(?:action-stack|follow-ups|decision-queue|awaiting-reply|awaiting-approval|blocked-initiatives|high-risk-items|upcoming-deadlines|relationship-health|hiring-critical-path|platform-blockers|capital-watchpoints|legal-obligations|narrative-opportunities|tech-debt|improvement-backlog|inbound)\.yaml\b/,
349
+ HINT_PATH,
350
+ ),
351
+ // Inbox and obligation handles: the inbound-queue id (`inb-<svc>.<kind>#n`),
352
+ // the obligation key (`cohort_<kind>_<cuid>_<n>`), the item reference
353
+ // (`cohort:<kind>:<cuid>:<n>`), an inbox file name, and the processed/deferred
354
+ // markers. A bare Cohort message id is NOT matched: people and clients use
355
+ // those as permalinks.
356
+ regexRule(
357
+ "inbox-item-ref",
358
+ "id",
359
+ /\binb-[a-z_]+\.[a-z_.]+#\d+|\bcohort_[a-z_]+_c[a-z0-9]{20,}_\d+\b|\bcohort:[a-z_]+:c[a-z0-9]{20,}:\d+\b|\.yaml\.(?:processed|deferred|bundled|claimed)(?:-[a-z]+)?\b|\b\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-z]+-[\w-]+\.yaml\b/,
360
+ HINT_ID,
361
+ ),
362
+ ]);
363
+
364
+ /**
365
+ * Every machine-leak match in `text`, ordered by position. Pure.
366
+ *
367
+ * @param {string} text
368
+ * @param {{rules?:ReadonlyArray<object>, agentRoot?:string}} [o]
369
+ * `rules` is the ablation seam (fallback-leak-corpus.test.mjs removes one
370
+ * rule at a time); `agentRoot` lets `agent-root-path` match `~/<dir>/…`.
371
+ * @returns {{rule:string, kind:string, match:string, index:number}[]}
372
+ */
373
+ export function findMachineLeaks(text, o = {}) {
374
+ const t = typeof text === "string" ? text : "";
375
+ if (!t) return [];
376
+ const rules = Array.isArray(o.rules) ? o.rules : MACHINE_LEAK_RULES;
377
+ const out = [];
378
+ const seen = new Set();
379
+ for (const rule of rules) {
380
+ for (const hit of rule.find(t, o)) {
381
+ const k = `${rule.id}@${hit.index}`;
382
+ if (seen.has(k)) continue;
383
+ seen.add(k);
384
+ out.push({ rule: rule.id, kind: rule.kind, match: hit.match, index: hit.index });
385
+ }
386
+ }
387
+ return out.sort((a, b) => a.index - b.index || a.rule.localeCompare(b.rule));
388
+ }
389
+
390
+ /** How many matches a refusal spells out before summarising the rest. */
391
+ const MACHINE_LEAK_REPORT_LIMIT = 10;
392
+
393
+ /**
394
+ * The refusal for a body carrying machine internals, or null. Pure.
395
+ *
396
+ * LOUD BY CONSTRUCTION: the reason names every rule and quotes every span (up to
397
+ * {@link MACHINE_LEAK_REPORT_LIMIT}), so one refusal tells the sender everything
398
+ * to rewrite, and it says in words that nothing was sent and nothing was edited.
399
+ *
400
+ * @param {string} text
401
+ * @param {{agentRoot?:string}} [o]
402
+ * @returns {null|{reason:string, rule:string, match:string, matches:object[]}}
403
+ */
404
+ export function machineLeakVerdict(text, o = {}) {
405
+ const found = findMachineLeaks(text, o);
406
+ if (!found.length) return null;
407
+ const shown = found.slice(0, MACHINE_LEAK_REPORT_LIMIT);
408
+ const list = shown.map((m) => "rule \"" + m.rule + "\" matched \"" + m.match + "\"").join("; ");
409
+ const more = found.length > shown.length ? " (and " + (found.length - shown.length) + " more)" : "";
410
+ const hints = [];
411
+ for (const m of found) {
412
+ const r = MACHINE_LEAK_RULES.find((x) => x.id === m.rule);
413
+ if (r && !hints.includes(r.hint)) hints.push(r.hint);
414
+ }
415
+ return {
416
+ reason:
417
+ "machine internals in the outbound body — " + list + more + ". " +
418
+ "Nothing was sent and nothing was redacted: rewrite it in your own words and send again. " +
419
+ hints.join(" "),
420
+ rule: found[0].rule,
421
+ match: found[0].match,
422
+ matches: found.map(({ rule, kind, match, index }) => ({ rule, kind, match, index })),
423
+ };
424
+ }
134
425
  /* ──────────────────────── session-scaffold markers ───────────────────────── */
135
426
  // A raw model turn must never reach a person. On 5 and 20 September 2026, bodies
136
427
  // carrying `<user_message>`, a closing `</thinking>` and the responder's
@@ -793,6 +1084,14 @@ export async function screenOutbound({
793
1084
  const personaReason = screenPersona(text, personaContext(fs, agentRoot, { agentFirst, sessionNames }));
794
1085
  if (personaReason) return blocked(personaReason);
795
1086
 
1087
+ // (a3) Machine internals and the agent's own sessions — MACHINE_LEAK_RULES.
1088
+ // Pure, reads no file, so like the scaffold screen it has no fail
1089
+ // posture: it blocks for internal recipients too, because every
1090
+ // recorded leak of this kind went to an internal channel with people
1091
+ // in it. The verdict carries the rule and the span for the sender.
1092
+ const leak = machineLeakVerdict(text, { agentRoot });
1093
+ if (leak) return blocked(leak.reason, { rule: leak.rule, match: leak.match, matches: leak.matches });
1094
+
796
1095
  // (b) AI-disclosure. The truthfulness invariant is enforced from the
797
1096
  // embedded denial list even without the file; posture resolution needs
798
1097
  // the file. Missing file → invariant still runs; posture defaults apply.
@@ -1090,9 +1389,10 @@ export function hookAllowlistMatch(recipient, allowlistText) {
1090
1389
  * @param {string} o.stdin the raw PreToolUse payload
1091
1390
  * @param {string[]} [o.sessionNames] from hookSessionNames
1092
1391
  * @param {null|{path:string, text:string|null}} [o.allowlist] null = not enforced; text null = unreadable
1392
+ * @param {string} [o.agentRoot] the agent root, so `agent-root-path` can match `~/<agent-dir>/…`
1093
1393
  * @returns {{allow:true, recipient:string}|{allow:false, reason:string}}
1094
1394
  */
1095
- export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist = null }) {
1395
+ export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist = null, agentRoot = "" }) {
1096
1396
  const deny = (reason) => ({ allow: false, reason });
1097
1397
  if (!channel) return deny(HOOK_CHANNEL_REQUIRED);
1098
1398
  const raw = shellCaptured(stdin == null ? "" : stdin);
@@ -1139,6 +1439,13 @@ export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist
1139
1439
  const hit = hookSessionNameHit(text, name);
1140
1440
  if (hit) return deny(`Persona leak in outbound message: "${hit}" is an internal session name — say "my team" or "a colleague" instead`);
1141
1441
  }
1442
+ // (a3) Machine internals — the shared MACHINE_LEAK_RULES, as in screenOutbound.
1443
+ // Outside the parity contract by construction, like the scaffold screen: the
1444
+ // frozen shell oracle has no counterpart rule, so this is an ADDITION.
1445
+ const leak = machineLeakVerdict(text, { agentRoot });
1446
+ if (leak) {
1447
+ return { allow: false, reason: `Machine internals in outbound message: ${leak.reason}`, rule: leak.rule, match: leak.match, matches: leak.matches };
1448
+ }
1142
1449
  if (recipient && allowlist) {
1143
1450
  if (allowlist.text == null || !hookAllowlistMatch(recipient, allowlist.text)) {
1144
1451
  return deny(`Recipient "${recipient}" not on send allowlist (${allowlist.path})`);
@@ -1325,7 +1632,7 @@ export function preparePreSendHook({ channel, stdin, env = process.env, now = ne
1325
1632
  const allowPath = v("MAESTRO_SEND_ALLOWLIST");
1326
1633
  const allowlist = allowPath && isFile(allowPath) ? { path: allowPath, text: readIfFile(allowPath) } : null;
1327
1634
 
1328
- const screened = screenHookPayload({ channel, stdin, sessionNames, allowlist });
1635
+ const screened = screenHookPayload({ channel, stdin, sessionNames, allowlist, agentRoot: v("AGENT_ROOT") || v("AGENT_DIR") });
1329
1636
  if (!screened.allow) return refuse(screened.reason);
1330
1637
 
1331
1638
  const runtimeDir = `${v("MAESTRO_RUNTIME_DIR") || `${v("HOME")}/.maestro/runtime`}/audit`;
@@ -22,6 +22,7 @@
22
22
  "use strict";
23
23
 
24
24
  import { loadOrgContext } from "./bootstrap-context.mjs";
25
+ import { loadChain } from "./escalation-chain.mjs";
25
26
 
26
27
  /**
27
28
  * Resolve the first arg into a context object. A string is treated as an
@@ -101,8 +102,20 @@ export function escalateTo(ctxOrRoot) {
101
102
  refSummary(profile.reportingLine && profile.reportingLine.manager) ||
102
103
  refSummary(rel.reportingLine && rel.reportingLine.manager);
103
104
 
104
- if (!escalationPath && !manager) return null;
105
- return { escalationPath, manager };
105
+ // Genesis M3: when the seat reports to an AGENT, the person an escalation
106
+ // must finally reach is the first human up the chain (escalation-chain.mjs,
107
+ // walked loop-safely on the beat). Added ONLY when a walk has resolved one,
108
+ // so an old server's answer keeps its exact pre-WS6 shape.
109
+ const chain =
110
+ ctx.escalationChain && typeof ctx.escalationChain === "object"
111
+ ? ctx.escalationChain
112
+ : typeof ctxOrRoot === "string"
113
+ ? loadChain(ctxOrRoot)
114
+ : null;
115
+ const firstHuman = chain && chain.firstHuman ? { memberId: String(chain.firstHuman), via: Array.isArray(chain.path) ? chain.path.slice() : [] } : null;
116
+
117
+ if (!escalationPath && !manager && !firstHuman) return null;
118
+ return firstHuman ? { escalationPath, manager, firstHuman } : { escalationPath, manager };
106
119
  }
107
120
 
108
121
  /**