@cohortapp/agent-sdk 2.3.1 → 2.4.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 (162) hide show
  1. package/bin/maestro.mjs +37 -50
  2. package/framework-features.json +30 -0
  3. package/lib/backlog.mjs +136 -0
  4. package/lib/cadences.mjs +63 -2
  5. package/lib/cadences.test.mjs +105 -0
  6. package/lib/capability/inventory.mjs +542 -0
  7. package/lib/capability/inventory.test.mjs +232 -0
  8. package/lib/capability/probe.mjs +255 -0
  9. package/lib/channels/contract.mjs +37 -1
  10. package/lib/channels/contract.test.mjs +25 -1
  11. package/lib/channels/inbox-item.mjs +20 -0
  12. package/lib/claude-bin.mjs +37 -3
  13. package/lib/claude-bin.test.mjs +42 -8
  14. package/lib/execution/disposition.mjs +501 -0
  15. package/lib/execution/disposition.test.mjs +482 -0
  16. package/lib/execution/drive.mjs +352 -0
  17. package/lib/execution/drive.test.mjs +270 -0
  18. package/lib/execution/effects.mjs +340 -0
  19. package/lib/execution/effects.test.mjs +193 -0
  20. package/lib/execution/index.mjs +152 -0
  21. package/lib/execution/intake.mjs +581 -0
  22. package/lib/execution/intake.test.mjs +343 -0
  23. package/lib/execution/journal.mjs +374 -0
  24. package/lib/execution/journal.test.mjs +261 -0
  25. package/lib/execution/match.mjs +331 -0
  26. package/lib/execution/match.test.mjs +235 -0
  27. package/lib/execution/pipeline.mjs +341 -0
  28. package/lib/execution/pipeline.test.mjs +389 -0
  29. package/lib/execution/route.mjs +332 -0
  30. package/lib/execution/route.test.mjs +186 -0
  31. package/lib/execution/surface-policy.mjs +446 -0
  32. package/lib/execution/surface-policy.test.mjs +162 -0
  33. package/lib/goals/admission.mjs +209 -0
  34. package/lib/goals/admission.test.mjs +139 -0
  35. package/lib/goals/classify.mjs +206 -0
  36. package/lib/goals/classify.test.mjs +109 -0
  37. package/lib/goals/collaborate.mjs +415 -0
  38. package/lib/goals/collaborate.test.mjs +324 -0
  39. package/lib/goals/gaps.mjs +111 -0
  40. package/lib/goals/gaps.test.mjs +284 -0
  41. package/lib/goals/loop.mjs +537 -0
  42. package/lib/goals/loop.test.mjs +719 -0
  43. package/lib/identity/persona.mjs +247 -0
  44. package/lib/identity/persona.test.mjs +117 -0
  45. package/lib/kpi.mjs +469 -0
  46. package/lib/kpi.test.mjs +244 -0
  47. package/lib/mandate/audit.mjs +168 -0
  48. package/lib/mandate/audit.test.mjs +195 -0
  49. package/lib/mandate/cache.mjs +162 -0
  50. package/lib/mandate/derive.mjs +317 -0
  51. package/lib/mandate/derive.test.mjs +224 -0
  52. package/lib/mandate/model.mjs +352 -0
  53. package/lib/mandate/model.test.mjs +145 -0
  54. package/lib/mandate/refresh.mjs +187 -0
  55. package/lib/mandate/refresh.test.mjs +293 -0
  56. package/lib/mcp/server.test.mjs +4 -4
  57. package/lib/org/approvals.mjs +14 -2
  58. package/lib/org/client.mjs +79 -25
  59. package/lib/org/client.test.mjs +54 -1
  60. package/lib/org/doctor.mjs +64 -0
  61. package/lib/org/doctor.test.mjs +31 -2
  62. package/lib/org/inbound/directedness.mjs +720 -0
  63. package/lib/org/inbound/directedness.test.mjs +543 -0
  64. package/lib/org/inbound/facts.mjs +501 -0
  65. package/lib/org/inbound/facts.test.mjs +375 -0
  66. package/lib/org/inbound/hydrate.mjs +535 -0
  67. package/lib/org/inbound/hydrate.test.mjs +326 -0
  68. package/lib/org/inbound/index.mjs +233 -0
  69. package/lib/org/inbound/index.test.mjs +324 -0
  70. package/lib/org/inbound/io.mjs +141 -0
  71. package/lib/org/inbound/project.mjs +201 -0
  72. package/lib/org/inbound/project.test.mjs +287 -0
  73. package/lib/org/inbound/surfaces.mjs +257 -0
  74. package/lib/org/knowledge.mjs +10 -1
  75. package/lib/org/knowledge.test.mjs +8 -1
  76. package/lib/org/leases.mjs +5 -0
  77. package/lib/org/mesh.mjs +45 -2
  78. package/lib/org/mesh.test.mjs +55 -0
  79. package/lib/org/messaging.mjs +180 -15
  80. package/lib/org/messaging.test.mjs +117 -0
  81. package/lib/org/param-contract.mjs +694 -0
  82. package/lib/org/param-contract.test.mjs +451 -0
  83. package/lib/org/protocol.checksum +1 -1
  84. package/lib/org/protocol.mjs +8 -0
  85. package/lib/org/protocol.test.mjs +5 -1
  86. package/lib/org/push.mjs +1025 -0
  87. package/lib/org/push.test.mjs +690 -0
  88. package/lib/org/tool-surface.mjs +138 -38
  89. package/lib/org/tool-surface.test.mjs +13 -8
  90. package/lib/org/typing.mjs +341 -0
  91. package/lib/org/typing.test.mjs +291 -0
  92. package/lib/plan/compile.mjs +510 -0
  93. package/lib/plan/compile.test.mjs +286 -0
  94. package/lib/plan/emit.mjs +256 -0
  95. package/lib/plan/emit.test.mjs +246 -0
  96. package/lib/plan/explain.mjs +226 -0
  97. package/lib/plan/explain.test.mjs +188 -0
  98. package/lib/plan/schema.mjs +140 -0
  99. package/lib/resource-governor.mjs +47 -1
  100. package/lib/resource-governor.test.mjs +21 -1
  101. package/lib/setup/enroll-from-cohort.mjs +84 -16
  102. package/lib/setup/enroll-from-cohort.test.mjs +43 -1
  103. package/lib/setup/sections/identity.mjs +15 -4
  104. package/lib/setup/sections/identity.test.mjs +94 -0
  105. package/lib/setup/sections/inventory.mjs +178 -0
  106. package/lib/setup/sections/inventory.test.mjs +198 -0
  107. package/lib/setup/sections/mandate.mjs +392 -0
  108. package/lib/setup/sections/mandate.test.mjs +373 -0
  109. package/lib/setup/sections/subagents.mjs +427 -0
  110. package/lib/setup/sections/subagents.test.mjs +429 -0
  111. package/lib/setup/sections/verify.mjs +121 -0
  112. package/lib/setup/sections/verify.test.mjs +175 -0
  113. package/lib/setup/sot.mjs +2 -0
  114. package/lib/subagents/cli.mjs +463 -0
  115. package/lib/subagents/cli.test.mjs +389 -0
  116. package/lib/subagents/client.mjs +373 -0
  117. package/lib/subagents/client.test.mjs +309 -0
  118. package/lib/subagents/gap.mjs +268 -0
  119. package/lib/subagents/gap.test.mjs +234 -0
  120. package/lib/subagents/lock.mjs +296 -0
  121. package/lib/subagents/lock.test.mjs +248 -0
  122. package/lib/subagents/manifest.mjs +224 -0
  123. package/lib/subagents/manifest.test.mjs +175 -0
  124. package/lib/subagents/refs.mjs +274 -0
  125. package/lib/subagents/refs.test.mjs +204 -0
  126. package/lib/subagents/resolve.mjs +455 -0
  127. package/lib/subagents/resolve.test.mjs +422 -0
  128. package/lib/subagents/schema.mjs +467 -0
  129. package/lib/subagents/schema.test.mjs +306 -0
  130. package/package.json +9 -4
  131. package/plugins/maestro-skills/.claude-plugin/marketplace.json +16 -0
  132. package/policies/ai-disclosure.yaml +42 -2
  133. package/scaffold/CLAUDE.md +16 -2
  134. package/schedules/triggers/goal-steward.md +79 -0
  135. package/scripts/ci/conformance-org-api.mjs +792 -0
  136. package/scripts/ci/conformance-org-api.test.mjs +417 -0
  137. package/scripts/daemon/agent-daemon.mjs +70 -11
  138. package/scripts/daemon/cadence-handlers.mjs +187 -5
  139. package/scripts/daemon/goal-steward-cadence.test.mjs +243 -0
  140. package/scripts/daemon/inbox-deferral.mjs +45 -2
  141. package/scripts/daemon/inbox-deferral.test.mjs +56 -0
  142. package/scripts/daemon/inbox-wake.mjs +282 -0
  143. package/scripts/daemon/inbox-wake.test.mjs +199 -0
  144. package/scripts/daemon/maestro-daemon.mjs +23 -0
  145. package/scripts/daemon/prompt-builder.mjs +41 -1
  146. package/scripts/daemon/responder.mjs +56 -0
  147. package/scripts/daemon/typing-registry.mjs +55 -2
  148. package/scripts/daemon/typing-registry.test.mjs +25 -0
  149. package/scripts/local-triggers/generate-plists.test.mjs +5 -5
  150. package/scripts/poller/inbox-scan-poller.mjs +26 -1
  151. package/scripts/poller/inbox-scan-poller.test.mjs +64 -0
  152. package/scripts/poller/slack-cloud-relay-client.mjs +5 -0
  153. package/scripts/poller/slack-poller.mjs +32 -0
  154. package/scripts/poller/slack-socket-mode.mjs +27 -1
  155. package/scripts/poller/slack-socket-mode.test.mjs +52 -0
  156. package/scripts/poller/utils.mjs +47 -0
  157. package/scripts/setup/gen-subagent-manifest.mjs +95 -0
  158. package/scripts/setup/gen-subagent-manifest.test.mjs +124 -0
  159. package/scripts/setup/generate-plan.mjs +108 -0
  160. package/scripts/setup/init-capability-manifest.mjs +70 -0
  161. package/scripts/setup/init-skill-marketplace.mjs +155 -0
  162. package/scripts/setup/init-skill-marketplace.test.mjs +193 -0
@@ -0,0 +1,417 @@
1
+ /**
2
+ * conformance-org-api.test.mjs — the PURE parts of the live conformance probe.
3
+ *
4
+ * The probe's value rests entirely on one judgement: given an hq error frame,
5
+ * is this WIRE-CONTRACT DRIFT (fail) or a legitimate refusal (skip/warn)? Get
6
+ * that wrong in the lenient direction and the probe is decorative; get it wrong
7
+ * in the strict direction and nobody will keep it in CI. So `classifyFrame` and
8
+ * `citedParams` are tested against the ACTUAL error strings hq's handlers emit
9
+ * — including the real message from every P0 row of the 2026-08 audit.
10
+ *
11
+ * Hermetic: no network, no disk, no credentials. The runner is exercised through
12
+ * injected `callImpl`/`readImpl`.
13
+ *
14
+ * Run: node --test scripts/ci/conformance-org-api.test.mjs
15
+ */
16
+
17
+ "use strict";
18
+
19
+ import { test } from "node:test";
20
+ import assert from "node:assert/strict";
21
+
22
+ import {
23
+ classifyFrame,
24
+ citedParams,
25
+ buildProbes,
26
+ parseArgs,
27
+ probeSelected,
28
+ runProbes,
29
+ referencesGhost,
30
+ wireBodyFor,
31
+ uncoveredContractMethods,
32
+ ghostId,
33
+ SCHEMA_PASSED_CODES,
34
+ } from "./conformance-org-api.mjs";
35
+ import { PARAM_CONTRACT } from "../../lib/org/param-contract.mjs";
36
+ import { methodDef } from "../../lib/org/protocol.mjs";
37
+
38
+ const err = (code, message) => ({ ok: false, error: { code, message } });
39
+ const probe = (method) => ({ method, params: {} });
40
+
41
+ // ═══════════════════════════════════════════════════════════════════════════
42
+ // citedParams — parsing hq's four error dialects
43
+ // ═══════════════════════════════════════════════════════════════════════════
44
+
45
+ test("citedParams: zod path prefix (the `parse()` helper's shape)", () => {
46
+ assert.deepEqual(citedParams("channelId: Required").cited, ["channelId"]);
47
+ assert.deepEqual(citedParams("itemId: itemId is required").cited, ["itemId"]);
48
+ // A nested path reports its ROOT — that is the key the caller controls.
49
+ assert.deepEqual(citedParams("participantIds.0: Expected string").cited, ["participantIds"]);
50
+ });
51
+
52
+ test("citedParams: zod .strict() unrecognized keys", () => {
53
+ const r = citedParams("Unrecognized key(s) in object: 'note', 'stray'");
54
+ assert.deepEqual(r.unrecognized.sort(), ["note", "stray"]);
55
+ });
56
+
57
+ test("citedParams: hq's hand-written guards", () => {
58
+ assert.ok(citedParams("title is required").cited.includes("title"));
59
+ assert.ok(citedParams("actionClass is required").cited.includes("actionClass"));
60
+ assert.ok(citedParams("memoryClass must be one of: framework, ledger").cited.includes("memoryClass"));
61
+ assert.ok(citedParams("payloadHash must be a sha-256 hex digest").cited.includes("payloadHash"));
62
+ });
63
+
64
+ test("citedParams: a message naming nothing yields nothing (never invents a field)", () => {
65
+ assert.deepEqual(citedParams("an escalation must reference a task or a channel").unrecognized, []);
66
+ assert.deepEqual(citedParams("").cited, []);
67
+ assert.deepEqual(citedParams(null).cited, []);
68
+ });
69
+
70
+ // ═══════════════════════════════════════════════════════════════════════════
71
+ // classifyFrame — the discriminator
72
+ // ═══════════════════════════════════════════════════════════════════════════
73
+
74
+ test("ok:true → pass", () => {
75
+ assert.equal(classifyFrame(probe("member.get"), { slug: "x" }, { ok: true, result: {} }).verdict, "pass");
76
+ });
77
+
78
+ test("every legitimate-refusal code → skip, NOT fail (the schema was accepted)", () => {
79
+ for (const code of SCHEMA_PASSED_CODES) {
80
+ const v = classifyFrame(probe("board.claim"), { itemId: "i" }, err(code, "nope"));
81
+ assert.equal(v.verdict, "skip", `${code} must not be reported as drift`);
82
+ }
83
+ });
84
+
85
+ test("a non-BAD_REQUEST failure (INTERNAL/5xx) → warn, never a silent pass", () => {
86
+ const v = classifyFrame(probe("board.claim"), { itemId: "i" }, err("INTERNAL", "boom"));
87
+ assert.equal(v.verdict, "warn");
88
+ });
89
+
90
+ test("a missing/garbled frame → warn, never a pass", () => {
91
+ assert.equal(classifyFrame(probe("x.y"), {}, null).verdict, "warn");
92
+ assert.equal(classifyFrame(probe("x.y"), {}, undefined).verdict, "warn");
93
+ });
94
+
95
+ // ── the FAIL cases: this is the drift the audit found ──────────────────────
96
+
97
+ test("DRIFT: hq requires a name we never send → fail (the messaging.send P0)", () => {
98
+ // What hq actually returned while the SDK minted `clientMsgId`.
99
+ const v = classifyFrame(
100
+ probe("messaging.send"),
101
+ { channelId: "C1", body: "hi", clientMsgId: "cm-1" },
102
+ err("BAD_REQUEST", "idempotencyId: Required"),
103
+ );
104
+ assert.equal(v.verdict, "fail");
105
+ assert.match(v.reason, /idempotencyId/);
106
+ });
107
+
108
+ test("DRIFT: hq's .strict() schema rejects a key we DO send → fail (the board.complete P0)", () => {
109
+ const v = classifyFrame(
110
+ probe("board.complete"),
111
+ { itemId: "i-1", note: "done" },
112
+ err("BAD_REQUEST", "Unrecognized key(s) in object: 'note'"),
113
+ );
114
+ assert.equal(v.verdict, "fail");
115
+ assert.match(v.reason, /REJECTS the param name/);
116
+ assert.match(v.reason, /note/);
117
+ });
118
+
119
+ test("DRIFT: the registry.register P0 — a raw self-entry into a strict schema", () => {
120
+ const v = classifyFrame(
121
+ probe("registry.register"),
122
+ { id: "A016", name: "isla", towers: ["eng"] },
123
+ err("BAD_REQUEST", "Unrecognized key(s) in object: 'id', 'name', 'towers'"),
124
+ );
125
+ assert.equal(v.verdict, "fail");
126
+ });
127
+
128
+ test("DRIFT: each remaining P0 hand-written guard is caught", () => {
129
+ const rows = [
130
+ ["escalation.create", { severity: "high", subject: "s", body: "b" }, "title is required", "title"],
131
+ ["approval.request", { kind: "external_comms", payload_hash: "x" }, "actionClass is required", "actionClass"],
132
+ ["decision.comment", { decisionId: "d", body: "b" }, "text is required", "text"],
133
+ ["member.get", { memberId: "m" }, "slug is required", "slug"],
134
+ ["memory.author", { content: "c", kind: "note" }, "memoryClass must be one of: framework, ledger", "memoryClass"],
135
+ ];
136
+ for (const [method, sent, message, expect] of rows) {
137
+ const v = classifyFrame(probe(method), sent, err("BAD_REQUEST", message));
138
+ assert.equal(v.verdict, "fail", `${method} must be flagged`);
139
+ assert.match(v.reason, new RegExp(expect), `${method} must name ${expect}`);
140
+ }
141
+ });
142
+
143
+ // ── the WARN case: a value complaint is not drift ──────────────────────────
144
+
145
+ test("NOT DRIFT: hq disliking the VALUE of a param we sent → warn", () => {
146
+ const v = classifyFrame(
147
+ probe("approval.request"),
148
+ { actionClass: "x", payloadHash: "not-a-hash" },
149
+ err("BAD_REQUEST", "payloadHash must be a sha-256 hex digest"),
150
+ );
151
+ assert.equal(v.verdict, "warn", "we send the right NAME; the probe's placeholder was the problem");
152
+ assert.match(v.reason, /probe placeholder/);
153
+ });
154
+
155
+ test("NOT DRIFT: a refine() that names no field → warn, not a false FAIL", () => {
156
+ const v = classifyFrame(
157
+ probe("escalation.create"),
158
+ { title: "t" },
159
+ err("BAD_REQUEST", "an escalation must reference a task or a channel"),
160
+ );
161
+ assert.equal(v.verdict, "warn");
162
+ });
163
+
164
+ test("a BAD_REQUEST we cannot parse is a warn — never an assumed pass", () => {
165
+ const v = classifyFrame(probe("x.y"), { a: 1 }, err("BAD_REQUEST", "computer says no"));
166
+ assert.equal(v.verdict, "warn");
167
+ assert.match(v.reason, /unparsed/);
168
+ });
169
+
170
+ // ═══════════════════════════════════════════════════════════════════════════
171
+ // the probe table — coverage + safety
172
+ // ═══════════════════════════════════════════════════════════════════════════
173
+
174
+ test("every probe names a real protocol method and declares its write posture", () => {
175
+ for (const p of buildProbes()) {
176
+ assert.ok(methodDef(p.method), `${p.method} is not in the vendored protocol table`);
177
+ assert.equal(typeof p.writes, "boolean", `${p.method} must declare writes`);
178
+ assert.ok(p.why && p.why.length > 8, `${p.method} must justify its safety posture`);
179
+ assert.ok(p.params && typeof p.params === "object", `${p.method} needs params`);
180
+ }
181
+ });
182
+
183
+ test("COVERAGE: every contracted method has a probe (a new contract row cannot ship unprobed)", () => {
184
+ assert.deepEqual(
185
+ uncoveredContractMethods(),
186
+ [],
187
+ "add a probe to buildProbes() for each new PARAM_CONTRACT entry",
188
+ );
189
+ });
190
+
191
+ test("SAFETY: every probe declares a guard, and a `ghost` guard really carries a ghost id", () => {
192
+ const GUARDS = new Set(["read", "ghost", "audit-only", "no-op", "write"]);
193
+ const offenders = [];
194
+ for (const p of buildProbes()) {
195
+ if (!GUARDS.has(p.guard)) {
196
+ offenders.push(`${p.method} declares no valid guard (got ${JSON.stringify(p.guard)})`);
197
+ continue;
198
+ }
199
+ if (p.writes && p.guard !== "write") offenders.push(`${p.method} writes but is not guarded "write"`);
200
+ if (!p.writes && p.guard === "write") offenders.push(`${p.method} is guarded "write" but claims writes:false`);
201
+ // The load-bearing one: a side-effecting method run BY DEFAULT is safe only
202
+ // because its target cannot exist.
203
+ if (p.guard === "ghost" && !referencesGhost(p.params)) {
204
+ offenders.push(`${p.method} claims guard "ghost" but its params carry no ghost id`);
205
+ }
206
+ // And nothing side-effecting may run by default under a "read" guard.
207
+ const def = methodDef(p.method);
208
+ if (p.guard === "read" && def && def.sideEffecting) {
209
+ offenders.push(`${p.method} is side-effecting but guarded "read"`);
210
+ }
211
+ }
212
+ assert.deepEqual(offenders, [], `unsafe probes:\n ${offenders.join("\n ")}`);
213
+ });
214
+
215
+ test("SAFETY: a create-or-upsert method is never guarded `ghost` — an unknown id CREATES", () => {
216
+ // REGRESSION. The `ghost` guard assumes the handler REQUIRES its entity to
217
+ // exist, so an impossible id makes a side-effecting probe harmless. That
218
+ // assumption inverts for create-or-upsert handlers: hq's knowledge.replace
219
+ // treats an unknown id as the CREATE branch and appends `knowledge.created`
220
+ // at version 1, so a ghost id GUARANTEES a durable row. It shipped declared
221
+ // `writes:false` and a read-only run created a junk fact in the live org.
222
+ //
223
+ // These methods are upserts on hq's side and must stay `--write`-gated.
224
+ const UPSERTS = ["knowledge.replace", "contacts.upsert", "meetings.record"];
225
+ const byMethod = new Map(buildProbes().map((p) => [p.method, p]));
226
+ for (const method of UPSERTS) {
227
+ const p = byMethod.get(method);
228
+ if (!p) continue; // coverage is asserted elsewhere
229
+ assert.equal(p.writes, true, `${method} is create-or-upsert: it must declare writes:true`);
230
+ assert.notEqual(p.guard, "ghost", `${method} is an upsert — a ghost id creates a row, it does not prevent one`);
231
+ }
232
+ });
233
+
234
+ test("SAFETY: no outbound-content probe is ever unguarded — a real send must be impossible", () => {
235
+ // messaging.send is probed, and is safe ONLY because its channel cannot exist.
236
+ const send = buildProbes().find((p) => p.method === "messaging.send");
237
+ assert.ok(send, "messaging.send IS probed — it was the worst drift row");
238
+ assert.equal(send.writes, false);
239
+ assert.equal(send.guard, "ghost");
240
+ assert.ok(referencesGhost(send.params), "the channel id must be a ghost or a message could be delivered");
241
+ // No probe touches the outbound email lane at all.
242
+ const emailSends = buildProbes().filter((p) => /^email\.(send|draftSend)$/.test(p.method));
243
+ assert.deepEqual(emailSends, [], "email sends are never probed");
244
+ });
245
+
246
+ test("SAFETY: ghost ids are unique per run, so a probe can never collide with real data", () => {
247
+ const a = ghostId("task");
248
+ const b = ghostId("task");
249
+ assert.notEqual(a, b);
250
+ assert.match(a, /^probe-task-[0-9a-f-]{36}$/, "the `probe-` marker is load-bearing for the safety test");
251
+ assert.equal(referencesGhost({ taskId: a }), true);
252
+ assert.equal(referencesGhost({ taskId: "t-real-123" }), false);
253
+ });
254
+
255
+ test("the probe payloads are already canonical — the contract rewrites nothing", () => {
256
+ // If a probe needed rewriting, it would be testing the contract against itself
257
+ // rather than against hq.
258
+ for (const p of buildProbes()) {
259
+ const sent = wireBodyFor(p.method, p.params);
260
+ for (const k of Object.keys(p.params)) {
261
+ assert.ok(k in sent, `${p.method}: probe param ${k} vanished`);
262
+ }
263
+ const c = PARAM_CONTRACT[p.method];
264
+ if (!c || !c.alias) continue;
265
+ for (const legacy of Object.keys(c.alias)) {
266
+ if (c.serverAccepts && c.serverAccepts.includes(legacy)) continue;
267
+ assert.ok(!(legacy in p.params), `${p.method}: probe uses the LEGACY name ${legacy}`);
268
+ }
269
+ }
270
+ });
271
+
272
+ test("every probe payload satisfies what hq requires (no self-inflicted BAD_REQUEST)", () => {
273
+ for (const p of buildProbes()) {
274
+ const sent = wireBodyFor(p.method, p.params);
275
+ const c = PARAM_CONTRACT[p.method];
276
+ if (!c) continue;
277
+ const missing = (c.required || []).filter((k) => sent[k] === undefined || sent[k] === "");
278
+ assert.deepEqual(missing, [], `${p.method} probe omits required ${missing.join(",")}`);
279
+ }
280
+ });
281
+
282
+ // ═══════════════════════════════════════════════════════════════════════════
283
+ // argv + filtering
284
+ // ═══════════════════════════════════════════════════════════════════════════
285
+
286
+ test("parseArgs: flags, --only list, --agent-root, and unknown-arg capture", () => {
287
+ const a = parseArgs(["--write", "--json", "-v", "--only=board, messaging", "--agent-root=/tmp/x"]);
288
+ assert.equal(a.write, true);
289
+ assert.equal(a.json, true);
290
+ assert.equal(a.verbose, true);
291
+ assert.deepEqual(a.only, ["board", "messaging"]);
292
+ assert.equal(a.agentRoot, "/tmp/x");
293
+ assert.deepEqual(a.bad, []);
294
+ assert.deepEqual(parseArgs(["--nope"]).bad, ["--nope"]);
295
+ assert.equal(parseArgs([]).write, false, "write is OFF by default");
296
+ });
297
+
298
+ test("probeSelected: no filter selects everything; a family filter narrows", () => {
299
+ const p = { method: "board.claim" };
300
+ assert.equal(probeSelected(p, []), true);
301
+ assert.equal(probeSelected(p, ["board"]), true);
302
+ assert.equal(probeSelected(p, ["messaging"]), false);
303
+ assert.equal(probeSelected(p, ["board.claim"]), true, "an exact method name also selects");
304
+ });
305
+
306
+ // ═══════════════════════════════════════════════════════════════════════════
307
+ // the runner (injected transport)
308
+ // ═══════════════════════════════════════════════════════════════════════════
309
+
310
+ test("runProbes: row-creating probes are SKIPPED without --write, and never dispatched", async () => {
311
+ const dispatched = [];
312
+ const callImpl = async (method) => {
313
+ dispatched.push(method);
314
+ return { ok: true, result: {} };
315
+ };
316
+ const readImpl = async () => ({ ok: true, payload: {} });
317
+ const { results } = await runProbes({ base: "https://x", token: "t", callImpl, readImpl });
318
+
319
+ const writers = buildProbes().filter((p) => p.writes).map((p) => p.method);
320
+ assert.ok(writers.length > 0, "there ARE row-creating probes to gate");
321
+ for (const m of writers) {
322
+ assert.ok(!dispatched.includes(m), `${m} must not be dispatched without --write`);
323
+ const row = results.find((r) => r.method === m);
324
+ assert.equal(row.verdict, "skip");
325
+ assert.match(row.reason, /--write/);
326
+ }
327
+ });
328
+
329
+ test("runProbes: --write dispatches the row-creating probes too", async () => {
330
+ const dispatched = [];
331
+ const callImpl = async (method) => {
332
+ dispatched.push(method);
333
+ return { ok: true, result: {} };
334
+ };
335
+ const readImpl = async () => ({ ok: true, payload: {} });
336
+ await runProbes({ base: "https://x", token: "t", write: true, callImpl, readImpl });
337
+ for (const p of buildProbes()) assert.ok(dispatched.includes(p.method), `${p.method} dispatched`);
338
+ });
339
+
340
+ test("runProbes: a BAD_REQUEST naming an unsent param surfaces as a failure", async () => {
341
+ // Simulates FUTURE drift: hq starts requiring a name this SDK does not send.
342
+ // (The historical bug was the mirror image — hq wanted `idempotencyId` while we
343
+ // sent `clientMsgId` — and the probe would have caught it identically.)
344
+ const callImpl = async (method) =>
345
+ method === "messaging.send" ? err("BAD_REQUEST", "conversationId: Required") : { ok: true, result: {} };
346
+ const readImpl = async () => ({ ok: true, payload: {} });
347
+ const { failures } = await runProbes({
348
+ base: "https://x",
349
+ token: "t",
350
+ only: ["messaging"],
351
+ callImpl,
352
+ readImpl,
353
+ });
354
+ assert.equal(failures.length, 1);
355
+ assert.equal(failures[0].method, "messaging.send");
356
+ });
357
+
358
+ test("runProbes: NOT_FOUND everywhere is a clean run — that is the expected shape", async () => {
359
+ const callImpl = async () => err("NOT_FOUND", "no such thing");
360
+ const readImpl = async () => ({ ok: true, payload: {} });
361
+ const { failures, results } = await runProbes({ base: "https://x", token: "t", callImpl, readImpl });
362
+ assert.deepEqual(failures, []);
363
+ assert.ok(results.every((r) => r.verdict === "skip"));
364
+ });
365
+
366
+ test("runProbes: a transport throw is contained as a warn, never an unhandled rejection", async () => {
367
+ const callImpl = async () => {
368
+ throw new Error("socket hang up");
369
+ };
370
+ const readImpl = async () => ({ ok: true, payload: {} });
371
+ const { results, failures } = await runProbes({
372
+ base: "https://x",
373
+ token: "t",
374
+ only: ["messaging"],
375
+ callImpl,
376
+ readImpl,
377
+ });
378
+ assert.deepEqual(failures, []);
379
+ assert.ok(results.every((r) => r.verdict === "warn"));
380
+ });
381
+
382
+ test("runProbes: a BAD_REQUEST on a GET read path is drift too", async () => {
383
+ const callImpl = async () => ({ ok: true, result: {} });
384
+ const readImpl = async (path) =>
385
+ path === "snapshot" ? { ok: false, error: { code: "BAD_REQUEST", message: "bad" }, status: 400 } : { ok: true, payload: {} };
386
+ const { reads, failures } = await runProbes({ base: "https://x", token: "t", only: ["reads"], callImpl, readImpl });
387
+ assert.ok(reads.length >= 12, "every read path probed");
388
+ assert.equal(failures.length, 1);
389
+ assert.equal(failures[0].path, "snapshot");
390
+ });
391
+
392
+ // ---------------------------------------------------------------------------
393
+ // A run that proved nothing must not report success
394
+ // ---------------------------------------------------------------------------
395
+
396
+ test("UNAUTHORIZED is a CREDENTIAL verdict, never a pass or a skip", () => {
397
+ // hq returns UNAUTHORIZED for a bad bearer key on every method and every GET
398
+ // read. It used to sit in SCHEMA_PASSED_CODES, so a rotated/revoked token made
399
+ // all 36 method probes `skip`, all 12 read paths `pass`, and the run print
400
+ // "No wire-contract drift." and exit 0 — green forever while probing nothing.
401
+ const v = classifyFrame(
402
+ { method: "board.createTask" },
403
+ {},
404
+ { ok: false, error: { code: "UNAUTHORIZED", message: "bad key" } },
405
+ );
406
+ assert.equal(v.verdict, "credential");
407
+ assert.match(v.reason, /nothing was tested/i);
408
+ });
409
+
410
+ test("a genuinely declined handler is still a skip (we did test the schema)", () => {
411
+ const v = classifyFrame(
412
+ { method: "board.createTask" },
413
+ {},
414
+ { ok: false, error: { code: "NOT_FOUND", message: "no such item" } },
415
+ );
416
+ assert.equal(v.verdict, "skip");
417
+ });
@@ -57,7 +57,8 @@ import { sendQuickResponse, sendHoldingMessage, isQuickReply } from "./responder
57
57
  import { recordPoll, recordClassification, recordSession, writeHealthDashboard } from "./health.mjs";
58
58
  import { acquireLock, releaseLock, updateLock, scanStaleLocks, acquireThreadLock, claimRequest, hasActiveClaim, sweepStaleItemClaims, sanitiseItemId } from "./session-lock.mjs";
59
59
  import { markDeferred } from "./inbox-deferral.mjs";
60
- import { parseQueueItems } from "../../lib/backlog.mjs";
60
+ import { parseQueueItems, rankBacklog, resolveBacklogWeights } from "../../lib/backlog.mjs";
61
+ import { readLatestGaps } from "../../lib/goals/gaps.mjs";
61
62
  // Org shared-memory write-back (central store via memory.author / knowledge.append
62
63
  // RPC). After a daemon turn completes cleanly we distil a one-line record of the
63
64
  // work and land it in the org's shared, ACL'd store so the fleet's memory
@@ -120,19 +121,46 @@ function logEvent(type, entry) {
120
121
  // ---------------------------------------------------------------------------
121
122
 
122
123
  async function poll() {
123
- const services = [
124
- { name: "slack", fn: pollSlack },
125
- { name: "gmail", fn: pollGmail },
126
- { name: "alex-gmail", fn: pollSecondaryGmail },
127
- { name: "calendar", fn: pollCalendar },
128
- { name: "voice", fn: pollVoice },
124
+ // COHORT IS THE DEFAULT SUBSTRATE. An agent's messaging, email, calendar,
125
+ // CRM, directory, spaces, boards, books and calls all live on the Cohort
126
+ // server. The third-party adapters below are LEGACY BRIDGES for agents that
127
+ // additionally sit in someone else's Slack or Gmail — they are not what a new
128
+ // agent should be doing by default.
129
+ //
130
+ // They used to be polled unconditionally, which meant every freshly-created
131
+ // agent burned a poll cycle on Slack, two Gmail accounts, Google Calendar and
132
+ // voice on a loop, and filled its log with "SLACK_TOKEN not set" /
133
+ // "App password not set" forever. Worse, the noise made a REAL failure
134
+ // (Cohort inbound not wired at all) invisible in the same log.
135
+ //
136
+ // Each is now gated on evidence that it is actually configured, exactly like
137
+ // the channel-bus platforms below. Nothing is removed — an agent that IS on
138
+ // Slack keeps working the moment its token exists.
139
+ const services = [];
140
+ const legacyBridges = [
141
+ { name: "slack", fn: pollSlack, on: () => Boolean(process.env.SLACK_TOKEN || process.env.SLACK_USER_TOKEN) },
142
+ { name: "gmail", fn: pollGmail, on: () => Boolean(process.env.GMAIL_APP_PASSWORD) },
143
+ { name: "alex-gmail", fn: pollSecondaryGmail, on: () => Boolean(process.env.SECONDARY_GMAIL_APP_PASSWORD) },
144
+ { name: "calendar", fn: pollCalendar, on: () => _existsSync(join(AGENT_REPO_DIR, "config/google-calendar.yaml")) || Boolean(process.env.GOOGLE_CALENDAR_CREDENTIALS) },
145
+ { name: "voice", fn: pollVoice, on: () => _existsSync(join(AGENT_REPO_DIR, "config/voice.yaml")) || Boolean(process.env.TWILIO_ACCOUNT_SID) },
129
146
  ];
147
+ for (const b of legacyBridges) {
148
+ let enabled = false;
149
+ try { enabled = b.on(); } catch { enabled = false; }
150
+ if (enabled) services.push({ name: b.name, fn: b.fn });
151
+ }
130
152
 
131
153
  // WS2: channel-bus platforms (Telegram, Baileys WhatsApp) deliver events as
132
154
  // inbox YAML via the daemon's channel loop. They have no API poller, so a
133
155
  // generic inbox scanner drains their items into the same pipeline. Gate on
134
156
  // the platform's config file so we don't scan dirs for disabled channels.
135
- for (const [name, gate] of [["telegram", "config/telegram.yaml"], ["whatsapp", "config/whatsapp.yaml"], ["orgmail", "config/orgmail.yaml"]]) {
157
+ // `cohort` is the SAME shape: the messaging-inbound cadence pulls org
158
+ // messages / @mentions / call-invites directed at this agent and writes them
159
+ // as inbox YAML under state/inbox/cohort/ — but nothing drained that
160
+ // directory, so the items simply accumulated and the agent never answered.
161
+ // The whole SP10 inbound chain existed except this last hop. Gated on org
162
+ // enrolment (config/org.yaml) exactly like the other channel sources.
163
+ for (const [name, gate] of [["telegram", "config/telegram.yaml"], ["whatsapp", "config/whatsapp.yaml"], ["orgmail", "config/orgmail.yaml"], ["cohort", "config/org.yaml"]]) {
136
164
  if (_existsSync(join(AGENT_REPO_DIR, gate))) {
137
165
  services.push({ name, fn: makeInboxScanPoller(name, { agentRoot: AGENT_REPO_DIR }) });
138
166
  }
@@ -808,9 +836,40 @@ async function sweepBacklog() {
808
836
  }
809
837
  }
810
838
 
811
- // Sort: critical first, then high, then normal
812
- const priorityOrder = { critical: 0, high: 1, normal: 2, low: 3 };
813
- actionableItems.sort((a, b) => (priorityOrder[a.priority] || 3) - (priorityOrder[b.priority] || 3));
839
+ // Rank: flat priority (critical → low) as the base term, PROMOTED by the
840
+ // measured KPI gap of whatever objective the item claims to advance
841
+ // (SPEC §6.3 step 6: score = w_p·priority + w_g·(normalizedGap × expectedDelta)
842
+ // − w_a·age). Items with no `advances[]` — every seeded/hand-written item —
843
+ // score exactly as they do today, so nothing regresses. Weights come from
844
+ // the charter's rewardWeights when present.
845
+ //
846
+ // Fail-open: any error here falls back to the flat sort rather than
847
+ // stalling the sweep, and says so.
848
+ let ranked = actionableItems;
849
+ try {
850
+ const gapsByObjective = readLatestGaps(AGENT_REPO_DIR, {
851
+ log: (lvl, msg) => console.log(`[daemon] ${msg}`),
852
+ });
853
+ let charter = null;
854
+ try {
855
+ charter = JSON.parse(readFileSync(join(AGENT_REPO_DIR, "config", "agent.json"), "utf-8")).charter || null;
856
+ } catch { /* no charter on disk yet — defaults apply */ }
857
+ ranked = rankBacklog(actionableItems, {
858
+ gapsByObjective,
859
+ weights: resolveBacklogWeights(charter),
860
+ now: Date.now(),
861
+ });
862
+ const promoted = ranked.filter((r) => r._scoreParts && r._scoreParts.gapTerm > 0).length;
863
+ if (promoted > 0) {
864
+ console.log(`[daemon] Backlog ranking: ${promoted} item(s) promoted by a measured KPI gap`);
865
+ }
866
+ } catch (err) {
867
+ console.error(`[daemon] Backlog gap-ranking failed, falling back to flat priority order: ${err.message}`);
868
+ const priorityOrder = { critical: 0, high: 1, normal: 2, low: 3 };
869
+ ranked = [...actionableItems].sort((a, b) => (priorityOrder[a.priority] || 3) - (priorityOrder[b.priority] || 3));
870
+ }
871
+ actionableItems.length = 0;
872
+ actionableItems.push(...ranked);
814
873
 
815
874
  // Filter out items that already have active sessions or exceeded retries
816
875
  const dispatchable = actionableItems.filter((qi) => {