@cohortapp/agent-sdk 2.3.2 → 2.4.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 (148) hide show
  1. package/framework-features.json +30 -0
  2. package/lib/backlog.mjs +136 -0
  3. package/lib/cadences.mjs +63 -2
  4. package/lib/cadences.test.mjs +105 -0
  5. package/lib/capability/inventory.mjs +542 -0
  6. package/lib/capability/inventory.test.mjs +232 -0
  7. package/lib/capability/probe.mjs +255 -0
  8. package/lib/channels/contract.mjs +37 -1
  9. package/lib/channels/contract.test.mjs +25 -1
  10. package/lib/claude-bin.mjs +37 -3
  11. package/lib/claude-bin.test.mjs +42 -8
  12. package/lib/execution/disposition.mjs +501 -0
  13. package/lib/execution/disposition.test.mjs +482 -0
  14. package/lib/execution/drive.mjs +352 -0
  15. package/lib/execution/drive.test.mjs +270 -0
  16. package/lib/execution/effects.mjs +340 -0
  17. package/lib/execution/effects.test.mjs +193 -0
  18. package/lib/execution/index.mjs +152 -0
  19. package/lib/execution/intake.mjs +581 -0
  20. package/lib/execution/intake.test.mjs +343 -0
  21. package/lib/execution/journal.mjs +374 -0
  22. package/lib/execution/journal.test.mjs +261 -0
  23. package/lib/execution/match.mjs +331 -0
  24. package/lib/execution/match.test.mjs +235 -0
  25. package/lib/execution/pipeline.mjs +341 -0
  26. package/lib/execution/pipeline.test.mjs +389 -0
  27. package/lib/execution/route.mjs +332 -0
  28. package/lib/execution/route.test.mjs +186 -0
  29. package/lib/execution/surface-policy.mjs +446 -0
  30. package/lib/execution/surface-policy.test.mjs +162 -0
  31. package/lib/goals/admission.mjs +209 -0
  32. package/lib/goals/admission.test.mjs +139 -0
  33. package/lib/goals/classify.mjs +206 -0
  34. package/lib/goals/classify.test.mjs +109 -0
  35. package/lib/goals/collaborate.mjs +415 -0
  36. package/lib/goals/collaborate.test.mjs +324 -0
  37. package/lib/goals/gaps.mjs +111 -0
  38. package/lib/goals/gaps.test.mjs +284 -0
  39. package/lib/goals/loop.mjs +537 -0
  40. package/lib/goals/loop.test.mjs +719 -0
  41. package/lib/identity/persona.mjs +247 -0
  42. package/lib/identity/persona.test.mjs +117 -0
  43. package/lib/kpi.mjs +469 -0
  44. package/lib/kpi.test.mjs +244 -0
  45. package/lib/mandate/audit.mjs +168 -0
  46. package/lib/mandate/audit.test.mjs +195 -0
  47. package/lib/mandate/cache.mjs +162 -0
  48. package/lib/mandate/derive.mjs +317 -0
  49. package/lib/mandate/derive.test.mjs +224 -0
  50. package/lib/mandate/model.mjs +352 -0
  51. package/lib/mandate/model.test.mjs +145 -0
  52. package/lib/mandate/refresh.mjs +187 -0
  53. package/lib/mandate/refresh.test.mjs +293 -0
  54. package/lib/mcp/server.test.mjs +4 -4
  55. package/lib/org/approvals.mjs +14 -2
  56. package/lib/org/client.mjs +58 -22
  57. package/lib/org/client.test.mjs +3 -1
  58. package/lib/org/inbound/directedness.mjs +720 -0
  59. package/lib/org/inbound/directedness.test.mjs +543 -0
  60. package/lib/org/inbound/facts.mjs +501 -0
  61. package/lib/org/inbound/facts.test.mjs +375 -0
  62. package/lib/org/inbound/hydrate.mjs +535 -0
  63. package/lib/org/inbound/hydrate.test.mjs +326 -0
  64. package/lib/org/inbound/index.mjs +233 -0
  65. package/lib/org/inbound/index.test.mjs +324 -0
  66. package/lib/org/inbound/io.mjs +141 -0
  67. package/lib/org/inbound/project.mjs +201 -0
  68. package/lib/org/inbound/project.test.mjs +287 -0
  69. package/lib/org/inbound/surfaces.mjs +257 -0
  70. package/lib/org/knowledge.mjs +10 -1
  71. package/lib/org/knowledge.test.mjs +8 -1
  72. package/lib/org/leases.mjs +5 -0
  73. package/lib/org/mesh.mjs +17 -2
  74. package/lib/org/messaging.mjs +40 -4
  75. package/lib/org/messaging.test.mjs +40 -0
  76. package/lib/org/param-contract.mjs +694 -0
  77. package/lib/org/param-contract.test.mjs +451 -0
  78. package/lib/org/protocol.checksum +1 -1
  79. package/lib/org/protocol.mjs +8 -0
  80. package/lib/org/protocol.test.mjs +5 -1
  81. package/lib/org/push.mjs +1025 -0
  82. package/lib/org/push.test.mjs +690 -0
  83. package/lib/org/tool-surface.mjs +138 -38
  84. package/lib/org/tool-surface.test.mjs +13 -8
  85. package/lib/org/typing.mjs +341 -0
  86. package/lib/org/typing.test.mjs +291 -0
  87. package/lib/plan/compile.mjs +510 -0
  88. package/lib/plan/compile.test.mjs +286 -0
  89. package/lib/plan/emit.mjs +256 -0
  90. package/lib/plan/emit.test.mjs +246 -0
  91. package/lib/plan/explain.mjs +226 -0
  92. package/lib/plan/explain.test.mjs +188 -0
  93. package/lib/plan/schema.mjs +140 -0
  94. package/lib/resource-governor.mjs +47 -1
  95. package/lib/resource-governor.test.mjs +21 -1
  96. package/lib/setup/enroll-from-cohort.mjs +105 -17
  97. package/lib/setup/enroll-from-cohort.test.mjs +68 -1
  98. package/lib/setup/sections/identity.mjs +15 -4
  99. package/lib/setup/sections/identity.test.mjs +94 -0
  100. package/lib/setup/sections/inventory.mjs +178 -0
  101. package/lib/setup/sections/inventory.test.mjs +198 -0
  102. package/lib/setup/sections/mandate.mjs +392 -0
  103. package/lib/setup/sections/mandate.test.mjs +373 -0
  104. package/lib/setup/sections/subagents.mjs +427 -0
  105. package/lib/setup/sections/subagents.test.mjs +429 -0
  106. package/lib/setup/sections/verify.mjs +121 -0
  107. package/lib/setup/sections/verify.test.mjs +175 -0
  108. package/lib/setup/sot.mjs +2 -0
  109. package/lib/subagents/cli.mjs +463 -0
  110. package/lib/subagents/cli.test.mjs +389 -0
  111. package/lib/subagents/client.mjs +373 -0
  112. package/lib/subagents/client.test.mjs +309 -0
  113. package/lib/subagents/gap.mjs +268 -0
  114. package/lib/subagents/gap.test.mjs +234 -0
  115. package/lib/subagents/lock.mjs +296 -0
  116. package/lib/subagents/lock.test.mjs +248 -0
  117. package/lib/subagents/manifest.mjs +224 -0
  118. package/lib/subagents/manifest.test.mjs +175 -0
  119. package/lib/subagents/refs.mjs +274 -0
  120. package/lib/subagents/refs.test.mjs +204 -0
  121. package/lib/subagents/resolve.mjs +455 -0
  122. package/lib/subagents/resolve.test.mjs +422 -0
  123. package/lib/subagents/schema.mjs +467 -0
  124. package/lib/subagents/schema.test.mjs +306 -0
  125. package/package.json +8 -3
  126. package/plugins/maestro-skills/.claude-plugin/marketplace.json +16 -0
  127. package/policies/ai-disclosure.yaml +42 -2
  128. package/scaffold/CLAUDE.md +16 -2
  129. package/schedules/triggers/goal-steward.md +79 -0
  130. package/scripts/ci/conformance-org-api.mjs +792 -0
  131. package/scripts/ci/conformance-org-api.test.mjs +417 -0
  132. package/scripts/daemon/agent-daemon.mjs +36 -4
  133. package/scripts/daemon/cadence-handlers.mjs +145 -1
  134. package/scripts/daemon/goal-steward-cadence.test.mjs +243 -0
  135. package/scripts/daemon/inbox-deferral.mjs +45 -2
  136. package/scripts/daemon/inbox-deferral.test.mjs +56 -0
  137. package/scripts/daemon/inbox-wake.mjs +282 -0
  138. package/scripts/daemon/inbox-wake.test.mjs +199 -0
  139. package/scripts/daemon/prompt-builder.mjs +41 -1
  140. package/scripts/daemon/typing-registry.mjs +55 -2
  141. package/scripts/daemon/typing-registry.test.mjs +25 -0
  142. package/scripts/local-triggers/generate-plists.test.mjs +5 -5
  143. package/scripts/setup/gen-subagent-manifest.mjs +95 -0
  144. package/scripts/setup/gen-subagent-manifest.test.mjs +124 -0
  145. package/scripts/setup/generate-plan.mjs +108 -0
  146. package/scripts/setup/init-capability-manifest.mjs +70 -0
  147. package/scripts/setup/init-skill-marketplace.mjs +155 -0
  148. package/scripts/setup/init-skill-marketplace.test.mjs +193 -0
@@ -0,0 +1,352 @@
1
+ /**
2
+ * lib/execution/drive.mjs — turn a decision into a thing that actually happened.
3
+ *
4
+ * `disposition.mjs` is pure and decides; this module is effectful and does. The
5
+ * split exists so the decision can be tested exhaustively per surface without a
6
+ * network, and so the journal records the reasoning *before* the side effect
7
+ * runs — if the process dies mid-action there is still a record of what it was
8
+ * trying to do and why.
9
+ *
10
+ * Order of operations, and the reason for each:
11
+ *
12
+ * 1. journal the decision (so a crash leaves evidence, not silence)
13
+ * 2. ignore ⇒ record and stop (an ignore is an outcome, not an absence)
14
+ * 3. observe-only ⇒ propose (§5.10: the 14-day window creates no work)
15
+ * 4. approval gate (§8: blast radius gates BEFORE any rung)
16
+ * 5. arbitration gate (one agent per thread, fail-open on 3s)
17
+ * 6. the effect itself
18
+ * 7. drift report (best effort; never blocks the action)
19
+ * 8. journal the outcome
20
+ *
21
+ * Every effect is INJECTED. `drive` imports nothing that touches the network —
22
+ * `effects.mjs` does that — which keeps this file testable with plain fakes and
23
+ * keeps the sequencing logic in one readable place.
24
+ *
25
+ * FAIL-OPEN, NEVER SILENT. An effect that throws does not take the daemon down
26
+ * and does not abort the remaining bookkeeping; it produces `ok:false` with the
27
+ * error text on the outcome row and a `degraded` entry the caller logs. Every
28
+ * bug found in this system so far has been a silent fail-open, so there is no
29
+ * bare `catch {}` in this file.
30
+ *
31
+ * @module lib/execution/drive
32
+ */
33
+
34
+ "use strict";
35
+
36
+ import { recordDecision, recordOutcome } from "./journal.mjs";
37
+ import { willAct } from "./disposition.mjs";
38
+ import { isDisposition } from "./surface-policy.mjs";
39
+
40
+ /** The effect name invoked for each disposition. */
41
+ export const EFFECT_FOR = Object.freeze({
42
+ react_now: "react",
43
+ schedule: "schedule",
44
+ delegate: "delegate",
45
+ escalate: "escalate",
46
+ });
47
+
48
+ /** Dispositions after which the agent has SPOKEN (deepens a reply chain). */
49
+ const SPEAKING = Object.freeze(["react_now"]);
50
+
51
+ /**
52
+ * Run one effect with uniform error capture. Returns a normalised result rather
53
+ * than throwing, so the caller's sequencing stays linear.
54
+ *
55
+ * @param {Function|undefined} fn
56
+ * @param {string} name
57
+ * @param {object} args
58
+ * @returns {Promise<{ok:boolean, ref:any, error:string|null, missing:boolean}>}
59
+ */
60
+ async function runEffect(fn, name, args) {
61
+ if (typeof fn !== "function") {
62
+ return { ok: false, ref: null, error: `no effect wired for \`${name}\``, missing: true };
63
+ }
64
+ try {
65
+ const r = await fn(args);
66
+ if (r && typeof r === "object" && "ok" in r) {
67
+ return {
68
+ ok: r.ok !== false,
69
+ ref: r.ref === undefined ? null : r.ref,
70
+ error: r.error ? String(r.error) : null,
71
+ missing: false,
72
+ };
73
+ }
74
+ return { ok: true, ref: r === undefined ? null : r, error: null, missing: false };
75
+ } catch (err) {
76
+ return {
77
+ ok: false,
78
+ ref: null,
79
+ error: err && err.message ? err.message : String(err),
80
+ missing: false,
81
+ };
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Drive a decision to an action.
87
+ *
88
+ * @param {object} decision the output of `disposition.decide`
89
+ * @param {object} o
90
+ * @param {object} o.candidate the inbound Candidate the decision was made about
91
+ * @param {object} o.effects {
92
+ * react, schedule, delegate, escalate, propose,
93
+ * requestApproval, arbitrate, reportDrift
94
+ * } — every key optional; a missing one degrades that path loudly
95
+ * @param {string} [o.agentRoot]
96
+ * @param {number} [o.nowMs]
97
+ * @param {string} [o.traceId]
98
+ * @param {Function} [o.log] (level, message, attrs) — defaults to console.warn
99
+ * for degradations. Never swallowed.
100
+ * @param {Function} [o.append] journal writer override (tests)
101
+ * @returns {Promise<{
102
+ * ok:boolean, disposition:string, effect:string|null, ref:any,
103
+ * spoke:boolean, error:string|null, degraded:string[], decision:object
104
+ * }>}
105
+ */
106
+ export async function drive(decision, o = {}) {
107
+ const effects = (o && o.effects) || {};
108
+ const nowMs = Number.isFinite(o.nowMs) ? o.nowMs : Date.now();
109
+ const journalOpts = {
110
+ agentRoot: o.agentRoot,
111
+ nowMs,
112
+ traceId: o.traceId,
113
+ append: o.append,
114
+ path: o.journalPath,
115
+ };
116
+ const degraded = [].concat((decision && decision.degraded) || []);
117
+ const log =
118
+ typeof o.log === "function"
119
+ ? o.log
120
+ : (level, msg, attrs) => {
121
+ // A degradation that is not printed is a degradation nobody fixes.
122
+ const line = `[execution] ${msg}`;
123
+ if (level === "error") console.error(line, attrs || "");
124
+ else console.warn(line, attrs || "");
125
+ };
126
+
127
+ if (!decision || typeof decision !== "object") {
128
+ log("error", "drive called with no decision — the inbound event is unaccounted for");
129
+ return {
130
+ ok: false,
131
+ disposition: null,
132
+ effect: null,
133
+ ref: null,
134
+ spoke: false,
135
+ error: "no decision",
136
+ degraded: ["no_decision"],
137
+ decision: null,
138
+ };
139
+ }
140
+
141
+ // 1. Journal the reasoning FIRST. If the process dies in the effect below,
142
+ // this row is what tells you what it was doing.
143
+ const written = recordDecision(decision, journalOpts);
144
+ if (!written.ok) {
145
+ degraded.push("journal_decision_write_failed");
146
+ log("error", "could not write the decision journal — proceeding, but this action will be unexplained", {
147
+ key: decision.key,
148
+ });
149
+ }
150
+ for (const d of decision.degraded || []) log("warn", `decision degraded: ${d}`, { key: decision.key });
151
+
152
+ const finish = async (res) => {
153
+ const outcome = {
154
+ key: decision.key,
155
+ thread: decision.thread,
156
+ surface: decision.surface,
157
+ disposition: decision.disposition,
158
+ effect: res.effect,
159
+ ok: res.ok,
160
+ spoke: res.spoke === true,
161
+ ref: res.ref,
162
+ error: res.error,
163
+ degraded: res.degraded && res.degraded.length ? res.degraded.join(",") : null,
164
+ obligationKey: decision.obligationKey,
165
+ costCents: res.costCents,
166
+ };
167
+ const w = recordOutcome(outcome, journalOpts);
168
+ if (!w.ok) log("error", "could not write the outcome journal", { key: decision.key });
169
+ return {
170
+ ok: res.ok,
171
+ disposition: decision.disposition,
172
+ effect: res.effect,
173
+ ref: res.ref,
174
+ spoke: res.spoke === true,
175
+ error: res.error,
176
+ degraded: res.degraded || [],
177
+ decision,
178
+ };
179
+ };
180
+
181
+ // Drift is reported for ignore paths too (`mandate_stale` is an ignore), so it
182
+ // runs before the ignore short-circuit. Best effort by design: a drift report
183
+ // that fails must never stop the agent doing the actual work.
184
+ if (decision.drift) {
185
+ const d = await runEffect(effects.reportDrift, "reportDrift", {
186
+ drift: decision.drift,
187
+ decision,
188
+ candidate: o.candidate,
189
+ });
190
+ if (!d.ok) {
191
+ degraded.push(`drift_report_failed:${decision.drift.kind}`);
192
+ log("warn", `drift report failed (${decision.drift.kind}) — the plan gap is local-only`, { error: d.error });
193
+ }
194
+ }
195
+
196
+ // 2. An ignore is a completed decision. Record it and stop.
197
+ //
198
+ // An UNRECOGNISED disposition is not the same thing and must not be quietly
199
+ // folded in here — that would be the exact silent fail-open this codebase
200
+ // keeps shipping: a malformed decision would look like a successful "we chose
201
+ // not to act" and the event would vanish with a green outcome row.
202
+ if (!isDisposition(decision.disposition)) {
203
+ log("error", `unrecognised disposition \`${decision.disposition}\` — the event was not acted on`, {
204
+ key: decision.key,
205
+ });
206
+ degraded.push("invalid_disposition");
207
+ return finish({
208
+ effect: null,
209
+ ok: false,
210
+ spoke: false,
211
+ ref: null,
212
+ error: `unmapped disposition ${decision.disposition}`,
213
+ degraded,
214
+ });
215
+ }
216
+ if (!willAct(decision)) {
217
+ return finish({ effect: "none", ok: true, spoke: false, ref: null, error: null, degraded });
218
+ }
219
+
220
+ // 3. Observe-only: decide fully, act not at all. The proposal is the artefact.
221
+ if (decision.observeOnly === true) {
222
+ const r = await runEffect(effects.propose, "propose", { decision, candidate: o.candidate });
223
+ if (r.missing) {
224
+ degraded.push("propose_effect_missing");
225
+ log("warn", "observe-only decision had nowhere to be proposed — it is journal-only", { key: decision.key });
226
+ }
227
+ return finish({
228
+ effect: "propose",
229
+ ok: r.ok || r.missing, // a missing proposal sink is a degradation, not a failure to decide
230
+ spoke: false,
231
+ ref: r.ref,
232
+ error: r.error,
233
+ degraded,
234
+ });
235
+ }
236
+
237
+ const gates = decision.gates || {};
238
+
239
+ // 4. Blast radius. An `external | irreversible | financial` action is approved
240
+ // BEFORE any rung executes, rung 0 included.
241
+ if (gates.approval && gates.approval.required) {
242
+ const a = await runEffect(effects.requestApproval, "requestApproval", {
243
+ decision,
244
+ candidate: o.candidate,
245
+ classes: gates.approval.classes,
246
+ });
247
+ if (a.missing) {
248
+ // No approval channel wired and the action is gated: the ONLY safe answer
249
+ // is not to do it. Fail closed here — this is the one place in the file
250
+ // where failing open would let an agent email the world unsupervised.
251
+ degraded.push("approval_effect_missing");
252
+ log("error", "gated action with no approval channel wired → refusing to execute", {
253
+ key: decision.key,
254
+ classes: gates.approval.classes,
255
+ });
256
+ return finish({
257
+ effect: "approval",
258
+ ok: false,
259
+ spoke: false,
260
+ ref: null,
261
+ error: "gated action with no approval channel",
262
+ degraded,
263
+ });
264
+ }
265
+ if (!a.ok) {
266
+ log("warn", "approval request failed → holding the action", { key: decision.key, error: a.error });
267
+ return finish({ effect: "approval", ok: false, spoke: false, ref: a.ref, error: a.error, degraded });
268
+ }
269
+ const granted = a.ref && typeof a.ref === "object" ? a.ref.granted : undefined;
270
+ if (granted === false) {
271
+ log("warn", "approval declined → the action does not run", { key: decision.key });
272
+ return finish({ effect: "approval", ok: true, spoke: false, ref: a.ref, error: null, degraded });
273
+ }
274
+ if (granted !== true) {
275
+ // Pending is a legitimate terminal state for this pass: the approval will
276
+ // arrive as its own inbound event and re-enter the ladder.
277
+ degraded.push("approval_pending");
278
+ return finish({ effect: "approval", ok: true, spoke: false, ref: a.ref, error: null, degraded });
279
+ }
280
+ }
281
+
282
+ // 5. Thread arbitration. Exactly one agent answers a shared thread. Fails OPEN
283
+ // on a 3s timeout (a down coordination plane must not silence the agent),
284
+ // and the fail-open is recorded rather than assumed.
285
+ if (gates.arbitration) {
286
+ const t = await runEffect(effects.arbitrate, "arbitrate", {
287
+ decision,
288
+ candidate: o.candidate,
289
+ scope: gates.arbitration.scope,
290
+ resource: gates.arbitration.resource,
291
+ });
292
+ if (t.missing) {
293
+ degraded.push("arbitration_effect_missing");
294
+ log("warn", "no arbitration wired for a shared-thread reply — risking a double answer", {
295
+ key: decision.key,
296
+ });
297
+ } else if (!t.ok) {
298
+ degraded.push("arbitration_failed_open");
299
+ log("warn", "arbitration call failed → proceeding fail-open", { key: decision.key, error: t.error });
300
+ } else {
301
+ const may = t.ref && typeof t.ref === "object" ? t.ref.mayReply : true;
302
+ if (t.ref && t.ref.failedOpen) {
303
+ degraded.push("arbitration_failed_open");
304
+ log("warn", "arbitration timed out → proceeding fail-open", { key: decision.key });
305
+ }
306
+ if (may === false) {
307
+ log("warn", "another agent holds this thread → standing down", { key: decision.key });
308
+ return finish({
309
+ effect: "arbitration",
310
+ ok: true,
311
+ spoke: false,
312
+ ref: t.ref,
313
+ error: null,
314
+ degraded,
315
+ });
316
+ }
317
+ }
318
+ }
319
+
320
+ // 6. The effect.
321
+ const name = EFFECT_FOR[decision.disposition] || null;
322
+ if (!name) {
323
+ log("error", `no effect mapping for disposition ${decision.disposition}`, { key: decision.key });
324
+ return finish({
325
+ effect: null,
326
+ ok: false,
327
+ spoke: false,
328
+ ref: null,
329
+ error: `unmapped disposition ${decision.disposition}`,
330
+ degraded,
331
+ });
332
+ }
333
+ const r = await runEffect(effects[name], name, { decision, candidate: o.candidate });
334
+ if (r.missing) {
335
+ degraded.push(`${name}_effect_missing`);
336
+ log("error", `no \`${name}\` effect wired — the event was decided but not acted on`, { key: decision.key });
337
+ } else if (!r.ok) {
338
+ log("error", `${name} effect failed`, { key: decision.key, error: r.error });
339
+ }
340
+
341
+ return finish({
342
+ effect: name,
343
+ ok: r.ok,
344
+ spoke: r.ok && SPEAKING.includes(decision.disposition),
345
+ ref: r.ref,
346
+ error: r.error,
347
+ degraded,
348
+ costCents: r.ref && typeof r.ref === "object" ? r.ref.costCents : undefined,
349
+ });
350
+ }
351
+
352
+ export default { drive, EFFECT_FOR };
@@ -0,0 +1,270 @@
1
+ /**
2
+ * drive.test.mjs — sequencing, gates, and the fail-open-but-never-silent rule.
3
+ * Run: node --test lib/execution/drive.test.mjs
4
+ */
5
+ "use strict";
6
+
7
+ import { test } from "node:test";
8
+ import assert from "node:assert/strict";
9
+
10
+ import { drive, EFFECT_FOR } from "./drive.mjs";
11
+
12
+ const NOW = Date.parse("2026-08-11T12:00:00Z");
13
+
14
+ /**
15
+ * Collect journal rows instead of writing them, and swallow nothing.
16
+ *
17
+ * Overrides are WRAPPED in the same recorder as the defaults — an override that
18
+ * forgot to record would make `names()` silently under-report and turn a real
19
+ * assertion into a false pass. Passing `undefined` for a key removes the effect
20
+ * entirely (that is how the "not wired" cases are expressed).
21
+ */
22
+ function harness(over = {}) {
23
+ const rows = [];
24
+ const logs = [];
25
+ const calls = [];
26
+ const defaults = {
27
+ react: async () => ({ ok: true, ref: { messageId: "m1" } }),
28
+ schedule: async () => ({ ok: true, ref: { id: "q1" } }),
29
+ delegate: async () => ({ ok: true, ref: { id: "h1" } }),
30
+ escalate: async () => ({ ok: true, ref: { id: "e1" } }),
31
+ propose: async () => ({ ok: true, ref: { proposed: true } }),
32
+ requestApproval: async () => ({ ok: true, ref: { granted: true } }),
33
+ arbitrate: async () => ({ ok: true, ref: { mayReply: true } }),
34
+ reportDrift: async () => ({ ok: true }),
35
+ };
36
+ const effects = {};
37
+ for (const name of Object.keys(defaults)) {
38
+ const impl = Object.prototype.hasOwnProperty.call(over, name) ? over[name] : defaults[name];
39
+ if (typeof impl !== "function") continue; // explicitly "not wired"
40
+ effects[name] = async (a) => { calls.push([name, a]); return impl(a); };
41
+ }
42
+ return {
43
+ rows, logs, calls, effects,
44
+ opts: {
45
+ effects,
46
+ nowMs: NOW,
47
+ append: (_p, r) => { rows.push(r); return true; },
48
+ log: (level, msg, attrs) => logs.push({ level, msg, attrs }),
49
+ candidate: { ids: { channelId: "c1" }, entityId: "m1" },
50
+ },
51
+ names: () => calls.map((c) => c[0]),
52
+ };
53
+ }
54
+
55
+ const REACT = {
56
+ key: "messaging.send#1", thread: "messaging:c1:m1", surface: "dm",
57
+ disposition: "react_now", reason: "directed_now", why: ["directed"], rung: 0, gates: {},
58
+ };
59
+
60
+ test("the decision is journaled BEFORE the effect runs", async () => {
61
+ const h = harness({
62
+ react: async () => { assert.equal(h.rows.length, 1, "reasoning must be on disk before the side effect"); return { ok: true }; },
63
+ });
64
+ await drive(REACT, h.opts);
65
+ assert.equal(h.rows[0].event, "decision");
66
+ assert.equal(h.rows[1].event, "outcome");
67
+ });
68
+
69
+ test("each disposition invokes its own effect, and only that one", async () => {
70
+ for (const [disposition, effect] of Object.entries(EFFECT_FOR)) {
71
+ const h = harness();
72
+ await drive({ ...REACT, disposition, gates: {} }, h.opts);
73
+ assert.deepEqual(h.names(), [effect], `${disposition} → ${effect}`);
74
+ }
75
+ });
76
+
77
+ test("an ignore is RECORDED as a completed outcome, not skipped", async () => {
78
+ const h = harness();
79
+ const r = await drive({ ...REACT, disposition: "ignore", reason: "duplicate" }, h.opts);
80
+ assert.equal(r.ok, true);
81
+ assert.equal(r.effect, "none");
82
+ assert.equal(r.spoke, false);
83
+ assert.deepEqual(h.names(), [], "no effect runs");
84
+ assert.equal(h.rows.length, 2, "but both the decision and the outcome are written");
85
+ assert.equal(h.rows[1].disposition, "ignore");
86
+ assert.equal(h.rows[1].ok, true, "an ignore is a success, not a failure");
87
+ });
88
+
89
+ test("`spoke` is true only when the agent actually replied", async () => {
90
+ const spoke = await drive(REACT, harness().opts);
91
+ assert.equal(spoke.spoke, true);
92
+ for (const d of ["schedule", "delegate", "escalate"]) {
93
+ const r = await drive({ ...REACT, disposition: d }, harness().opts);
94
+ assert.equal(r.spoke, false, `${d} does not deepen a reply chain`);
95
+ }
96
+ });
97
+
98
+ test("a failed effect does not count as speaking", async () => {
99
+ const h = harness({ react: async () => ({ ok: false, error: "network down" }) });
100
+ const r = await drive(REACT, h.opts);
101
+ assert.equal(r.ok, false);
102
+ assert.equal(r.spoke, false, "a failed send must not gag the next attempt via the chain guard");
103
+ });
104
+
105
+ // ── gates ──────────────────────────────────────────────────────────────────
106
+
107
+ test("a gated action is approved BEFORE the effect runs", async () => {
108
+ const h = harness();
109
+ await drive({ ...REACT, gates: { approval: { required: true, classes: ["external"] } } }, h.opts);
110
+ assert.deepEqual(h.names(), ["requestApproval", "react"]);
111
+ assert.deepEqual(h.calls[0][1].classes, ["external"]);
112
+ });
113
+
114
+ test("a DECLINED approval stops the action, and is not an error", async () => {
115
+ const h = harness({ requestApproval: async () => ({ ok: true, ref: { granted: false } }) });
116
+ const r = await drive({ ...REACT, gates: { approval: { required: true, classes: ["financial"] } } }, h.opts);
117
+ assert.deepEqual(h.names(), ["requestApproval"]);
118
+ assert.equal(r.ok, true, "a human saying no is a working system");
119
+ assert.equal(r.spoke, false);
120
+ });
121
+
122
+ test("a PENDING approval ends the pass without acting", async () => {
123
+ const h = harness({ requestApproval: async () => ({ ok: true, ref: { granted: undefined, id: "ap1" } }) });
124
+ const r = await drive({ ...REACT, gates: { approval: { required: true, classes: ["external"] } } }, h.opts);
125
+ assert.deepEqual(h.names(), ["requestApproval"]);
126
+ assert.ok(r.degraded.includes("approval_pending"));
127
+ });
128
+
129
+ test("a gated action with NO approval channel FAILS CLOSED and screams", async () => {
130
+ // The one place fail-open would let an agent email the world unsupervised.
131
+ const h = harness({ requestApproval: undefined });
132
+ const r = await drive({ ...REACT, gates: { approval: { required: true, classes: ["external"] } } }, h.opts);
133
+ assert.equal(r.ok, false);
134
+ assert.deepEqual(h.names(), [], "the action never ran");
135
+ assert.ok(h.logs.some((l) => l.level === "error" && /no approval channel/.test(l.msg)));
136
+ });
137
+
138
+ test("a failed approval REQUEST holds the action rather than proceeding", async () => {
139
+ const h = harness({ requestApproval: async () => { throw new Error("hq unreachable"); } });
140
+ const r = await drive({ ...REACT, gates: { approval: { required: true, classes: ["irreversible"] } } }, h.opts);
141
+ assert.equal(r.ok, false);
142
+ assert.deepEqual(h.names(), ["requestApproval"], "it asked, and stopped when asking failed");
143
+ assert.equal(h.names().includes("react"), false, "the gated action must NOT run unapproved");
144
+ assert.match(r.error, /hq unreachable/);
145
+ });
146
+
147
+ test("losing the thread lease stands the agent down, quietly and correctly", async () => {
148
+ const h = harness({ arbitrate: async () => ({ ok: true, ref: { mayReply: false } }) });
149
+ const r = await drive({ ...REACT, gates: { arbitration: { scope: "thread-ownership", resource: "t" } } }, h.opts);
150
+ assert.deepEqual(h.names(), ["arbitrate"]);
151
+ assert.equal(r.spoke, false);
152
+ assert.equal(r.ok, true, "another agent answering is a working system");
153
+ });
154
+
155
+ test("arbitration FAILS OPEN — a down coordination plane must not silence the agent", async () => {
156
+ for (const arbitrate of [
157
+ async () => { throw new Error("timeout"); },
158
+ async () => ({ ok: true, ref: { mayReply: true, failedOpen: true } }),
159
+ ]) {
160
+ const h = harness({ arbitrate });
161
+ const r = await drive({ ...REACT, gates: { arbitration: { scope: "thread-ownership" } } }, h.opts);
162
+ assert.ok(h.names().includes("react"), "the agent still answered");
163
+ assert.ok(r.degraded.includes("arbitration_failed_open"));
164
+ assert.ok(h.logs.length > 0, "and the fail-open was LOGGED, not assumed");
165
+ }
166
+ });
167
+
168
+ test("gates run in order: approval, then arbitration, then the effect", async () => {
169
+ const h = harness();
170
+ await drive({
171
+ ...REACT,
172
+ gates: { approval: { required: true, classes: ["external"] }, arbitration: { scope: "thread-ownership" } },
173
+ }, h.opts);
174
+ assert.deepEqual(h.names(), ["requestApproval", "arbitrate", "react"]);
175
+ });
176
+
177
+ // ── observe-only + drift ───────────────────────────────────────────────────
178
+
179
+ test("observe-only proposes instead of acting", async () => {
180
+ const h = harness();
181
+ const r = await drive({ ...REACT, observeOnly: true }, h.opts);
182
+ assert.deepEqual(h.names(), ["propose"]);
183
+ assert.equal(r.effect, "propose");
184
+ assert.equal(r.spoke, false);
185
+ });
186
+
187
+ test("observe-only with no proposal sink degrades loudly but still decides", async () => {
188
+ const h = harness({ propose: undefined });
189
+ const r = await drive({ ...REACT, observeOnly: true }, h.opts);
190
+ assert.equal(r.ok, true);
191
+ assert.ok(r.degraded.includes("propose_effect_missing"));
192
+ assert.ok(h.logs.some((l) => /nowhere to be proposed/.test(l.msg)));
193
+ });
194
+
195
+ test("drift is reported even on an ignore path, and never blocks the action", async () => {
196
+ const stale = { ...REACT, disposition: "ignore", reason: "mandate_stale", drift: { kind: "mandate_stale" } };
197
+ const h1 = harness();
198
+ await drive(stale, h1.opts);
199
+ assert.deepEqual(h1.names(), ["reportDrift"]);
200
+
201
+ // A failing drift report must not stop real work.
202
+ const h2 = harness({ reportDrift: async () => { throw new Error("disk full"); } });
203
+ const r = await drive({ ...REACT, drift: { kind: "uncovered_event" } }, h2.opts);
204
+ assert.ok(h2.names().includes("react"), "the reply still went out");
205
+ assert.ok(r.degraded.some((d) => /drift_report_failed/.test(d)));
206
+ assert.ok(h2.logs.some((l) => /drift report failed/.test(l.msg)));
207
+ });
208
+
209
+ // ── failure modes ──────────────────────────────────────────────────────────
210
+
211
+ test("a missing effect is an ERROR, never a silent successful no-op", async () => {
212
+ const h = harness({ react: undefined });
213
+ const r = await drive(REACT, h.opts);
214
+ assert.equal(r.ok, false, "a missing responder is an outage, not a no-op");
215
+ assert.ok(r.degraded.includes("react_effect_missing"));
216
+ assert.ok(h.logs.some((l) => l.level === "error" && /no `react` effect wired/.test(l.msg)));
217
+ assert.equal(h.rows[1].ok, false, "and the journal records the failure");
218
+ });
219
+
220
+ test("a throwing effect is captured, journaled, and does not propagate", async () => {
221
+ const h = harness({ schedule: async () => { throw new Error("disk full"); } });
222
+ const r = await drive({ ...REACT, disposition: "schedule" }, h.opts);
223
+ assert.equal(r.ok, false);
224
+ assert.match(r.error, /disk full/);
225
+ assert.equal(h.rows[1].error, "disk full");
226
+ assert.ok(h.logs.some((l) => l.level === "error"));
227
+ });
228
+
229
+ test("an effect returning a bare value is treated as success", async () => {
230
+ const h = harness({ schedule: async () => "queued-1" });
231
+ const r = await drive({ ...REACT, disposition: "schedule" }, h.opts);
232
+ assert.equal(r.ok, true);
233
+ assert.equal(r.ref, "queued-1");
234
+ });
235
+
236
+ test("decision-level degradations are logged, not just carried", async () => {
237
+ const h = harness();
238
+ await drive({ ...REACT, degraded: ["history_absent", "unknown_surface:x"] }, h.opts);
239
+ assert.equal(h.logs.filter((l) => /decision degraded/.test(l.msg)).length, 2);
240
+ });
241
+
242
+ test("a journal write failure is reported but does not abort the action", async () => {
243
+ const h = harness();
244
+ const r = await drive(REACT, { ...h.opts, append: () => false });
245
+ assert.ok(h.names().includes("react"), "the work still happened");
246
+ assert.ok(r.degraded.includes("journal_decision_write_failed"));
247
+ assert.ok(h.logs.some((l) => l.level === "error" && /unexplained/.test(l.msg)));
248
+ });
249
+
250
+ test("drive with no decision is an error, not a crash", async () => {
251
+ for (const d of [null, undefined, "nonsense", 42]) {
252
+ const r = await drive(d, harness().opts);
253
+ assert.equal(r.ok, false);
254
+ assert.equal(r.error, "no decision");
255
+ }
256
+ });
257
+
258
+ test("an unmapped disposition fails loudly instead of doing nothing", async () => {
259
+ const h = harness();
260
+ const r = await drive({ ...REACT, disposition: "teleport" }, h.opts);
261
+ assert.equal(r.ok, false);
262
+ assert.match(r.error, /unmapped disposition/);
263
+ });
264
+
265
+ test("with no effects wired at all, nothing throws and everything is recorded", async () => {
266
+ const rows = [];
267
+ const r = await drive(REACT, { effects: {}, nowMs: NOW, append: (_p, x) => { rows.push(x); return true; }, log: () => {} });
268
+ assert.equal(r.ok, false);
269
+ assert.equal(rows.length, 2);
270
+ });