@cohortapp/agent-sdk 2.18.37 → 2.19.1

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.
Files changed (39) hide show
  1. package/bin/maestro.mjs +10 -1
  2. package/docs/guides/billing-console-keys.md +16 -3
  3. package/lib/assurance/first-reply.mjs +31 -2
  4. package/lib/assurance/operator-plane-store.mjs +164 -0
  5. package/lib/assurance/operator-plane.mjs +689 -0
  6. package/lib/budget-guard.mjs +93 -3
  7. package/lib/cli/attention.mjs +300 -0
  8. package/lib/cli/seat-auth.mjs +86 -6
  9. package/lib/comms/receipts.mjs +15 -3
  10. package/lib/comms/send-gate.mjs +329 -2
  11. package/lib/org/awareness.mjs +15 -2
  12. package/lib/org/clause-match.mjs +470 -0
  13. package/lib/org/client.mjs +27 -1
  14. package/lib/org/escalation-chain.mjs +134 -0
  15. package/lib/org/first-run.mjs +263 -0
  16. package/lib/org/genesis-contract.mjs +271 -0
  17. package/lib/org/governance-runtime.mjs +409 -0
  18. package/lib/org/governance-store.mjs +238 -0
  19. package/lib/org/governance.mjs +326 -0
  20. package/lib/org/mesh.mjs +135 -0
  21. package/lib/org/protocol.checksum +1 -1
  22. package/lib/org/protocol.mjs +6 -0
  23. package/lib/org/registry.mjs +7 -1
  24. package/lib/org/tool-surface.mjs +28 -0
  25. package/lib/setup/enroll-from-cohort.mjs +11 -0
  26. package/lib/telemetry/alerts.mjs +86 -1
  27. package/lib/telemetry/collect.mjs +237 -1
  28. package/package.json +1 -1
  29. package/scripts/daemon/agent-daemon.mjs +41 -2
  30. package/scripts/daemon/assurance.mjs +482 -55
  31. package/scripts/daemon/cadence-consumer.mjs +17 -0
  32. package/scripts/daemon/context-compiler.mjs +25 -0
  33. package/scripts/daemon/deliver.mjs +71 -5
  34. package/scripts/fleet/closing-sweep.mjs +266 -0
  35. package/scripts/healthcheck.sh +35 -0
  36. package/scripts/local-triggers/autoupdate.sh +61 -5
  37. package/scripts/maintenance/check-stamp-freshness.mjs +314 -0
  38. package/scripts/org/send-orgmail.mjs +112 -25
  39. package/scripts/session/supervisor.mjs +14 -0
@@ -131,6 +131,317 @@ 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
+ * ── A NEW SHAPE LANDS IN THE RULE AND THE CORPUS TOGETHER ───────────────────
233
+ *
234
+ * These rules are a vocabulary, and a vocabulary only covers the shapes it was
235
+ * told about. A newly minted queue file, queue-id prefix or inbox/obligation
236
+ * handle that is not added here is a shape that leaks with nothing going red.
237
+ * So, in the SAME change that introduces it:
238
+ *
239
+ * 1. add it to the rule (`queue-file`, `queue-item-id` or `inbox-item-ref`);
240
+ * 2. add a must-block case for it under that rule's id in `DEDICATED` in
241
+ * lib/comms/fallback-leak-corpus.test.mjs — the in-file ablation then
242
+ * proves the rule is what catches it;
243
+ * 3. add a must-pass case for any legitimate look-alike it could swallow
244
+ * (an org register id, a product path) to the corpus's PASS lists.
245
+ *
246
+ * Queue FILE names are minted in one place (`maestro init`'s queue scaffold,
247
+ * bin/maestro.mjs), so that half is also enforced: the corpus fails if a
248
+ * scaffolded queue is not named by `queue-file`. Queue ID prefixes are minted by
249
+ * seats, with no central declaration to check against, so that half is this
250
+ * rule — recorded again in docs/engineering/functional-architecture.md §9.
251
+ *
252
+ * @type {ReadonlyArray<{id:string, kind:string, hint:string, find:(text:string, ctx?:object)=>{match:string,index:number}[]}>}
253
+ */
254
+ export const MACHINE_LEAK_RULES = Object.freeze([
255
+ // "a concurrent session", "a parallel session", "another peer session". A
256
+ // determiner is required so a count ("100 concurrent sessions" on a pooler)
257
+ // reads as the engineering it is.
258
+ regexRule(
259
+ "session-concurrency",
260
+ "persona",
261
+ /\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,
262
+ HINT_PERSONA,
263
+ ),
264
+ // A session as the subject of an agent's own act. Trading sessions open,
265
+ // close, rally and fade; they do not reply, draft or claim.
266
+ regexRule(
267
+ "session-agency",
268
+ "persona",
269
+ /\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,
270
+ HINT_PERSONA,
271
+ ),
272
+ regexRule(
273
+ "reply-from-another-session",
274
+ "persona",
275
+ /\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,
276
+ HINT_PERSONA,
277
+ ),
278
+ // "my session log", "my session on this was interrupted", "my sessions". A
279
+ // meeting ("my session with the auditors") is not the machinery.
280
+ regexRule(
281
+ "my-session",
282
+ "persona",
283
+ /\bmy\s+(?:own\s+|working\s+|earlier\s+|last\s+|previous\s+|other\s+|current\s+)?sessions?\b(?!\s+with\b)/i,
284
+ HINT_PERSONA,
285
+ ),
286
+ // "this session" is ordinary desk language ("weakest name in the book this
287
+ // session"). It is the agent's own run only when the same sentence narrates
288
+ // the agent's message or queue work, so the rule needs both.
289
+ Object.freeze({
290
+ id: "this-session-agent-work",
291
+ kind: "persona",
292
+ hint: HINT_PERSONA,
293
+ find(text) {
294
+ const out = [];
295
+ const sentence = /[^.!?\n]+[.!?]?/g;
296
+ let m;
297
+ while ((m = sentence.exec(text)) !== null) {
298
+ if (/\bthis\s+session\b/i.test(m[0]) && AGENT_WORK_VERB.test(m[0])) {
299
+ const s = m[0].trim();
300
+ out.push({ match: s, index: m.index + m[0].indexOf(s) });
301
+ }
302
+ }
303
+ return out;
304
+ },
305
+ }),
306
+ // The persona rule names "subagent" outright; the ported list above only
307
+ // blocks it when it is said to have spoken, so the bare noun gets its own rule.
308
+ // As a WORD only: inside an identifier or a path (`check-subagent-frontmatter`,
309
+ // `sections/subagents.test.mjs`) it is the name of a file or a CI guard in a
310
+ // code review, which is substance. A sentence-final "subagents." still matches.
311
+ regexRule("subagent", "persona", /(?<![\w./-])sub-?agents?(?![\w-]|[./]\w)/i, HINT_PERSONA),
312
+ // The agent's own state and audit trees, as a relative path. Anchored so a
313
+ // product path that merely CONTAINS a `state/` directory
314
+ // (`engine/src/state/…`) is not matched, and requiring a second segment or a
315
+ // file extension so prose like "state/action pairs" or "logs/metrics/traces"
316
+ // reads as prose.
317
+ regexRule(
318
+ "agent-state-path",
319
+ "path",
320
+ /(?<![\w./~$-])(?:state\/(?:[\w.-]+\/[\w.*-]*|[\w-]+\.(?:ya?ml|jsonl?|md|txt|db|lock|pid|tsv))|logs\/audit\b[\w./-]*|logs\/[\w./-]+\.jsonl\b)/,
321
+ HINT_PATH,
322
+ ),
323
+ // Anything spelled from the agent root: `$AGENT_DIR/…`, `$AGENT_ROOT/…`, and
324
+ // — when the caller knows the root — `~/<agent-dir>/…`.
325
+ Object.freeze({
326
+ id: "agent-root-path",
327
+ kind: "path",
328
+ hint: HINT_PATH,
329
+ find(text, ctx = {}) {
330
+ const res = [new RegExp("\\$\\{?AGENT_(?:DIR|ROOT)\\}?\\/" + PATH_TAIL, "g")];
331
+ const base = agentDirName(ctx && ctx.agentRoot);
332
+ if (base) res.push(new RegExp("~\\/" + escapeRe(base) + "\\/" + PATH_TAIL, "g"));
333
+ const out = [];
334
+ for (const re of res) {
335
+ let m;
336
+ while ((m = re.exec(text)) !== null) {
337
+ const match = trimSpan(m[0]);
338
+ if (match) out.push({ match, index: m.index });
339
+ }
340
+ }
341
+ return out;
342
+ },
343
+ }),
344
+ // An absolute path on THIS machine: a macOS user home, a mounted volume, the
345
+ // per-user temp tree. Not `/tmp/…` or `/home/…`, which in an engineering post
346
+ // are almost always a container's paths and mean the same thing on every box.
347
+ // The lookbehind keeps a URL path (`github.com/Users/…`) and a product path
348
+ // segment from matching; `file:///Users/…` still matches.
349
+ regexRule(
350
+ "absolute-machine-path",
351
+ "path",
352
+ new RegExp("(?<![\\w.-])\\/(?:Users|Volumes|private\\/(?:var|tmp|etc)|var\\/folders)\\/" + PATH_TAIL),
353
+ HINT_PATH,
354
+ ),
355
+ regexRule(
356
+ "queue-item-id",
357
+ "id",
358
+ /\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]+)+/,
359
+ HINT_ID,
360
+ ),
361
+ // The queue files themselves, named bare — a backup or a "last row in…". As a
362
+ // path (`state/queues/…`) they are already `agent-state-path`, so this one
363
+ // only fires when the name stands alone. The list is `maestro init`'s queue
364
+ // scaffold (bin/maestro.mjs) plus the inbound queue.
365
+ regexRule(
366
+ "queue-file",
367
+ "path",
368
+ /(?<![\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/,
369
+ HINT_PATH,
370
+ ),
371
+ // Inbox and obligation handles: the inbound-queue id (`inb-<svc>.<kind>#n`),
372
+ // the obligation key (`cohort_<kind>_<cuid>_<n>`), the item reference
373
+ // (`cohort:<kind>:<cuid>:<n>`), an inbox file name, and the processed/deferred
374
+ // markers. A bare Cohort message id is NOT matched: people and clients use
375
+ // those as permalinks.
376
+ regexRule(
377
+ "inbox-item-ref",
378
+ "id",
379
+ /\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/,
380
+ HINT_ID,
381
+ ),
382
+ ]);
383
+
384
+ /**
385
+ * Every machine-leak match in `text`, ordered by position. Pure.
386
+ *
387
+ * @param {string} text
388
+ * @param {{rules?:ReadonlyArray<object>, agentRoot?:string}} [o]
389
+ * `rules` is the ablation seam (fallback-leak-corpus.test.mjs removes one
390
+ * rule at a time); `agentRoot` lets `agent-root-path` match `~/<dir>/…`.
391
+ * @returns {{rule:string, kind:string, match:string, index:number}[]}
392
+ */
393
+ export function findMachineLeaks(text, o = {}) {
394
+ const t = typeof text === "string" ? text : "";
395
+ if (!t) return [];
396
+ const rules = Array.isArray(o.rules) ? o.rules : MACHINE_LEAK_RULES;
397
+ const out = [];
398
+ const seen = new Set();
399
+ for (const rule of rules) {
400
+ for (const hit of rule.find(t, o)) {
401
+ const k = `${rule.id}@${hit.index}`;
402
+ if (seen.has(k)) continue;
403
+ seen.add(k);
404
+ out.push({ rule: rule.id, kind: rule.kind, match: hit.match, index: hit.index });
405
+ }
406
+ }
407
+ return out.sort((a, b) => a.index - b.index || a.rule.localeCompare(b.rule));
408
+ }
409
+
410
+ /** How many matches a refusal spells out before summarising the rest. */
411
+ const MACHINE_LEAK_REPORT_LIMIT = 10;
412
+
413
+ /**
414
+ * The refusal for a body carrying machine internals, or null. Pure.
415
+ *
416
+ * LOUD BY CONSTRUCTION: the reason names every rule and quotes every span (up to
417
+ * {@link MACHINE_LEAK_REPORT_LIMIT}), so one refusal tells the sender everything
418
+ * to rewrite, and it says in words that nothing was sent and nothing was edited.
419
+ *
420
+ * @param {string} text
421
+ * @param {{agentRoot?:string}} [o]
422
+ * @returns {null|{reason:string, rule:string, match:string, matches:object[]}}
423
+ */
424
+ export function machineLeakVerdict(text, o = {}) {
425
+ const found = findMachineLeaks(text, o);
426
+ if (!found.length) return null;
427
+ const shown = found.slice(0, MACHINE_LEAK_REPORT_LIMIT);
428
+ const list = shown.map((m) => "rule \"" + m.rule + "\" matched \"" + m.match + "\"").join("; ");
429
+ const more = found.length > shown.length ? " (and " + (found.length - shown.length) + " more)" : "";
430
+ const hints = [];
431
+ for (const m of found) {
432
+ const r = MACHINE_LEAK_RULES.find((x) => x.id === m.rule);
433
+ if (r && !hints.includes(r.hint)) hints.push(r.hint);
434
+ }
435
+ return {
436
+ reason:
437
+ "machine internals in the outbound body — " + list + more + ". " +
438
+ "Nothing was sent and nothing was redacted: rewrite it in your own words and send again. " +
439
+ hints.join(" "),
440
+ rule: found[0].rule,
441
+ match: found[0].match,
442
+ matches: found.map(({ rule, kind, match, index }) => ({ rule, kind, match, index })),
443
+ };
444
+ }
134
445
  /* ──────────────────────── session-scaffold markers ───────────────────────── */
135
446
  // A raw model turn must never reach a person. On 5 and 20 September 2026, bodies
136
447
  // carrying `<user_message>`, a closing `</thinking>` and the responder's
@@ -793,6 +1104,14 @@ export async function screenOutbound({
793
1104
  const personaReason = screenPersona(text, personaContext(fs, agentRoot, { agentFirst, sessionNames }));
794
1105
  if (personaReason) return blocked(personaReason);
795
1106
 
1107
+ // (a3) Machine internals and the agent's own sessions — MACHINE_LEAK_RULES.
1108
+ // Pure, reads no file, so like the scaffold screen it has no fail
1109
+ // posture: it blocks for internal recipients too, because every
1110
+ // recorded leak of this kind went to an internal channel with people
1111
+ // in it. The verdict carries the rule and the span for the sender.
1112
+ const leak = machineLeakVerdict(text, { agentRoot });
1113
+ if (leak) return blocked(leak.reason, { rule: leak.rule, match: leak.match, matches: leak.matches });
1114
+
796
1115
  // (b) AI-disclosure. The truthfulness invariant is enforced from the
797
1116
  // embedded denial list even without the file; posture resolution needs
798
1117
  // the file. Missing file → invariant still runs; posture defaults apply.
@@ -1090,9 +1409,10 @@ export function hookAllowlistMatch(recipient, allowlistText) {
1090
1409
  * @param {string} o.stdin the raw PreToolUse payload
1091
1410
  * @param {string[]} [o.sessionNames] from hookSessionNames
1092
1411
  * @param {null|{path:string, text:string|null}} [o.allowlist] null = not enforced; text null = unreadable
1412
+ * @param {string} [o.agentRoot] the agent root, so `agent-root-path` can match `~/<agent-dir>/…`
1093
1413
  * @returns {{allow:true, recipient:string}|{allow:false, reason:string}}
1094
1414
  */
1095
- export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist = null }) {
1415
+ export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist = null, agentRoot = "" }) {
1096
1416
  const deny = (reason) => ({ allow: false, reason });
1097
1417
  if (!channel) return deny(HOOK_CHANNEL_REQUIRED);
1098
1418
  const raw = shellCaptured(stdin == null ? "" : stdin);
@@ -1139,6 +1459,13 @@ export function screenHookPayload({ channel, stdin, sessionNames = [], allowlist
1139
1459
  const hit = hookSessionNameHit(text, name);
1140
1460
  if (hit) return deny(`Persona leak in outbound message: "${hit}" is an internal session name — say "my team" or "a colleague" instead`);
1141
1461
  }
1462
+ // (a3) Machine internals — the shared MACHINE_LEAK_RULES, as in screenOutbound.
1463
+ // Outside the parity contract by construction, like the scaffold screen: the
1464
+ // frozen shell oracle has no counterpart rule, so this is an ADDITION.
1465
+ const leak = machineLeakVerdict(text, { agentRoot });
1466
+ if (leak) {
1467
+ return { allow: false, reason: `Machine internals in outbound message: ${leak.reason}`, rule: leak.rule, match: leak.match, matches: leak.matches };
1468
+ }
1142
1469
  if (recipient && allowlist) {
1143
1470
  if (allowlist.text == null || !hookAllowlistMatch(recipient, allowlist.text)) {
1144
1471
  return deny(`Recipient "${recipient}" not on send allowlist (${allowlist.path})`);
@@ -1325,7 +1652,7 @@ export function preparePreSendHook({ channel, stdin, env = process.env, now = ne
1325
1652
  const allowPath = v("MAESTRO_SEND_ALLOWLIST");
1326
1653
  const allowlist = allowPath && isFile(allowPath) ? { path: allowPath, text: readIfFile(allowPath) } : null;
1327
1654
 
1328
- const screened = screenHookPayload({ channel, stdin, sessionNames, allowlist });
1655
+ const screened = screenHookPayload({ channel, stdin, sessionNames, allowlist, agentRoot: v("AGENT_ROOT") || v("AGENT_DIR") });
1329
1656
  if (!screened.allow) return refuse(screened.reason);
1330
1657
 
1331
1658
  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
  /**