@cohortapp/agent-sdk 2.9.1 → 2.10.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.
@@ -0,0 +1,564 @@
1
+ /**
2
+ * deliver.test.mjs — node:test coverage for the Cohort reply CHOKEPOINT.
3
+ *
4
+ * These pin the `task/<title>` regression: a board comment used to be answered
5
+ * by calling `messaging.send({channel: "task/Roll out tier-3 guardrails…"})`,
6
+ * because `sendCohortReply` fell back to `item.channel` — the human LABEL —
7
+ * when the surface had no room. hq resolved that to nothing, threw NOT_FOUND,
8
+ * and the daemon retried the impossible send three times a sweep forever.
9
+ *
10
+ * What is pinned here:
11
+ * 1. a board item routes to board.addTaskComment with the REAL task id;
12
+ * 2. a room item still routes to messaging.send, unchanged;
13
+ * 3. an unaddressable item (approval) fails explicitly and PERMANENTLY;
14
+ * 4. no route, on any surface, is ever derived from `item.channel`.
15
+ *
16
+ * Hermetic: the transport is stubbed at both seams (`callImpl` for entity
17
+ * threads, `sendMessageImpl` for rooms), the send-gate is stubbed, and
18
+ * AGENT_DIR is pointed at a scratch dir BEFORE the module loads so the receipt
19
+ * writer never touches the real agent state.
20
+ */
21
+
22
+ import { test } from "node:test";
23
+ import assert from "node:assert/strict";
24
+ import { mkdtempSync, rmSync } from "node:fs";
25
+ import { tmpdir } from "node:os";
26
+ import { join } from "node:path";
27
+
28
+ // Must be set before the module is evaluated — AGENT_REPO_DIR is a load-time
29
+ // constant and it is where receipts land.
30
+ const SCRATCH = mkdtempSync(join(tmpdir(), "deliver-test-"));
31
+ process.env.AGENT_DIR = SCRATCH;
32
+ process.on("exit", () => { try { rmSync(SCRATCH, { recursive: true, force: true }); } catch { /* best effort */ } });
33
+
34
+ const {
35
+ deliver,
36
+ deliverWithRetry,
37
+ cohortReplyRoute,
38
+ cohortSurfaceOf,
39
+ replyTargetOf,
40
+ canDeliverTo,
41
+ } = await import("./deliver.mjs");
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Fixtures — the real on-disk shapes, taken from live inbox items.
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /** A board comment. Note `channel_id` is blank and `channel` is a TITLE. */
48
+ const TASK_ITEM = Object.freeze({
49
+ service: "cohort",
50
+ kind: "task_comment",
51
+ channel: "task/Roll out tier-3 guardrails to agents with financial-action scopes",
52
+ channel_id: "",
53
+ thread_id: "cmrlw2l3600e9hh8n10hprdrd",
54
+ scope_id: "cmrlw2l3600e9hh8n10hprdrd",
55
+ raw_ref: "cohort:task_comment:cmrlw2l3600e9hh8n10hprdrd:25029",
56
+ id: "25029",
57
+ });
58
+
59
+ /** An ordinary room message. */
60
+ const DM_ITEM = Object.freeze({
61
+ service: "cohort",
62
+ channel: "#eng",
63
+ channel_id: "cmql1802601iihhzpf774vwbk",
64
+ thread_id: "",
65
+ raw_ref: "cohort:dm:cmsnbgwsz003flj014spp4i1z:812",
66
+ id: "cmsnbgwsz003flj014spp4i1z",
67
+ });
68
+
69
+ /** An approval — a verdict surface, with no prose thread to write into. */
70
+ const APPROVAL_ITEM = Object.freeze({
71
+ service: "cohort",
72
+ kind: "approval",
73
+ channel: "approval/journey",
74
+ channel_id: "",
75
+ thread_id: "aprv_journey_msopegu4",
76
+ scope_id: "cmrlw2l3600e9hh8n10hprdrd",
77
+ raw_ref: "cohort:approval:aprv_journey_msopegu4:13546",
78
+ id: "13546",
79
+ });
80
+
81
+ const OK_GATE = () => ({ allow: true });
82
+ const CFG = { org: { cohort: { enabled: true, base: "https://hq.example", token: "t" } } };
83
+
84
+ /** A stubbed org RPC that records what it was asked to do. */
85
+ function recordingCall(frame = { ok: true, result: { id: "c1" } }) {
86
+ const calls = [];
87
+ const fn = async (method, params, o) => { calls.push({ method, params, o }); return frame; };
88
+ fn.calls = calls;
89
+ return fn;
90
+ }
91
+
92
+ /** A stubbed messaging.send. */
93
+ function recordingSend(frame = { ok: true, result: { id: "m1" } }) {
94
+ const calls = [];
95
+ const fn = async (params, o) => { calls.push({ params, o }); return frame; };
96
+ fn.calls = calls;
97
+ return fn;
98
+ }
99
+
100
+ /**
101
+ * Both seams at once, so "did it use the OTHER transport" is always assertable.
102
+ *
103
+ * `ledgerImpl: null` is the documented opt-out in `lib/org/messaging.mjs` —
104
+ * a delivered entity comment now writes a cost-attribution row, and a unit test
105
+ * must not put one on disk.
106
+ */
107
+ function seams(o = {}) {
108
+ const callImpl = recordingCall(o.callFrame);
109
+ const sendMessageImpl = recordingSend(o.sendFrame);
110
+ return { callImpl, sendMessageImpl, gateImpl: OK_GATE, cfg: CFG, ledgerImpl: null };
111
+ }
112
+
113
+ // ---------------------------------------------------------------------------
114
+ // (1) A board item is answered ON THE BOARD.
115
+ // ---------------------------------------------------------------------------
116
+
117
+ test("task_comment routes to board.addTaskComment with the real task id", async () => {
118
+ const s = seams();
119
+ const r = await deliver(TASK_ITEM, "On it — the guardrail rollout is unblocked.", { kind: "reply", ...s });
120
+
121
+ assert.equal(r.sent, true, `expected sent, got ${JSON.stringify(r)}`);
122
+ assert.equal(r.via, "board.addTaskComment");
123
+ assert.equal(r.channel, "task:cmrlw2l3600e9hh8n10hprdrd");
124
+
125
+ assert.equal(s.sendMessageImpl.calls.length, 0, "a board comment must NOT go through messaging.send");
126
+ assert.equal(s.callImpl.calls.length, 1);
127
+ const [c] = s.callImpl.calls;
128
+ assert.equal(c.method, "board.addTaskComment");
129
+ // `kind:"agent"`, not "human": hq renders a "human" task comment as the
130
+ // VIEWER'S OWN bubble with no AI avatar (`components/board/task-conversation
131
+ // .tsx`), so the daemon's reply used to arrive looking like something the
132
+ // reading human had written themselves.
133
+ assert.deepEqual(c.params, {
134
+ taskId: "cmrlw2l3600e9hh8n10hprdrd",
135
+ kind: "agent",
136
+ body: "On it — the guardrail rollout is unblocked.",
137
+ });
138
+ // The whole point: the TITLE never reaches the wire.
139
+ assert.ok(!JSON.stringify(c.params).includes("task/"), "the channel label leaked into the RPC params");
140
+ });
141
+
142
+ test("the ACK path benefits too — one chokepoint, so deliverWithRetry lands on the board as well", async () => {
143
+ const s = seams();
144
+ const r = await deliverWithRetry(TASK_ITEM, "On it — looking now.", { kind: "ack", ...s, sleep: async () => {} });
145
+ assert.equal(r.sent, true);
146
+ assert.equal(r.attempts, 1);
147
+ assert.equal(s.callImpl.calls.length, 1);
148
+ assert.equal(s.callImpl.calls[0].method, "board.addTaskComment");
149
+ assert.equal(s.callImpl.calls[0].params.taskId, "cmrlw2l3600e9hh8n10hprdrd");
150
+ // The ack and the eventual answer must not collide on hq's dedup.
151
+ assert.equal(s.callImpl.calls[0].o.idempotencyKey, "reply-25029-ack");
152
+ });
153
+
154
+ test("task_assigned routes to the board too, and prefers the id over any label", () => {
155
+ const route = cohortReplyRoute({ ...TASK_ITEM, kind: "task_assigned", raw_ref: "cohort:task_assigned:T-9:1", scope_id: "T-9", thread_id: "T-9" });
156
+ assert.equal(route.transport, "rpc");
157
+ assert.equal(route.method, "board.addTaskComment");
158
+ assert.equal(route.params.taskId, "T-9");
159
+ });
160
+
161
+ test("doc_comment routes to files.commentAdd; decision routes to decision.comment (param `text`, not `body`)", async () => {
162
+ const doc = { service: "cohort", kind: "file_comment", channel: "doc/CHARTER.pdf", channel_id: "", thread_id: "cmsu0pbez00m7lx01u6mbqk9g", scope_id: "cmsu0pbez00m7lx01u6mbqk9g", raw_ref: "cohort:doc_comment:cmsu0pbez00m7lx01u6mbqk9g:27088" };
163
+ const s1 = seams();
164
+ const r1 = await deliver(doc, "Section 3 reads fine to me.", { ...s1 });
165
+ assert.equal(r1.sent, true);
166
+ assert.equal(s1.callImpl.calls[0].method, "files.commentAdd");
167
+ assert.deepEqual(s1.callImpl.calls[0].params, { fileId: "cmsu0pbez00m7lx01u6mbqk9g", body: "Section 3 reads fine to me." });
168
+
169
+ const dec = { service: "cohort", kind: "decision", channel: "decision/Adopt tier-3", channel_id: "", thread_id: "D-1", scope_id: "D-1", raw_ref: "cohort:decision:D-1:9" };
170
+ const s2 = seams();
171
+ const r2 = await deliver(dec, "Signed.", { ...s2 });
172
+ assert.equal(r2.sent, true);
173
+ assert.equal(s2.callImpl.calls[0].method, "decision.comment");
174
+ assert.deepEqual(s2.callImpl.calls[0].params, { decisionId: "D-1", text: "Signed." });
175
+ });
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // (2) A room item is unchanged.
179
+ // ---------------------------------------------------------------------------
180
+
181
+ test("a normal channel item still routes to messaging.send, unchanged", async () => {
182
+ const s = seams();
183
+ const r = await deliver(DM_ITEM, "hello", { kind: "reply", ...s });
184
+
185
+ assert.equal(r.sent, true);
186
+ assert.equal(r.via, "cohort");
187
+ assert.equal(r.channel, "cmql1802601iihhzpf774vwbk");
188
+
189
+ assert.equal(s.callImpl.calls.length, 0, "a room message must NOT go through an entity comment method");
190
+ assert.equal(s.sendMessageImpl.calls.length, 1);
191
+ const [c] = s.sendMessageImpl.calls;
192
+ assert.equal(c.params.channel, "cmql1802601iihhzpf774vwbk");
193
+ assert.equal(c.params.body, "hello");
194
+ assert.equal(c.params.idempotencyId, "reply-cmsnbgwsz003flj014spp4i1z");
195
+ });
196
+
197
+ test("ack and reply on the same room item get distinct idempotency ids", async () => {
198
+ const s = seams();
199
+ await deliver(DM_ITEM, "on it", { kind: "ack", ...s });
200
+ await deliver(DM_ITEM, "here you go", { kind: "reply", ...s });
201
+ assert.deepEqual(
202
+ s.sendMessageImpl.calls.map((c) => c.params.idempotencyId),
203
+ ["reply-cmsnbgwsz003flj014spp4i1z-ack", "reply-cmsnbgwsz003flj014spp4i1z"],
204
+ );
205
+ });
206
+
207
+ test("a room surface with no channel_id is undeliverable — it does not fall back to the label", async () => {
208
+ const orphan = { ...DM_ITEM, channel_id: "" };
209
+ assert.equal(replyTargetOf(orphan), null);
210
+ assert.equal(canDeliverTo(orphan), false);
211
+ const s = seams();
212
+ const r = await deliver(orphan, "hello", { ...s });
213
+ assert.equal(r.sent, false);
214
+ assert.equal(r.permanent, true);
215
+ assert.equal(s.sendMessageImpl.calls.length, 0);
216
+ assert.equal(s.callImpl.calls.length, 0);
217
+ });
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // (3) An unaddressable item fails loudly, and does not retry.
221
+ // ---------------------------------------------------------------------------
222
+
223
+ test("an approval produces an explicit, permanent error naming the surface and the reason", async () => {
224
+ const s = seams();
225
+ const r = await deliver(APPROVAL_ITEM, "Approved.", { kind: "ack", ...s });
226
+
227
+ assert.equal(r.sent, false);
228
+ assert.equal(r.permanent, true, "an unroutable item must be permanent, or the sweep retries it forever");
229
+ assert.equal(r.surface, "approval");
230
+ assert.match(r.error, /cannot address a reply to approval item cohort:approval:aprv_journey_msopegu4:13546/);
231
+ assert.match(r.error, /approval\.resolve/);
232
+ assert.equal(s.callImpl.calls.length, 0);
233
+ assert.equal(s.sendMessageImpl.calls.length, 0);
234
+ });
235
+
236
+ test("assurance's pre-flight predicates refuse an approval instead of promising", () => {
237
+ assert.equal(replyTargetOf(APPROVAL_ITEM), null);
238
+ assert.equal(canDeliverTo(APPROVAL_ITEM), false);
239
+ // …and still say yes to the surfaces that DO have a route.
240
+ assert.equal(replyTargetOf(TASK_ITEM), "task:cmrlw2l3600e9hh8n10hprdrd");
241
+ assert.equal(canDeliverTo(TASK_ITEM), true);
242
+ assert.equal(replyTargetOf(DM_ITEM), "cmql1802601iihhzpf774vwbk");
243
+ assert.equal(canDeliverTo(DM_ITEM), true);
244
+ });
245
+
246
+ test("deliverWithRetry stops after ONE attempt on an unroutable item", async () => {
247
+ const s = seams();
248
+ let slept = 0;
249
+ const r = await deliverWithRetry(APPROVAL_ITEM, "Approved.", { kind: "ack", ...s, sleep: async () => { slept++; } });
250
+ assert.equal(r.sent, false);
251
+ assert.equal(r.attempts, 1, "the old code logged attempts:3 against an impossible send");
252
+ assert.equal(slept, 0);
253
+ });
254
+
255
+ test("a NOT_FOUND from hq is permanent — it is not retried three times", async () => {
256
+ const s = seams({ callFrame: { ok: false, error: { code: "NOT_FOUND", message: "no such task T-gone" } } });
257
+ let slept = 0;
258
+ const r = await deliverWithRetry({ ...TASK_ITEM, scope_id: "T-gone", thread_id: "T-gone" }, "hi", { ...s, sleep: async () => { slept++; } });
259
+ assert.equal(r.sent, false);
260
+ assert.equal(r.permanent, true);
261
+ assert.equal(r.code, "NOT_FOUND");
262
+ assert.equal(r.attempts, 1);
263
+ assert.equal(slept, 0);
264
+ assert.equal(s.callImpl.calls.length, 1);
265
+ });
266
+
267
+ test("a transient failure IS still retried", async () => {
268
+ const s = seams({ callFrame: { ok: false, error: { code: "INTERNAL", message: "hq restarting" } } });
269
+ let slept = 0;
270
+ const r = await deliverWithRetry(TASK_ITEM, "hi", { ...s, attempts: 3, sleep: async () => { slept++; } });
271
+ assert.equal(r.sent, false);
272
+ assert.equal(r.attempts, 3);
273
+ assert.equal(slept, 2);
274
+ assert.equal(s.callImpl.calls.length, 3);
275
+ });
276
+
277
+ // ---------------------------------------------------------------------------
278
+ // (4) The send-gate still guards the new lane, and it fails CLOSED.
279
+ // ---------------------------------------------------------------------------
280
+
281
+ test("the send-gate screens board comments too, and a block never reaches the wire", async () => {
282
+ const s = { ...seams(), gateImpl: async () => ({ allow: false, reason: "banned phrase" }) };
283
+ const r = await deliver(TASK_ITEM, "guaranteed returns", { ...s });
284
+ assert.equal(r.sent, false);
285
+ assert.equal(r.permanent, true);
286
+ assert.match(r.error, /FORBIDDEN_SCOPE: banned phrase/);
287
+ assert.equal(s.callImpl.calls.length, 0, "a blocked message must never reach the RPC");
288
+ });
289
+
290
+ test("a send-gate fault fails CLOSED on the entity lane", async () => {
291
+ const s = { ...seams(), gateImpl: async () => { throw new Error("policy file unreadable"); } };
292
+ const r = await deliver(TASK_ITEM, "hi", { ...s });
293
+ assert.equal(r.sent, false);
294
+ assert.equal(s.callImpl.calls.length, 0);
295
+ assert.match(r.error, /send-gate error/);
296
+ });
297
+
298
+ test("the gate screens the ROUTABLE target, never the label", async () => {
299
+ const seen = [];
300
+ const s = { ...seams(), gateImpl: async (a) => { seen.push(a.recipient); return { allow: true }; } };
301
+ await deliver(TASK_ITEM, "hi", { ...s });
302
+ assert.deepEqual(seen, ["task:cmrlw2l3600e9hh8n10hprdrd"]);
303
+ });
304
+
305
+ // ---------------------------------------------------------------------------
306
+ // Surface resolution
307
+ // ---------------------------------------------------------------------------
308
+
309
+ test("cohortSurfaceOf reads raw_ref, and tolerates the LEGACY cohort:<channelId>:<msgId> shape", () => {
310
+ assert.equal(cohortSurfaceOf(TASK_ITEM), "task_comment");
311
+ assert.equal(cohortSurfaceOf(APPROVAL_ITEM), "approval");
312
+ // Legacy raw_ref: the middle segment is a channel id, not a surface name.
313
+ assert.equal(cohortSurfaceOf({ raw_ref: "cohort:cmql1802601iihhzpf774vwbk:cmsnbgwsz003flj014spp4i1z", channel_id: "cmql1802601iihhzpf774vwbk" }), "dm");
314
+ // An all-lowercase legacy channel id must NOT be mistaken for a surface.
315
+ assert.equal(cohortSurfaceOf({ raw_ref: "cohort:abcdef:xyz", channel_id: "abcdef" }), "dm");
316
+ // `file_comment` is the kind of TWO surfaces; the room tells them apart.
317
+ assert.equal(cohortSurfaceOf({ kind: "file_comment", channel_id: "C-1" }), "file_comment");
318
+ assert.equal(cohortSurfaceOf({ kind: "file_comment", channel_id: "" }), "doc_comment");
319
+ });
320
+
321
+ test("a chat-attached file comment routes to file.addComment with fileKey + its room", () => {
322
+ const route = cohortReplyRoute({ service: "cohort", kind: "file_comment", channel: "#eng", channel_id: "C-9", thread_id: "fk_abc", raw_ref: "cohort:file_comment:cmt-1:3" });
323
+ assert.equal(route.method, "file.addComment");
324
+ assert.deepEqual(route.params, { fileKey: "fk_abc", channelId: "C-9" });
325
+ });
326
+
327
+ test("handoff and email are named as unaddressable rather than guessed into a channel", () => {
328
+ const h = cohortReplyRoute({ service: "cohort", kind: "handoff", channel: "handoff/Ship it", channel_id: "", thread_id: "run-1", raw_ref: "cohort:handoff:run-1:4" });
329
+ assert.equal(h.transport, null);
330
+ assert.match(h.error, /handoff\.accept\/decline/);
331
+ // `channel_id` on the email surface is a MAILBOX id — messaging.send would
332
+ // reject it exactly as it rejected a task title.
333
+ const e = cohortReplyRoute({ service: "cohort", kind: "email", channel: "email", channel_id: "MB-1", thread_id: "th-1", raw_ref: "cohort:email:e-1:2" });
334
+ assert.equal(e.transport, null);
335
+ assert.match(e.error, /mailbox id, not a channel/);
336
+ });
337
+
338
+ test("escalation and calendar use their own room when hq attached one, and refuse when it did not", () => {
339
+ const bound = cohortReplyRoute({ service: "cohort", kind: "escalation", channel: "escalation/DB down", channel_id: "C-7", thread_id: "esc-1", raw_ref: "cohort:escalation:esc-1:1" });
340
+ assert.equal(bound.transport, "channel");
341
+ assert.equal(bound.target, "C-7");
342
+ const loose = cohortReplyRoute({ service: "cohort", kind: "escalation", channel: "escalation/DB down", channel_id: "", thread_id: "esc-1", raw_ref: "cohort:escalation:esc-1:1" });
343
+ assert.equal(loose.transport, null);
344
+ assert.match(loose.error, /no comment surface/);
345
+ });
346
+
347
+ test("no route on any surface is ever derived from item.channel", () => {
348
+ const surfaces = [
349
+ "dm", "mention", "thread_reply", "call", "task_assigned", "task_comment",
350
+ "file_comment", "doc_comment", "approval", "decision", "escalation",
351
+ "calendar", "handoff", "email",
352
+ ];
353
+ for (const surface of surfaces) {
354
+ const item = { service: "cohort", channel: `${surface}/A LABEL`, channel_id: "", thread_id: "", scope_id: "", raw_ref: `cohort:${surface}:E-1:1` };
355
+ const route = cohortReplyRoute(item);
356
+ const blob = JSON.stringify(route);
357
+ assert.ok(!blob.includes("A LABEL"), `${surface}: the label leaked into the route (${blob})`);
358
+ assert.notEqual(replyTargetOf(item), item.channel, `${surface}: replyTargetOf returned the label`);
359
+ }
360
+ });
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // Non-cohort services are untouched.
364
+ // ---------------------------------------------------------------------------
365
+
366
+ test("slack and gmail targeting is unchanged", () => {
367
+ assert.equal(replyTargetOf({ service: "slack", channel: "D099N1JGKRQ" }), "D099N1JGKRQ");
368
+ assert.equal(replyTargetOf({ service: "slack", raw_ref: "slack:D099N1JGKRQ:1775331885.690669" }), "D099N1JGKRQ");
369
+ assert.equal(replyTargetOf({ service: "gmail", sender_email: "a@b.com", sender: "A B" }), "a@b.com");
370
+ assert.equal(canDeliverTo({ service: "telegram", channel_id: "12345", channel: "dm/casey" }), false);
371
+ });
372
+
373
+ // ---------------------------------------------------------------------------
374
+ // (5) THE REAL SEND-GATE. Every test above stubs it, and that is exactly how a
375
+ // lane that was blocked 100% of the time shipped with 21 green tests: the
376
+ // routing table reached the right method with the right params, and the
377
+ // gate in front of it refused every one of them before the wire.
378
+ //
379
+ // `screenOutbound` defaults `firstContact` to TRUE, and under the shipped
380
+ // `disclose-always` posture that blocks any message which does not
381
+ // proactively disclose AI. The room lane passes `false`; the entity lane
382
+ // did not pass it at all. FORBIDDEN_SCOPE is permanent, so the reply was
383
+ // dropped on the first attempt — a different error string for the same
384
+ // "the board never hears from us".
385
+ //
386
+ // These run the module's OWN screenOutbound against a real policy file on
387
+ // disk. Nothing is stubbed but the wire.
388
+ // ---------------------------------------------------------------------------
389
+
390
+ import { mkdirSync, writeFileSync } from "node:fs";
391
+
392
+ /** An agent root with the shipped `disclose-always` posture on disk. */
393
+ function policyRoot() {
394
+ const root = mkdtempSync(join(tmpdir(), "deliver-policies-"));
395
+ mkdirSync(join(root, "policies"), { recursive: true });
396
+ // The SHIPPED shape (isla-ai policies/ai-disclosure.yaml), not a shorthand:
397
+ // `posture` is a MAP of posture-name → config and `default_posture` selects
398
+ // one. A bare `posture: disclose-always` scalar resolves to an EMPTY posture
399
+ // object, `proactive_disclosure` is undefined, and the disclosure screen
400
+ // silently never fires — which would make this whole section vacuous.
401
+ writeFileSync(
402
+ join(root, "policies", "ai-disclosure.yaml"),
403
+ [
404
+ "version: 1",
405
+ "invariant:",
406
+ " answer_truthfully_if_asked: true",
407
+ "posture:",
408
+ " disclose-always:",
409
+ " proactive_disclosure: true",
410
+ " machine_readable_marking: true",
411
+ "default_posture: disclose-always",
412
+ "jurisdictions:",
413
+ " default:",
414
+ " posture: disclose-always",
415
+ "",
416
+ ].join("\n"),
417
+ "utf8",
418
+ );
419
+ writeFileSync(join(root, "policies", "information-barriers.yaml"), "walls: []\n", "utf8");
420
+ return root;
421
+ }
422
+
423
+ test("REAL GATE: a board comment reaches the wire — the entity lane is not first contact", async () => {
424
+ const agentRoot = policyRoot();
425
+ const callImpl = recordingCall();
426
+ const r = await deliver(TASK_ITEM, "The guardrail rollout is unblocked — moving it to review.", {
427
+ kind: "reply", callImpl, cfg: CFG, agentRoot, ledgerImpl: null,
428
+ });
429
+
430
+ assert.equal(r.sent, true, `the real gate blocked the entity lane: ${JSON.stringify(r)}`);
431
+ assert.equal(r.via, "board.addTaskComment");
432
+ assert.equal(callImpl.calls.length, 1, "nothing reached the wire");
433
+ assert.equal(callImpl.calls[0].method, "board.addTaskComment");
434
+ });
435
+
436
+ test("REAL GATE: doc and decision replies reach the wire too", async () => {
437
+ const agentRoot = policyRoot();
438
+ for (const [item, method] of [
439
+ [{ service: "cohort", kind: "file_comment", channel: "doc/CHARTER.pdf", channel_id: "", thread_id: "cmsu0pbez00m7lx01u6mbqk9g", scope_id: "cmsu0pbez00m7lx01u6mbqk9g", raw_ref: "cohort:doc_comment:cmsu0pbez00m7lx01u6mbqk9g:27088" }, "files.commentAdd"],
440
+ [{ service: "cohort", kind: "decision", channel: "decision/Adopt tier-3", channel_id: "", thread_id: "cmdec0000000000000000000", scope_id: "cmdec0000000000000000000", raw_ref: "cohort:decision:cmdec0000000000000000000:9" }, "decision.comment"],
441
+ ]) {
442
+ const callImpl = recordingCall();
443
+ const r = await deliver(item, "Section 3 reads fine to me.", { callImpl, cfg: CFG, agentRoot, ledgerImpl: null });
444
+ assert.equal(r.sent, true, `${method} blocked by the real gate: ${JSON.stringify(r)}`);
445
+ assert.equal(callImpl.calls[0].method, method);
446
+ }
447
+ });
448
+
449
+ test("REAL GATE: the room lane is unchanged — same policies, same text, still sends", async () => {
450
+ const agentRoot = policyRoot();
451
+ const sendMessageImpl = recordingSend();
452
+ const r = await deliver(DM_ITEM, "The guardrail rollout is unblocked.", {
453
+ sendMessageImpl, cfg: CFG, agentRoot, ledgerImpl: null,
454
+ });
455
+ assert.equal(r.sent, true, `the room lane regressed: ${JSON.stringify(r)}`);
456
+ assert.equal(sendMessageImpl.calls.length, 1);
457
+ });
458
+
459
+ test("REAL GATE: the entity target classifies INTERNAL, so a policy fault does not fail closed", async () => {
460
+ // An agentRoot with NO policies/ at all — the "unreadable required policy"
461
+ // case. It gags an EXTERNAL recipient and must not gag a board thread.
462
+ const bare = mkdtempSync(join(tmpdir(), "deliver-nopolicy-"));
463
+ const callImpl = recordingCall();
464
+ const r = await deliver(TASK_ITEM, "Moving it to review.", { callImpl, cfg: CFG, agentRoot: bare, ledgerImpl: null });
465
+ assert.equal(r.sent, true, `board lane failed closed on a policy fault: ${JSON.stringify(r)}`);
466
+ assert.equal(callImpl.calls.length, 1);
467
+ });
468
+
469
+ test("REAL GATE: banned prose is still refused on the entity lane", async () => {
470
+ // The gate must still be a gate — this is the half the stub was proving.
471
+ const agentRoot = policyRoot();
472
+ const callImpl = recordingCall();
473
+ const r = await deliver(TASK_ITEM, "Certainly! I guarantee returns on this rollout.", {
474
+ callImpl, cfg: CFG, agentRoot, ledgerImpl: null,
475
+ });
476
+ assert.equal(r.sent, false);
477
+ assert.equal(callImpl.calls.length, 0, "banned prose reached the wire");
478
+ });
479
+
480
+ // ---------------------------------------------------------------------------
481
+ // (6) The author kind, and its one fallback.
482
+ // ---------------------------------------------------------------------------
483
+
484
+ test("an unassigned task falls back to the acting member rather than losing the reply", async () => {
485
+ // hq's board/addTaskComment.ts refuses `kind:"agent"` when the task has no
486
+ // assignee AND no reviewer. That is a different request, not a flaky one, so
487
+ // it is re-asked once — not retried.
488
+ let n = 0;
489
+ const calls = [];
490
+ const callImpl = async (method, params, o) => {
491
+ calls.push(params);
492
+ n += 1;
493
+ return n === 1
494
+ ? { ok: false, error: { code: "BAD_REQUEST", message: "this task has no responsible agent to reply" } }
495
+ : { ok: true, result: { id: "c1" } };
496
+ };
497
+ const r = await deliver(TASK_ITEM, "Picking this up.", { callImpl, gateImpl: OK_GATE, cfg: CFG, ledgerImpl: null });
498
+ assert.equal(r.sent, true, `the fallback did not fire: ${JSON.stringify(r)}`);
499
+ assert.deepEqual(calls.map((c) => c.kind), ["agent", "human"]);
500
+ });
501
+
502
+ test("an UNRELATED BAD_REQUEST is still permanent — the fallback is not a blanket retry", async () => {
503
+ const s = seams({ callFrame: { ok: false, error: { code: "BAD_REQUEST", message: "body must be a string" } } });
504
+ const r = await deliverWithRetry(TASK_ITEM, "hi", { ...s, sleep: async () => {} });
505
+ assert.equal(r.sent, false);
506
+ assert.equal(r.permanent, true);
507
+ assert.equal(r.attempts, 1);
508
+ assert.equal(s.callImpl.calls.length, 1, "an unrelated BAD_REQUEST must not be re-asked");
509
+ });
510
+
511
+ test("a 401 is TRANSIENT — a token rotation must not throw the reply away", async () => {
512
+ // UNAUTHORIZED describes the credential at one instant, not the request.
513
+ const s = seams({ callFrame: { ok: false, error: { code: "UNAUTHORIZED", message: "token expired" } } });
514
+ let slept = 0;
515
+ const r = await deliverWithRetry(TASK_ITEM, "hi", { ...s, attempts: 3, sleep: async () => { slept++; } });
516
+ assert.equal(r.sent, false);
517
+ assert.equal(r.permanent, undefined);
518
+ assert.equal(r.attempts, 3);
519
+ assert.equal(slept, 2);
520
+ });
521
+
522
+ // ---------------------------------------------------------------------------
523
+ // (7) hq must be able to DEDUPE the retry the line above just re-enabled.
524
+ // ---------------------------------------------------------------------------
525
+
526
+ test("the entity comment methods are declared idempotent, so a retry cannot double-post", async () => {
527
+ // hq replays a stored result ONLY for `def.idempotent === true`
528
+ // (server/rpc/dispatch.ts); without the flag the `x-idempotency-key` this
529
+ // lane sends is ignored and a timeout-after-commit posts the comment twice.
530
+ const { methodDef } = await import("../../lib/org/protocol.mjs");
531
+ for (const m of ["board.addTaskComment", "files.commentAdd", "decision.comment", "file.addComment"]) {
532
+ assert.equal(methodDef(m).idempotent, true, `${m} is retried but not idempotent`);
533
+ }
534
+ // …and the lane actually sends a key.
535
+ const s = seams();
536
+ await deliver(TASK_ITEM, "hi", { ...s });
537
+ assert.equal(s.callImpl.calls[0].o.idempotencyKey, "reply-25029");
538
+ });
539
+
540
+ // ---------------------------------------------------------------------------
541
+ // (8) The assurance sweep must route the SAME item the live path did.
542
+ // ---------------------------------------------------------------------------
543
+
544
+ test("the sweep's item snapshot routes IDENTICALLY to the live item", async () => {
545
+ // `itemSnapshot` persisted channel/channel_id/thread_id/raw_ref but NOT
546
+ // `scope_id` — which `cohortReplyRoute` names FIRST for every roomless
547
+ // surface. The sweep re-delivers from the snapshot, so it was routing a
548
+ // different item than the live path. Masked only by every hydrator happening
549
+ // to set thread_id too.
550
+ const { itemSnapshot } = await import("./assurance.mjs");
551
+ for (const live of [
552
+ TASK_ITEM,
553
+ APPROVAL_ITEM,
554
+ DM_ITEM,
555
+ // The unmasked case: an id in scope_id and nowhere else.
556
+ { service: "cohort", kind: "decision", channel: "decision/x", channel_id: "", thread_id: "", scope_id: "cmdec0000000000000000000", raw_ref: "" },
557
+ ]) {
558
+ assert.deepEqual(
559
+ cohortReplyRoute(itemSnapshot(live)),
560
+ cohortReplyRoute(live),
561
+ `the sweep routes ${live.kind} differently from the live path`,
562
+ );
563
+ }
564
+ });
@@ -76,6 +76,22 @@ test("cohort: an empty channel is null, not an empty transcript", async () => {
76
76
  assert.equal(text, null);
77
77
  });
78
78
 
79
+ test("cohort: a roomless surface never asks messaging.history for its LABEL", async () => {
80
+ // A board / doc / decision item has a blank `channel_id` by design and its
81
+ // `channel` is the human label (`task/<title>`). This used to fall back to
82
+ // that label, so the history read asked hq for a channel named after a task
83
+ // title and got nothing — the same label-for-an-id substitution that had the
84
+ // REPLY posted to a task title. The entity's own thread already rides on the
85
+ // item as `thread_context`, so there is nothing to fetch here.
86
+ const seen = [];
87
+ const text = await loadConversationHistory(
88
+ { sender: "Dana Okafor", service: "cohort", kind: "task_comment", channel: "task/Roll out tier-3 guardrails", channel_id: "", content: "?" },
89
+ { fetchHistory: async (params) => { seen.push(params); return []; }, loadOrgConfig: () => ({}) },
90
+ );
91
+ assert.equal(seen.length, 0, "no history call may be made with a label");
92
+ assert.equal(text, null);
93
+ });
94
+
79
95
  test("cohort: a failing history call degrades to null and never throws", async () => {
80
96
  const text = await loadConversationHistory(cohortItem, {
81
97
  fetchHistory: async () => { throw new Error("cohort unreachable"); },
@@ -132,7 +148,7 @@ test("cohort: falls back to the local mirror when the server is unreachable", as
132
148
  );
133
149
 
134
150
  const text = await loadConversationHistory(
135
- { sender: "Dana Okafor", service: "cohort", channel: "chan-1", content: "?" },
151
+ { sender: "Dana Okafor", service: "cohort", channel: "chan-1", channel_id: "chan-1", content: "?" },
136
152
  {
137
153
  agentRepoDir: root,
138
154
  loadOrgConfig: () => ({}),
@@ -154,7 +170,7 @@ test("cohort: server history wins over the local mirror", async () => {
154
170
  );
155
171
 
156
172
  const text = await loadConversationHistory(
157
- { sender: "Dana Okafor", service: "cohort", channel: "chan-1", content: "?" },
173
+ { sender: "Dana Okafor", service: "cohort", channel: "chan-1", channel_id: "chan-1", content: "?" },
158
174
  {
159
175
  agentRepoDir: root,
160
176
  loadOrgConfig: () => ({}),
@@ -556,7 +556,13 @@ const COHORT_HISTORY_CHARS = 400;
556
556
  * Fails open to null on every path. No amount of history is worth failing a send.
557
557
  */
558
558
  async function loadCohortHistory(item, deps = {}) {
559
- const channel = item.channel_id || item.channel || "";
559
+ // `channel_id` ONLY. `item.channel` is the display label (`task/<title>`,
560
+ // `doc/<name>`) and `messaging.history` wants a channel id — the same
561
+ // label-for-an-id substitution that had board replies posted to a task's
562
+ // title. A surface with no room simply has no channel history: the board /
563
+ // doc / decision hydrators already put the entity's OWN thread on the item as
564
+ // `thread_context`, so nothing is lost by not asking for a room's.
565
+ const channel = item.channel_id || "";
560
566
  if (!channel) return null;
561
567
 
562
568
  try {