@cohortapp/agent-sdk 2.5.1 → 2.6.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.
Files changed (106) hide show
  1. package/bin/maestro.mjs +185 -88
  2. package/bin/maestro.test.mjs +175 -48
  3. package/docs/runbooks/backup-restore.md +65 -33
  4. package/framework-features.json +4 -4
  5. package/lib/backup/policy.mjs +710 -0
  6. package/lib/backup/policy.test.mjs +305 -0
  7. package/lib/budget-escalate.mjs +133 -0
  8. package/lib/budget-escalate.test.mjs +232 -0
  9. package/lib/budget-guard.envelope.test.mjs +476 -0
  10. package/lib/budget-guard.mjs +853 -75
  11. package/lib/budget-guard.test.mjs +91 -42
  12. package/lib/cadences.mjs +33 -0
  13. package/lib/channels/orgmail/adapter.mjs +88 -3
  14. package/lib/channels/orgmail/adapter.test.mjs +137 -0
  15. package/lib/channels/repeat-suppressor.mjs +198 -0
  16. package/lib/channels/repeat-suppressor.test.mjs +134 -0
  17. package/lib/comms/receipts.mjs +297 -0
  18. package/lib/cost/ledger-row.mjs +333 -0
  19. package/lib/cost/ledger-row.test.mjs +183 -0
  20. package/lib/execution/drive.mjs +28 -1
  21. package/lib/execution/effects.mjs +191 -12
  22. package/lib/execution/effects.test.mjs +50 -11
  23. package/lib/goals/admission.mjs +13 -1
  24. package/lib/goals/admission.test.mjs +26 -1
  25. package/lib/goals/loop.mjs +13 -0
  26. package/lib/kpi-sensors.test.mjs +3 -0
  27. package/lib/mandate/cache.mjs +13 -5
  28. package/lib/mandate/derive.mjs +146 -21
  29. package/lib/mandate/derive.test.mjs +50 -6
  30. package/lib/mandate/model.mjs +32 -4
  31. package/lib/mandate/refresh.test.mjs +16 -2
  32. package/lib/mcp/server.test.mjs +12 -3
  33. package/lib/model-router/economics.mjs +107 -76
  34. package/lib/model-router/economics.test.mjs +64 -46
  35. package/lib/model-router/integration-coverage.test.mjs +39 -37
  36. package/lib/model-router/ledger.mjs +75 -22
  37. package/lib/model-router/ledger.test.mjs +35 -2
  38. package/lib/org/client.mjs +14 -0
  39. package/lib/org/cost-sync.mjs +16 -2
  40. package/lib/org/doctor.mjs +62 -1
  41. package/lib/org/doctor.test.mjs +36 -3
  42. package/lib/org/email-remedy.mjs +49 -0
  43. package/lib/org/engagement-ledger.mjs +376 -0
  44. package/lib/org/engagement-ledger.test.mjs +112 -0
  45. package/lib/org/engagement.mjs +1056 -0
  46. package/lib/org/engagement.test.mjs +739 -0
  47. package/lib/org/messaging.mjs +230 -3
  48. package/lib/org/messaging.test.mjs +110 -1
  49. package/lib/org/param-contract.mjs +56 -2
  50. package/lib/org/param-contract.test.mjs +26 -0
  51. package/lib/org/protocol.checksum +1 -1
  52. package/lib/org/protocol.mjs +5 -0
  53. package/lib/org/protocol.test.mjs +7 -1
  54. package/lib/org/tool-surface.mjs +506 -10
  55. package/lib/org/tool-surface.test.mjs +191 -7
  56. package/lib/org/ui-parity.mjs +333 -6
  57. package/lib/org/ui-parity.test.mjs +96 -3
  58. package/lib/org/work-ledger.mjs +241 -0
  59. package/lib/org/work-ledger.test.mjs +237 -0
  60. package/lib/plan/adoption-e2e.test.mjs +366 -0
  61. package/lib/plan/budget-enforcement.test.mjs +400 -0
  62. package/lib/plan/budget-runtime.mjs +215 -0
  63. package/lib/plan/compile.mjs +201 -5
  64. package/lib/plan/compile.test.mjs +19 -5
  65. package/lib/plan/emit.mjs +8 -0
  66. package/lib/plan/emit.test.mjs +18 -0
  67. package/lib/resource-governor.mjs +58 -12
  68. package/lib/resource-governor.test.mjs +41 -1
  69. package/lib/security/audit-engine.mjs +45 -8
  70. package/lib/security/audit-engine.test.mjs +35 -0
  71. package/lib/setup/enroll-from-cohort.mjs +14 -1
  72. package/lib/setup/sections/mandate.mjs +48 -7
  73. package/lib/setup/sections/mandate.test.mjs +17 -2
  74. package/lib/setup/sections/orgmail.mjs +10 -2
  75. package/lib/setup/state.mjs +83 -2
  76. package/lib/telemetry/collect.mjs +360 -20
  77. package/lib/telemetry/collect.test.mjs +266 -0
  78. package/package.json +1 -1
  79. package/scripts/cost/track-claude-usage.mjs +207 -48
  80. package/scripts/cost/track-claude-usage.test.mjs +148 -0
  81. package/scripts/daemon/agent-daemon.mjs +315 -17
  82. package/scripts/daemon/assurance-e2e.test.mjs +421 -0
  83. package/scripts/daemon/assurance.mjs +944 -0
  84. package/scripts/daemon/assurance.test.mjs +668 -0
  85. package/scripts/daemon/cadence-consumer-governance.test.mjs +56 -0
  86. package/scripts/daemon/cadence-consumer.mjs +147 -9
  87. package/scripts/daemon/cadence-consumer.test.mjs +6 -0
  88. package/scripts/daemon/cadence-handlers.mjs +158 -0
  89. package/scripts/daemon/cadence-handlers.test.mjs +64 -0
  90. package/scripts/daemon/deliver.mjs +314 -0
  91. package/scripts/daemon/dispatcher-governance.test.mjs +10 -0
  92. package/scripts/daemon/dispatcher.mjs +64 -6
  93. package/scripts/daemon/responder-cost.test.mjs +68 -0
  94. package/scripts/daemon/responder.mjs +351 -298
  95. package/scripts/local-triggers/generate-plists.test.mjs +7 -4
  96. package/scripts/maintenance/backup-run.mjs +415 -0
  97. package/scripts/maintenance/backup-to-cloud.sh +16 -116
  98. package/scripts/org/send-orgmail.mjs +16 -0
  99. package/scripts/record-receipt.sh +63 -0
  100. package/scripts/restore-from-backup.sh +14 -3
  101. package/scripts/restore-from-backup.test.mjs +8 -5
  102. package/scripts/send-email-threaded.py +47 -0
  103. package/scripts/send-sms.sh +4 -0
  104. package/scripts/send-whatsapp.sh +4 -0
  105. package/scripts/setup/init-backup.mjs +93 -38
  106. package/scripts/slack-send.sh +12 -0
@@ -0,0 +1,421 @@
1
+ /**
2
+ * assurance-e2e.test.mjs — the owner's four scenarios, end to end, through the
3
+ * REAL daemon.
4
+ *
5
+ * Run: node --test scripts/daemon/assurance-e2e.test.mjs
6
+ * Read the story: ASSURANCE_TRANSCRIPT=1 node --test scripts/daemon/assurance-e2e.test.mjs
7
+ *
8
+ * This drives `agent-daemon.processItem` itself — the real classifier gate, the
9
+ * real acknowledgement decision, the real obligation ledger, the real
10
+ * settle-on-close logic, the real sweep. Only the two things that would cost
11
+ * money or touch a live workspace are injected fakes:
12
+ *
13
+ * * `dispatch` — instead of spawning a `claude` child, the fake invokes
14
+ * `onClose` with the exit code the scenario is about.
15
+ * * transport — instead of posting to Cohort/Slack, it appends to a
16
+ * transcript so the test can assert on the exact words a
17
+ * human would read.
18
+ *
19
+ * NOTHING here posts to the live workspace, spawns a model, or writes to the
20
+ * database. The four scenarios are the four the brief names: a fast ask, a slow
21
+ * ask, a timing-out session, and a crashing session — plus the one the old code
22
+ * could not even detect, a session that exits 0 having said nothing.
23
+ */
24
+
25
+ import { test, before, after } from "node:test";
26
+ import assert from "node:assert/strict";
27
+ import { register } from "node:module";
28
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ import { tmpdir } from "node:os";
31
+
32
+ // The daemon statically pulls in the agent-only `imapflow` dep via the gmail
33
+ // poller; stub it so the real daemon module can be imported in CI.
34
+ const loaderSrc = `
35
+ export async function resolve(specifier, context, next) {
36
+ if (specifier === "imapflow") return { url: "imapflow-stub:main", shortCircuit: true };
37
+ return next(specifier, context);
38
+ }
39
+ export async function load(url, context, next) {
40
+ if (url === "imapflow-stub:main") return { format: "module", shortCircuit: true, source: "export class ImapFlow {}" };
41
+ return next(url, context);
42
+ }
43
+ `;
44
+ register(`data:text/javascript,${encodeURIComponent(loaderSrc)}`);
45
+
46
+ const AGENT_DIR = mkdtempSync(join(tmpdir(), "maestro-assurance-e2e-"));
47
+ process.env.AGENT_DIR = AGENT_DIR;
48
+ process.env.AGENT_ROOT = AGENT_DIR;
49
+ process.env.MAESTRO_DAEMON_NO_AUTOSTART = "1";
50
+
51
+ let daemon, assurance, receipts;
52
+
53
+ before(async () => {
54
+ mkdirSync(join(AGENT_DIR, "state", "inbox", "cohort"), { recursive: true });
55
+ mkdirSync(join(AGENT_DIR, "state", "sessions", "locks"), { recursive: true });
56
+ daemon = await import("./agent-daemon.mjs");
57
+ assurance = await import("./assurance.mjs");
58
+ receipts = await import("../../lib/comms/receipts.mjs");
59
+ });
60
+
61
+ after(() => { try { rmSync(AGENT_DIR, { recursive: true, force: true }); } catch { /* */ } });
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Transcript: what the human sees, and when
65
+ // ---------------------------------------------------------------------------
66
+
67
+ const SHOW = process.env.ASSURANCE_TRANSCRIPT === "1";
68
+ let transcript = [];
69
+ let t0 = 0;
70
+
71
+ function beginScenario(title, ask) {
72
+ transcript = [];
73
+ t0 = Date.now();
74
+ if (SHOW) {
75
+ console.log(`\n${"═".repeat(78)}\n ${title}\n${"═".repeat(78)}`);
76
+ console.log(` [ 0.00s] OWNER → ${ask}`);
77
+ }
78
+ }
79
+
80
+ /** Record a message the human would receive, at a stated virtual offset. */
81
+ function heard(kind, text, virtualMs = null) {
82
+ const realMs = Date.now() - t0;
83
+ transcript.push({ kind, text, ms: realMs, virtualMs });
84
+ if (SHOW) {
85
+ const stamp = virtualMs != null
86
+ ? `+${(virtualMs / 60000).toFixed(1)}min`
87
+ : `${(realMs / 1000).toFixed(2)}s`;
88
+ console.log(` [${String(stamp).padStart(8)}] ISLA → ${text.replace(/\n/g, "\n ")}`);
89
+ }
90
+ }
91
+
92
+ function note(text, virtualMs = null) {
93
+ if (!SHOW) return;
94
+ const stamp = virtualMs != null ? `+${(virtualMs / 60000).toFixed(1)}min` : `${((Date.now() - t0) / 1000).toFixed(2)}s`;
95
+ console.log(` [${String(stamp).padStart(8)}] ····· (${text})`);
96
+ }
97
+
98
+ /** A transport fake that feeds the transcript. Never touches a network. */
99
+ function transport(virtualClock = () => null) {
100
+ return async (item, text, o = {}) => {
101
+ heard(o.kind || "reply", text, virtualClock());
102
+ return { sent: true, via: "fake", channel: item.channel_id || item.channel };
103
+ };
104
+ }
105
+
106
+ /** The daemon's ack seam, shaped exactly like responder.sendHoldingMessage. */
107
+ function ackSeam() {
108
+ return async (item, classResult) => {
109
+ const text = assurance.composeAck(item, classResult);
110
+ heard("ack", text);
111
+ return { sent: true, holdingText: text, via: "fake" };
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Each scenario gets its OWN channel id. The daemon's per-thread lock and
117
+ * request-claim would otherwise (correctly) suppress the second and subsequent
118
+ * asks as duplicates of a conversation already in flight — real behaviour, but
119
+ * orthogonal to what these scenarios are proving.
120
+ */
121
+ function makeItem(id, content) {
122
+ const channelId = `CDM-${id}`;
123
+ const item = {
124
+ id,
125
+ raw_ref: `cohort:${channelId}:${id}`,
126
+ message_id: id,
127
+ service: "cohort",
128
+ channel: "dm/owner",
129
+ channel_id: channelId,
130
+ is_dm: true,
131
+ sender: "the owner",
132
+ content,
133
+ };
134
+ // The poll filter expects a live inbox file for markProcessed to act on.
135
+ writeFileSync(join(AGENT_DIR, "state", "inbox", "cohort", `${id}.yaml`), `id: ${id}\n`);
136
+ return item;
137
+ }
138
+
139
+ const COMPLEX = {
140
+ priority: "critical", action: "respond", model: "opus", category: "action_required",
141
+ directed_at_agent: true, summary: "Fix the issues you just noted and push the fixes to git",
142
+ };
143
+
144
+ // ===========================================================================
145
+ // SCENARIO 1 — A FAST ASK. Answered directly. No "let me look into it".
146
+ // ===========================================================================
147
+
148
+ test("SCENARIO 1 — a fast ask gets a direct answer, with no pointless holding message", async () => {
149
+ const ask = "what time is the board call on Thursday?";
150
+ beginScenario("SCENARIO 1 — FAST ASK", ask);
151
+ const item = makeItem("FAST-1", ask);
152
+
153
+ let holdingCalls = 0;
154
+ await daemon.processItem(item, "cohort", {
155
+ classify: async () => ({ priority: "normal", action: "respond", model: "sonnet", category: "question", directed_at_agent: true, summary: "board call time" }),
156
+ isQuickReply: () => true,
157
+ sendQuickResponse: async (it) => {
158
+ heard("reply", "Thursday's board call is at 14:00 UK — calendar invite went out last week.");
159
+ return { sent: true, text: "…", channel: it.channel_id };
160
+ },
161
+ sendHoldingMessage: async () => { holdingCalls++; return { sent: true, holdingText: "x" }; },
162
+ dispatch: () => { throw new Error("a fast ask must not spawn a session"); },
163
+ });
164
+
165
+ assert.equal(holdingCalls, 0, "a simple ask must NOT be told 'I'll look into it' before its answer");
166
+ assert.equal(transcript.length, 1, "exactly one message: the answer");
167
+ assert.equal(transcript[0].kind, "reply");
168
+ assert.ok(transcript[0].ms < 1000, `answered in ${transcript[0].ms}ms`);
169
+ assert.equal(assurance.openObligations().length, 0, "nothing is owed — the ask is already discharged");
170
+ note("no obligation opened: the answer already went out");
171
+ });
172
+
173
+ // ===========================================================================
174
+ // SCENARIO 2 — A SLOW ASK. Acknowledged in milliseconds, updated, then answered.
175
+ // ===========================================================================
176
+
177
+ test("SCENARIO 2 — a slow ask is acknowledged at once, updated while it runs, then answered", async () => {
178
+ const ask = "with that in mind, fix these issues you just noted please and push their fixes to git";
179
+ beginScenario("SCENARIO 2 — SLOW ASK (the owner's actual message)", ask);
180
+ const item = makeItem("SLOW-1", ask);
181
+
182
+ let onCloseHook = null;
183
+ await daemon.processItem(item, "cohort", {
184
+ classify: async () => COMPLEX,
185
+ isQuickReply: () => false,
186
+ sendHoldingMessage: ackSeam(),
187
+ dispatch: (_p, _it, _cr, _s, opts) => { onCloseHook = opts.onClose; },
188
+ });
189
+
190
+ const ack = transcript.find((m) => m.kind === "ack");
191
+ assert.ok(ack, "the acknowledgement must go out");
192
+ assert.ok(ack.ms < 1000, `acknowledged in ${ack.ms}ms — the old path budgeted 60,000ms and missed 2 times in 3`);
193
+ assert.match(ack.text, /either way/i);
194
+
195
+ const key = assurance.openObligations()[0].key;
196
+ note("obligation opened and acknowledged; session running");
197
+
198
+ // ── 6 minutes later: still working. The sweep speaks rather than let the
199
+ // human sit behind a typing indicator wondering.
200
+ let virtual = 6 * 60_000;
201
+ const clock = () => virtual;
202
+ const deps = { deliverImpl: transport(clock), spokeSinceImpl: () => false };
203
+ let stats = await assurance.sweepObligations({ now: Date.now() + virtual, deps });
204
+ assert.equal(stats.progressed, 1, "long work must produce an interim update");
205
+
206
+ // ── 17 minutes: the session finally answers the human itself.
207
+ virtual = 17 * 60_000;
208
+ receipts.recordOutbound({ service: "cohort", channel: "CDM-SLOW-1", kind: "session", via: "messaging_send", agentRoot: AGENT_DIR });
209
+ heard("reply", "Done — all three issues fixed and pushed (commit a41f0c9). The flaky test was a race in the poller; I've pinned it and re-run CI twice, green both times.", virtual);
210
+ onCloseHook({ ok: true, code: 0, sessionId: "s-e2e-2", stdout: "" });
211
+ await new Promise((r) => setImmediate(r));
212
+
213
+ const rec = assurance.readObligation(key);
214
+ assert.equal(rec.state, "answered", "the debt is discharged by evidence of a delivered reply");
215
+ const progress = transcript.filter((m) => m.kind === "progress");
216
+ assert.equal(progress.length, 1);
217
+ assert.equal(transcript.filter((m) => m.kind === "ack").length, 1, "acknowledge once, never twice");
218
+ note("obligation discharged by receipt — the daemon added nothing on top of the session's own answer", virtual);
219
+ });
220
+
221
+ // ===========================================================================
222
+ // SCENARIO 3 — A TIMING-OUT SESSION. SIGTERM at the 45-minute cap.
223
+ // ===========================================================================
224
+
225
+ test("SCENARIO 3 — a timing-out session tells the human what happened and that a retry is running", async () => {
226
+ const ask = "can you reconcile the July spend against the forecast and tell me where we're over?";
227
+ beginScenario("SCENARIO 3 — SESSION TIMES OUT (exit 143 / SIGTERM)", ask);
228
+ const item = makeItem("TIMEOUT-1", ask);
229
+
230
+ let onCloseHook = null;
231
+ await daemon.processItem(item, "cohort", {
232
+ classify: async () => ({ ...COMPLEX, summary: "Reconcile July spend against forecast" }),
233
+ isQuickReply: () => false,
234
+ sendHoldingMessage: ackSeam(),
235
+ dispatch: (_p, _it, _cr, _s, opts) => { onCloseHook = opts.onClose; },
236
+ });
237
+ const key = assurance.openObligations().find((o) => o.key === item.raw_ref).key;
238
+ assert.ok(transcript.find((m) => m.kind === "ack"));
239
+
240
+ // 45 minutes in, the dispatcher's SIGTERM lands and the session closes 143.
241
+ const virtual = { v: 45 * 60_000 };
242
+ const r = await assurance.settleSession({
243
+ key, ok: false, code: 143, error: "session_close exit 143", sessionId: "s-e2e-3",
244
+ deps: { deliverImpl: transport(() => virtual.v), spokeSinceImpl: () => false },
245
+ });
246
+
247
+ assert.equal(r.willRetry, true, "a timeout is transient — it earns one retry");
248
+ const failure = transcript.filter((m) => m.kind === "failure").at(-1);
249
+ assert.ok(failure, "the human MUST be told; the old code emitted telemetry and nothing else");
250
+ assert.match(failure.text, /ran past its time limit/i);
251
+ assert.match(failure.text, /retrying it now/i);
252
+ assert.equal(assurance.readObligation(key).state, "open", "still owed until the retry resolves");
253
+ note("item left un-processed for redelivery; the debt stays open so the retry is covered too", virtual.v);
254
+ });
255
+
256
+ // ===========================================================================
257
+ // SCENARIO 4 — A CRASHING SESSION. Nothing to retry; say so and escalate.
258
+ // ===========================================================================
259
+
260
+ test("SCENARIO 4 — a crashing session tells the human it failed, stops, and escalates", async () => {
261
+ const ask = "pull the Q3 pipeline and draft the investor update";
262
+ beginScenario("SCENARIO 4 — SESSION CRASHES (unrecoverable)", ask);
263
+ const item = makeItem("CRASH-1", ask);
264
+
265
+ let onCloseHook = null;
266
+ await daemon.processItem(item, "cohort", {
267
+ classify: async () => ({ ...COMPLEX, summary: "Draft the Q3 investor update" }),
268
+ isQuickReply: () => false,
269
+ sendHoldingMessage: ackSeam(),
270
+ dispatch: (_p, _it, _cr, _s, opts) => { onCloseHook = opts.onClose; },
271
+ });
272
+ const key = item.raw_ref;
273
+
274
+ const r = await assurance.settleSession({
275
+ key, ok: false, code: 1, error: "claude CLI spawn error: ENOENT", sessionId: "s-e2e-4",
276
+ deps: { deliverImpl: transport(() => 90_000), spokeSinceImpl: () => false },
277
+ });
278
+
279
+ assert.equal(r.willRetry, false, "a spawn failure is permanent — retrying burns another 45 minutes for the same outcome");
280
+ const failure = transcript.filter((m) => m.kind === "failure").at(-1);
281
+ assert.match(failure.text, /couldn't get this done/i);
282
+ assert.match(failure.text, /stopped retrying/i);
283
+ assert.match(failure.text, /flagged it so it isn't lost/i);
284
+ assert.match(failure.text, /\?\s*$/, "a dead end ends in a question, so the human has a move");
285
+ assert.equal(assurance.readObligation(key).state, "failed");
286
+ note("durable needs-attention record written to state/obligations/needs-attention/", 90_000);
287
+ });
288
+
289
+ // ===========================================================================
290
+ // SCENARIO 5 — EXIT ZERO, NOTHING SAID. The silent death the old code called
291
+ // a success, marked processed forever, and emitted as `sent`.
292
+ // ===========================================================================
293
+
294
+ test("SCENARIO 5 — a session that exits 0 without replying no longer passes as a success", async () => {
295
+ const ask = "did the migration land cleanly?";
296
+ beginScenario("SCENARIO 5 — SESSION EXITS 0 HAVING SAID NOTHING", ask);
297
+ const item = makeItem("SILENT-1", ask);
298
+
299
+ let onCloseHook = null;
300
+ await daemon.processItem(item, "cohort", {
301
+ classify: async () => ({ ...COMPLEX, summary: "Check whether the migration landed cleanly" }),
302
+ isQuickReply: () => false,
303
+ sendHoldingMessage: ackSeam(),
304
+ dispatch: (_p, _it, _cr, _s, opts) => { onCloseHook = opts.onClose; },
305
+ });
306
+ const key = item.raw_ref;
307
+
308
+ // The real shape: exit 0, real work done, final text admitting nothing was sent.
309
+ const stdout = JSON.stringify({
310
+ type: "result",
311
+ result: "Checked the migration: it applied cleanly on the primary, but the read replica is 4 minutes behind and still catching up. No action needed unless it stalls. Nothing was sent.",
312
+ });
313
+ const r = await assurance.settleSession({
314
+ key, ok: true, code: 0, stdout, sessionId: "s-e2e-5",
315
+ deps: { deliverImpl: transport(() => 4 * 60_000), spokeSinceImpl: () => false },
316
+ });
317
+
318
+ assert.equal(r.verdict, "silent-success");
319
+ const rescued = transcript.at(-1);
320
+ assert.match(rescued.text, /didn't get a reply out to you/i);
321
+ assert.match(rescued.text, /read replica is 4 minutes behind/, "the work the session actually did reaches the human");
322
+ note("previously: marked processed, emitted `sent`, human heard nothing — forever", 4 * 60_000);
323
+ });
324
+
325
+ // ===========================================================================
326
+ // SCENARIO 6 — THE DAEMON ITSELF DIES MID-SESSION.
327
+ // ===========================================================================
328
+
329
+ test("SCENARIO 6 — a debt orphaned by a daemon restart is spoken to on the next start", async () => {
330
+ const ask = "sort out the DNS on the staging domain";
331
+ beginScenario("SCENARIO 6 — THE DAEMON DIES MID-SESSION", ask);
332
+ const item = makeItem("ORPHAN-1", ask);
333
+
334
+ await daemon.processItem(item, "cohort", {
335
+ classify: async () => ({ ...COMPLEX, summary: "Fix DNS on the staging domain" }),
336
+ isQuickReply: () => false,
337
+ sendHoldingMessage: ackSeam(),
338
+ dispatch: () => { /* the daemon dies here — onClose is never called */ },
339
+ });
340
+
341
+ // Rewrite the record as a previous process's, exactly as a restart would find it.
342
+ const rec = assurance.readObligation(item.raw_ref);
343
+ rec.daemonPid = process.pid + 12345;
344
+ writeFileSync(join(AGENT_DIR, "state", "obligations", `${assurance.sanitiseKey(item.raw_ref)}.json`), JSON.stringify(rec));
345
+ note("daemon process dies; obligation file survives on disk");
346
+
347
+ // The sweep must PROVE the owning process is gone before it says this — a bare
348
+ // pid mismatch is also what a second daemon on the same AGENT_DIR looks like,
349
+ // and telling a requester their running work was interrupted is its own bug.
350
+ const stats = await assurance.sweepObligations({
351
+ now: Date.now() + assurance.INTERRUPT_GRACE_MS + 30_000,
352
+ deps: { deliverImpl: transport(() => 30_000), spokeSinceImpl: () => false, isPidAliveImpl: () => false },
353
+ });
354
+ assert.equal(stats.interrupted, 1);
355
+ assert.match(transcript.at(-1).text, /was interrupted before it finished/i);
356
+ note("previously: the typing dot stopped and that was the last the human ever heard", 30_000);
357
+ });
358
+
359
+ // ===========================================================================
360
+ // SCENARIO 7 — TWO ASKS, ONE ROOM. The owner sends a second thing before the
361
+ // first is done. One session answers; the other exits 0 in silence.
362
+ // ===========================================================================
363
+
364
+ test("SCENARIO 7 — a second ask in the same DM is not discharged by the first one's answer", async () => {
365
+ const askA = "what's our runway at the current burn?";
366
+ const askB = "also please fix the flaky poller test and push it";
367
+ beginScenario("SCENARIO 7 — TWO ASKS IN ONE DM", `${askA}\n [ 0.00s] OWNER → ${askB}`);
368
+
369
+ // ONE room, two messages — which is simply what a DM with the owner is.
370
+ const room = "CDM-BOTH";
371
+ const mk = (id, content) => {
372
+ const item = {
373
+ id, raw_ref: `cohort:${room}:${id}`, message_id: id, service: "cohort",
374
+ channel: "dm/owner", channel_id: room, is_dm: true, sender: "the owner", content,
375
+ };
376
+ writeFileSync(join(AGENT_DIR, "state", "inbox", "cohort", `${id}.yaml`), `id: ${id}\n`);
377
+ return item;
378
+ };
379
+ const a = mk("BOTH-A", askA);
380
+ const b = mk("BOTH-B", askB);
381
+
382
+ const openA = await assurance.openAndAcknowledge({
383
+ item: a, classResult: { ...COMPLEX, summary: "work out the runway" },
384
+ deps: { ackSender: ackSeam() },
385
+ });
386
+ const openB = await assurance.openAndAcknowledge({
387
+ item: b, classResult: { ...COMPLEX, summary: "fix the flaky poller test" },
388
+ deps: { ackSender: ackSeam() },
389
+ });
390
+ assurance.noteSession(openA.key, "s-both-A");
391
+ assurance.noteSession(openB.key, "s-both-B");
392
+ note("two debts open, one room");
393
+
394
+ // Session A answers, through the CLI lane, stamped with the debt it was
395
+ // spawned for — exactly what the dispatcher's env now makes possible.
396
+ receipts.recordOutbound({
397
+ service: "cohort", channel: room, kind: "session", via: "slack-send.sh",
398
+ obligationKey: openA.key, sessionId: "s-both-A", agentRoot: AGENT_DIR,
399
+ });
400
+ heard("reply", "Runway is 14 months at the current burn — the July infra overage is the only thing moving it.", 8 * 60_000);
401
+
402
+ const settledA = await assurance.settleSession({
403
+ key: openA.key, ok: true, code: 0, sessionId: "s-both-A",
404
+ deps: { deliverImpl: transport(() => 8 * 60_000) },
405
+ });
406
+ assert.equal(settledA.verdict, "answered-by-session");
407
+ assert.equal(settledA.basis, "obligation-keyed", "the receipt names the debt it discharged");
408
+
409
+ // Session B exits 0 having said NOTHING. Keyed on the room alone — which is
410
+ // what shipped — A's receipt closed B too, and this ask vanished in silence.
411
+ const settledB = await assurance.settleSession({
412
+ key: openB.key, ok: true, code: 0, sessionId: "s-both-B",
413
+ stdout: JSON.stringify({ type: "result", result: "The flake is a race between the poller's lock release and the next tick. I've pinned the ordering but not pushed it yet." }),
414
+ deps: { deliverImpl: transport(() => 9 * 60_000) },
415
+ });
416
+ assert.equal(settledB.verdict, "silent-success", "the unanswered ask must NOT ride on the other one's receipt");
417
+ const rescue = transcript.at(-1);
418
+ assert.match(rescue.text, /didn't get a reply out to you/i);
419
+ assert.match(rescue.text, /race between the poller's lock release/, "and B's actual work reaches the human");
420
+ note("previously: B closed as `answered` on A's receipt — zero messages, ask gone");
421
+ });