@cohortapp/agent-sdk 2.17.0 → 2.18.4

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 (526) hide show
  1. package/.claude/settings.json +18 -0
  2. package/.env.example +18 -5
  3. package/README.md +1 -0
  4. package/bin/maestro.mjs +62 -0
  5. package/docs/guides/billing-console-keys.md +60 -0
  6. package/docs/guides/front-door-session.md +54 -9
  7. package/docs/guides/mac-mini.md +20 -25
  8. package/docs/guides/setup-wizard.md +1 -1
  9. package/docs/runbooks/fleet-rollout.md +156 -0
  10. package/docs/runbooks/mac-mini-bootstrap.md +12 -14
  11. package/lib/action-executor.js +19 -3
  12. package/lib/budget-guard.mjs +279 -3
  13. package/lib/channels/base-adapter.mjs +3 -1
  14. package/lib/channels/contract.mjs +2 -1
  15. package/lib/channels/inbox-item.mjs +8 -0
  16. package/lib/claude-bin.mjs +5 -6
  17. package/lib/cli/doctor-checks.mjs +141 -10
  18. package/lib/cli/global-setup-extras.mjs +5 -1
  19. package/lib/cli/inbox.mjs +100 -15
  20. package/lib/cli/seat-auth.mjs +463 -0
  21. package/lib/cli/session.mjs +80 -12
  22. package/lib/collective/capture.mjs +8 -6
  23. package/lib/collective/global-config.mjs +63 -1
  24. package/lib/collective/presence.mjs +142 -5
  25. package/lib/comms/send-gate.mjs +559 -1
  26. package/lib/diagnostics/alerts.mjs +49 -0
  27. package/lib/diagnostics/cadence-output-freshness.mjs +288 -0
  28. package/lib/engine/agents/definitions.mjs +343 -0
  29. package/lib/engine/agents/persist.mjs +275 -0
  30. package/lib/engine/agents/runtime.mjs +748 -0
  31. package/lib/engine/agents/usage.mjs +95 -0
  32. package/lib/engine/auth-status.mjs +139 -0
  33. package/lib/engine/budget.mjs +194 -0
  34. package/lib/engine/cli.mjs +1204 -0
  35. package/lib/engine/commands/index.mjs +269 -0
  36. package/lib/engine/context/budget.mjs +219 -0
  37. package/lib/engine/context/cache.mjs +125 -0
  38. package/lib/engine/context/child-env.mjs +215 -0
  39. package/lib/engine/context/compaction.mjs +342 -0
  40. package/lib/engine/context/images.mjs +90 -0
  41. package/lib/engine/context/instructions.mjs +327 -0
  42. package/lib/engine/context/lazy-instructions.mjs +169 -0
  43. package/lib/engine/context/manager.mjs +182 -0
  44. package/lib/engine/context/real-path.mjs +91 -0
  45. package/lib/engine/context/secret-values.mjs +163 -0
  46. package/lib/engine/context/settings.mjs +274 -0
  47. package/lib/engine/context/stream-input.mjs +159 -0
  48. package/lib/engine/guard.mjs +152 -0
  49. package/lib/engine/hooks.mjs +713 -0
  50. package/lib/engine/loop.mjs +560 -0
  51. package/lib/engine/mcp/client.mjs +254 -0
  52. package/lib/engine/mcp/config.mjs +301 -0
  53. package/lib/engine/mcp/http.mjs +201 -0
  54. package/lib/engine/mcp/index.mjs +146 -0
  55. package/lib/engine/mcp/jsonrpc.mjs +147 -0
  56. package/lib/engine/mcp/naming.mjs +66 -0
  57. package/lib/engine/mcp/resources.mjs +89 -0
  58. package/lib/engine/mcp/results.mjs +133 -0
  59. package/lib/engine/mcp/stdio.mjs +137 -0
  60. package/lib/engine/mcp/supervisor.mjs +116 -0
  61. package/lib/engine/messages.mjs +104 -0
  62. package/lib/engine/output/json.mjs +164 -0
  63. package/lib/engine/output/stream-json.mjs +266 -0
  64. package/lib/engine/permissions.mjs +845 -0
  65. package/lib/engine/process-identity.mjs +164 -0
  66. package/lib/engine/process-tree.mjs +551 -0
  67. package/lib/engine/prompt.mjs +60 -0
  68. package/lib/engine/session/store.mjs +299 -0
  69. package/lib/engine/session-runtime/args.mjs +97 -0
  70. package/lib/engine/session-runtime/host.mjs +143 -0
  71. package/lib/engine/session-runtime/inbox.mjs +122 -0
  72. package/lib/engine/session-runtime/notifications.mjs +129 -0
  73. package/lib/engine/session-runtime/registry.mjs +328 -0
  74. package/lib/engine/session-runtime/runner.mjs +344 -0
  75. package/lib/engine/session-runtime/socket.mjs +212 -0
  76. package/lib/engine/session-runtime/wakeup.mjs +115 -0
  77. package/lib/engine/skills/index.mjs +321 -0
  78. package/lib/engine/tools/bash-background.mjs +533 -0
  79. package/lib/engine/tools/bash.mjs +216 -0
  80. package/lib/engine/tools/edit.mjs +97 -0
  81. package/lib/engine/tools/glob.mjs +81 -0
  82. package/lib/engine/tools/grep.mjs +224 -0
  83. package/lib/engine/tools/index.mjs +84 -0
  84. package/lib/engine/tools/list-agents.mjs +32 -0
  85. package/lib/engine/tools/ls.mjs +127 -0
  86. package/lib/engine/tools/monitor.mjs +82 -0
  87. package/lib/engine/tools/notebook-edit.mjs +218 -0
  88. package/lib/engine/tools/read.mjs +103 -0
  89. package/lib/engine/tools/schedule-wakeup.mjs +45 -0
  90. package/lib/engine/tools/schema.mjs +144 -0
  91. package/lib/engine/tools/send-message.mjs +77 -0
  92. package/lib/engine/tools/session.mjs +70 -0
  93. package/lib/engine/tools/todo.mjs +144 -0
  94. package/lib/engine/tools/toolsearch.mjs +217 -0
  95. package/lib/engine/tools/walk.mjs +193 -0
  96. package/lib/engine/tools/web-switch.mjs +31 -0
  97. package/lib/engine/tools/webfetch-html.mjs +387 -0
  98. package/lib/engine/tools/webfetch-net.mjs +340 -0
  99. package/lib/engine/tools/webfetch.mjs +198 -0
  100. package/lib/engine/tools/websearch.mjs +91 -0
  101. package/lib/engine/tools/workflow.mjs +95 -0
  102. package/lib/engine/tools/write.mjs +76 -0
  103. package/lib/engine/tui/line-editor.mjs +137 -0
  104. package/lib/engine/tui/render.mjs +86 -0
  105. package/lib/engine/tui/tui.mjs +274 -0
  106. package/lib/engine/wire/anthropic-messages.mjs +263 -0
  107. package/lib/engine/wire/effort.mjs +36 -0
  108. package/lib/engine/wire/errors.mjs +496 -0
  109. package/lib/engine/wire/http.mjs +441 -0
  110. package/lib/engine/wire/index.mjs +76 -0
  111. package/lib/engine/wire/openai-chat.mjs +332 -0
  112. package/lib/engine/wire/prompt-cache.mjs +79 -0
  113. package/lib/engine/wire/search.mjs +140 -0
  114. package/lib/engine/wire/sse.mjs +114 -0
  115. package/lib/engine/wire/stall.mjs +349 -0
  116. package/lib/engine/wire/token-provider.mjs +175 -0
  117. package/lib/engine/wire/usage.mjs +192 -0
  118. package/lib/engine/workflow/host.mjs +524 -0
  119. package/lib/engine/workflow/journal.mjs +188 -0
  120. package/lib/engine/workflow/json-schema.mjs +171 -0
  121. package/lib/engine/workflow/meta.mjs +329 -0
  122. package/lib/engine/workflow/notifications.mjs +52 -0
  123. package/lib/engine/workflow/runtime.mjs +447 -0
  124. package/lib/engine/workflow/sandbox.mjs +534 -0
  125. package/lib/engine/workflow/worker.mjs +141 -0
  126. package/lib/engine/workflow/worktree.mjs +74 -0
  127. package/lib/execution/disposition.mjs +1 -1
  128. package/lib/execution/intake.mjs +10 -0
  129. package/lib/execution/surface-policy.mjs +15 -0
  130. package/lib/learning/curator.mjs +8 -6
  131. package/lib/learning/reflect.mjs +8 -6
  132. package/lib/model-router/catalog/cohort.yaml +137 -0
  133. package/lib/model-router/catalog.mjs +118 -1
  134. package/lib/model-router/failover.mjs +67 -16
  135. package/lib/model-router/llm-task.mjs +39 -3
  136. package/lib/model-router/resolve.mjs +89 -3
  137. package/lib/model-router/spawn.mjs +46 -47
  138. package/lib/model-router/taxonomy.mjs +126 -4
  139. package/lib/org/cost-sync.mjs +141 -11
  140. package/lib/org/inbound/broadcast.mjs +289 -0
  141. package/lib/org/inbound/collective.mjs +375 -0
  142. package/lib/org/inbound/directedness.mjs +96 -8
  143. package/lib/org/inbound/facts.mjs +78 -2
  144. package/lib/org/inbound/project.mjs +22 -0
  145. package/lib/org/inbound/surfaces.mjs +14 -0
  146. package/lib/org/llm-token.mjs +879 -0
  147. package/lib/org/mesh.mjs +61 -0
  148. package/lib/org/messaging.mjs +3 -1
  149. package/lib/org/protocol.checksum +1 -1
  150. package/lib/org/protocol.mjs +15 -0
  151. package/lib/org/quota.mjs +520 -0
  152. package/lib/org/tool-surface.mjs +104 -16
  153. package/lib/org/ui-parity.mjs +16 -1
  154. package/lib/org/work-ledger.mjs +37 -6
  155. package/lib/rate-guard.mjs +114 -1
  156. package/lib/resource-governor.mjs +41 -6
  157. package/lib/runtime/adapter.mjs +823 -0
  158. package/lib/runtime/child-env.mjs +191 -0
  159. package/lib/runtime/legacy-shell-guard.mjs +97 -0
  160. package/lib/runtime/seat-engine.mjs +162 -0
  161. package/lib/session/ask-ledger.mjs +271 -0
  162. package/lib/session/current-work.mjs +676 -0
  163. package/lib/session/feed-core.mjs +40 -3
  164. package/lib/session/launch-args.mjs +56 -4
  165. package/lib/session/status-summary.mjs +26 -9
  166. package/lib/session/upgrade-notice.mjs +42 -0
  167. package/lib/setup/claude-probe.mjs +117 -13
  168. package/lib/setup/enrich.mjs +13 -10
  169. package/lib/setup/sections/model.mjs +39 -13
  170. package/lib/telemetry/collect.mjs +208 -9
  171. package/lib/upgrade/ignored-drift.mjs +105 -0
  172. package/lib/voice/post-call-brief.mjs +30 -17
  173. package/package.json +13 -3
  174. package/plugins/maestro-skills/skills/board-work.md +5 -0
  175. package/plugins/maestro-skills/skills/inbound-triage.md +56 -15
  176. package/plugins/maestro-skills/skills/main-session.md +18 -7
  177. package/scripts/ci/check-tarball-fidelity.mjs +126 -2
  178. package/scripts/ci/run-tests.mjs +47 -19
  179. package/scripts/cohort-llm/api-key-helper.mjs +92 -0
  180. package/scripts/collective/hook-runner.mjs +29 -2
  181. package/scripts/continuous-monitor.sh +13 -0
  182. package/scripts/cost/track-claude-usage.mjs +15 -0
  183. package/scripts/daemon/agent-daemon.mjs +408 -20
  184. package/scripts/daemon/assurance.mjs +48 -12
  185. package/scripts/daemon/cadence-consumer.mjs +218 -68
  186. package/scripts/daemon/cadence-handlers.mjs +73 -4
  187. package/scripts/daemon/classifier.mjs +75 -26
  188. package/scripts/daemon/context-compiler.mjs +51 -37
  189. package/scripts/daemon/deliver.mjs +30 -1
  190. package/scripts/daemon/dispatcher.mjs +595 -149
  191. package/scripts/daemon/health.mjs +14 -1
  192. package/scripts/daemon/maestro-daemon.mjs +11 -0
  193. package/scripts/daemon/prompt-builder.mjs +24 -0
  194. package/scripts/daemon/responder.mjs +246 -79
  195. package/scripts/daemon/sdk-version.mjs +98 -16
  196. package/scripts/eval/probe-gateway.mjs +635 -0
  197. package/scripts/eval/replay/extract.mjs +270 -0
  198. package/scripts/eval/replay/grade.mjs +260 -0
  199. package/scripts/eval/replay/lib/config.mjs +50 -0
  200. package/scripts/eval/replay/lib/effects.mjs +65 -0
  201. package/scripts/eval/replay/lib/fixture.mjs +188 -0
  202. package/scripts/eval/replay/lib/judge.mjs +72 -0
  203. package/scripts/eval/replay/lib/redact.mjs +136 -0
  204. package/scripts/eval/replay/lib/sandbox.mjs +170 -0
  205. package/scripts/eval/replay/lib/schema-check.mjs +63 -0
  206. package/scripts/eval/replay/lib/transcript.mjs +76 -0
  207. package/scripts/eval/replay/mcp-replay-stub.mjs +101 -0
  208. package/scripts/eval/replay/report.mjs +185 -0
  209. package/scripts/eval/replay/run.mjs +404 -0
  210. package/scripts/fleet/rollout.mjs +1094 -0
  211. package/scripts/hooks/pre-send-audit.sh +36 -245
  212. package/scripts/hooks/pre-write-yaml-validate.mjs +275 -0
  213. package/scripts/hooks/validate-state-yaml.sh +190 -0
  214. package/scripts/huddle/huddle-llm.mjs +361 -0
  215. package/scripts/huddle/huddle-server.mjs +46 -121
  216. package/scripts/local-triggers/autoupdate.sh +448 -78
  217. package/scripts/local-triggers/run-trigger.sh +13 -0
  218. package/scripts/maintenance/pin-integrity.mjs +364 -0
  219. package/scripts/poll-slack-events.sh +41 -9
  220. package/scripts/poller/slack-socket-mode.mjs +28 -3
  221. package/scripts/session/supervisor.mjs +80 -13
  222. package/scripts/spawn-session.sh +13 -0
  223. package/bin/maestro.test.mjs +0 -1574
  224. package/lib/action-executor.test.mjs +0 -871
  225. package/lib/archetype.test.mjs +0 -132
  226. package/lib/assurance/plan-note.test.mjs +0 -234
  227. package/lib/assurance/room-budget.test.mjs +0 -486
  228. package/lib/assurance/tier.test.mjs +0 -174
  229. package/lib/autonomy.test.mjs +0 -66
  230. package/lib/backlog.test.mjs +0 -302
  231. package/lib/backup/policy.test.mjs +0 -305
  232. package/lib/budget-escalate.test.mjs +0 -232
  233. package/lib/budget-guard.envelope.test.mjs +0 -476
  234. package/lib/budget-guard.test.mjs +0 -427
  235. package/lib/cadence-bus-requeue.test.mjs +0 -83
  236. package/lib/cadence-bus-schedule.test.mjs +0 -194
  237. package/lib/cadence-bus.test.mjs +0 -720
  238. package/lib/cadences.test.mjs +0 -230
  239. package/lib/capability/inventory.test.mjs +0 -232
  240. package/lib/capability.test.mjs +0 -78
  241. package/lib/channels/base-adapter.test.mjs +0 -590
  242. package/lib/channels/channels.test.mjs +0 -371
  243. package/lib/channels/contract.test.mjs +0 -162
  244. package/lib/channels/inbox-item.test.mjs +0 -368
  245. package/lib/channels/orgmail/adapter.test.mjs +0 -448
  246. package/lib/channels/pairing.test.mjs +0 -270
  247. package/lib/channels/repeat-suppressor.test.mjs +0 -134
  248. package/lib/channels/slack-adapter.test.mjs +0 -212
  249. package/lib/channels/telegram-adapter.test.mjs +0 -306
  250. package/lib/channels/voice/adapter.test.mjs +0 -278
  251. package/lib/channels/whatsapp/adapter-baileys.test.mjs +0 -359
  252. package/lib/channels/whatsapp/baileys-typing.test.mjs +0 -154
  253. package/lib/charter.test.mjs +0 -89
  254. package/lib/claude-bin.test.mjs +0 -131
  255. package/lib/cli/board.test.mjs +0 -227
  256. package/lib/cli/design.test.mjs +0 -270
  257. package/lib/cli/doctor-checks.test.mjs +0 -336
  258. package/lib/cli/global-setup-extras.test.mjs +0 -462
  259. package/lib/cli/inbox.test.mjs +0 -230
  260. package/lib/cli/session-ack.test.mjs +0 -63
  261. package/lib/cli/session.test.mjs +0 -613
  262. package/lib/collective/capture.test.mjs +0 -121
  263. package/lib/collective/cards.test.mjs +0 -114
  264. package/lib/collective/config.test.mjs +0 -123
  265. package/lib/collective/global-config.test.mjs +0 -220
  266. package/lib/collective/global-skills.test.mjs +0 -126
  267. package/lib/collective/presence.test.mjs +0 -95
  268. package/lib/collective/recall.test.mjs +0 -116
  269. package/lib/collective/vendor-skills.test.mjs +0 -306
  270. package/lib/comms/send-gate.test.mjs +0 -770
  271. package/lib/comms.test.mjs +0 -41
  272. package/lib/context/budget.test.mjs +0 -252
  273. package/lib/context/history-scope.test.mjs +0 -79
  274. package/lib/cost/ledger-row.test.mjs +0 -183
  275. package/lib/design/design-md.test.mjs +0 -318
  276. package/lib/design/fixtures/DESIGN.golden.md +0 -238
  277. package/lib/design/fixtures/PRODUCT.golden.md +0 -67
  278. package/lib/design/fixtures/foundation.json +0 -133
  279. package/lib/design/refresh-gate.test.mjs +0 -144
  280. package/lib/design/write.test.mjs +0 -241
  281. package/lib/diagnostics/alerts.test.mjs +0 -318
  282. package/lib/diagnostics/backup-freshness.test.mjs +0 -185
  283. package/lib/diagnostics/counters.test.mjs +0 -206
  284. package/lib/diagnostics/events.test.mjs +0 -290
  285. package/lib/diagnostics/otel.test.mjs +0 -196
  286. package/lib/diagnostics/trace.test.mjs +0 -251
  287. package/lib/env-compat.test.mjs +0 -104
  288. package/lib/execution/disposition.test.mjs +0 -553
  289. package/lib/execution/drive.test.mjs +0 -270
  290. package/lib/execution/effects.test.mjs +0 -344
  291. package/lib/execution/intake.test.mjs +0 -389
  292. package/lib/execution/journal.test.mjs +0 -261
  293. package/lib/execution/match.test.mjs +0 -235
  294. package/lib/execution/pipeline.test.mjs +0 -392
  295. package/lib/execution/route.test.mjs +0 -186
  296. package/lib/execution/surface-policy.test.mjs +0 -162
  297. package/lib/fs-atomic.test.mjs +0 -72
  298. package/lib/fs-ownership.test.mjs +0 -158
  299. package/lib/goals/admission.test.mjs +0 -164
  300. package/lib/goals/classify.test.mjs +0 -167
  301. package/lib/goals/collaborate.test.mjs +0 -336
  302. package/lib/goals/gaps.test.mjs +0 -284
  303. package/lib/goals/loop.test.mjs +0 -845
  304. package/lib/hooks/bus.test.mjs +0 -387
  305. package/lib/identity/persona.test.mjs +0 -142
  306. package/lib/kpi-sensors.test.mjs +0 -278
  307. package/lib/kpi.test.mjs +0 -244
  308. package/lib/learning/config.test.mjs +0 -75
  309. package/lib/learning/counters.test.mjs +0 -69
  310. package/lib/learning/curator-consolidate.test.mjs +0 -238
  311. package/lib/learning/curator.test.mjs +0 -106
  312. package/lib/learning/reflect.test.mjs +0 -0
  313. package/lib/learning/session-index.test.mjs +0 -125
  314. package/lib/learning/skill-writer.test.mjs +0 -210
  315. package/lib/mandate/audit.test.mjs +0 -195
  316. package/lib/mandate/contract.test.mjs +0 -185
  317. package/lib/mandate/derive.test.mjs +0 -274
  318. package/lib/mandate/model.test.mjs +0 -164
  319. package/lib/mandate/refresh.test.mjs +0 -389
  320. package/lib/mcp/server.test.mjs +0 -426
  321. package/lib/model-router/auth-profiles.test.mjs +0 -580
  322. package/lib/model-router/catalog.test.mjs +0 -385
  323. package/lib/model-router/economics.test.mjs +0 -438
  324. package/lib/model-router/failover.test.mjs +0 -439
  325. package/lib/model-router/health.test.mjs +0 -338
  326. package/lib/model-router/integration-coverage.test.mjs +0 -831
  327. package/lib/model-router/integration.test.mjs +0 -564
  328. package/lib/model-router/ledger.test.mjs +0 -415
  329. package/lib/model-router/llm-task.test.mjs +0 -392
  330. package/lib/model-router/org-credentials.test.mjs +0 -265
  331. package/lib/model-router/pricing-refresh.test.mjs +0 -286
  332. package/lib/model-router/reconcile.test.mjs +0 -316
  333. package/lib/model-router/repair.test.mjs +0 -180
  334. package/lib/model-router/spawn.test.mjs +0 -446
  335. package/lib/model-router/taxonomy.test.mjs +0 -410
  336. package/lib/model-router.test.mjs +0 -1207
  337. package/lib/org/activity.test.mjs +0 -134
  338. package/lib/org/approvals.test.mjs +0 -216
  339. package/lib/org/awareness.test.mjs +0 -159
  340. package/lib/org/board-mine-cache.test.mjs +0 -53
  341. package/lib/org/board.test.mjs +0 -187
  342. package/lib/org/bootstrap-context.test.mjs +0 -153
  343. package/lib/org/client.test.mjs +0 -1206
  344. package/lib/org/cohort-client.test.mjs +0 -126
  345. package/lib/org/cost-sync.test.mjs +0 -153
  346. package/lib/org/doctor.test.mjs +0 -346
  347. package/lib/org/engagement-ledger.test.mjs +0 -112
  348. package/lib/org/engagement.test.mjs +0 -739
  349. package/lib/org/handoff.test.mjs +0 -269
  350. package/lib/org/inbound/directedness.test.mjs +0 -668
  351. package/lib/org/inbound/facts.test.mjs +0 -471
  352. package/lib/org/inbound/hydrate.test.mjs +0 -908
  353. package/lib/org/inbound/index.test.mjs +0 -429
  354. package/lib/org/inbound/project.test.mjs +0 -287
  355. package/lib/org/integration-tools.test.mjs +0 -160
  356. package/lib/org/keys.test.mjs +0 -92
  357. package/lib/org/knowledge.test.mjs +0 -326
  358. package/lib/org/leases.test.mjs +0 -235
  359. package/lib/org/mesh-directives.test.mjs +0 -110
  360. package/lib/org/mesh-integration.test.mjs +0 -127
  361. package/lib/org/mesh.test.mjs +0 -400
  362. package/lib/org/messaging.test.mjs +0 -471
  363. package/lib/org/param-contract.test.mjs +0 -477
  364. package/lib/org/policy.test.mjs +0 -237
  365. package/lib/org/protocol.checksum.test.mjs +0 -90
  366. package/lib/org/protocol.test.mjs +0 -323
  367. package/lib/org/push.test.mjs +0 -792
  368. package/lib/org/registry.test.mjs +0 -100
  369. package/lib/org/resource-tools.test.mjs +0 -361
  370. package/lib/org/tool-access.test.mjs +0 -144
  371. package/lib/org/tool-surface-integration.test.mjs +0 -120
  372. package/lib/org/tool-surface.test.mjs +0 -1268
  373. package/lib/org/typing.test.mjs +0 -291
  374. package/lib/org/ui-parity.test.mjs +0 -560
  375. package/lib/org/verify.test.mjs +0 -194
  376. package/lib/org/work-ledger.test.mjs +0 -273
  377. package/lib/plan/adoption-e2e.test.mjs +0 -366
  378. package/lib/plan/budget-enforcement.test.mjs +0 -400
  379. package/lib/plan/compile.test.mjs +0 -382
  380. package/lib/plan/emit.test.mjs +0 -269
  381. package/lib/plan/explain.test.mjs +0 -188
  382. package/lib/prompts/parallelism.test.mjs +0 -177
  383. package/lib/rag/rag.test.mjs +0 -505
  384. package/lib/rate-guard.test.mjs +0 -272
  385. package/lib/reactive-gate.test.mjs +0 -57
  386. package/lib/render.test.mjs +0 -68
  387. package/lib/resource-governor.test.mjs +0 -488
  388. package/lib/scheduling/dynamic-jobs.test.mjs +0 -344
  389. package/lib/scheduling/jitter.test.mjs +0 -140
  390. package/lib/secrets/broker.test.mjs +0 -280
  391. package/lib/secrets/providers.test.mjs +0 -274
  392. package/lib/security/audit-engine.test.mjs +0 -424
  393. package/lib/security/coerce-args.test.mjs +0 -281
  394. package/lib/security/dangerous-tools.test.mjs +0 -68
  395. package/lib/security/external-content.test.mjs +0 -84
  396. package/lib/security/redact.test.mjs +0 -441
  397. package/lib/security/secret-equal.test.mjs +0 -55
  398. package/lib/session/config.test.mjs +0 -92
  399. package/lib/session/feed-core.test.mjs +0 -198
  400. package/lib/session/first-run.test.mjs +0 -121
  401. package/lib/session/frontdoor.test.mjs +0 -205
  402. package/lib/session/handoffs.test.mjs +0 -183
  403. package/lib/session/identity.test.mjs +0 -180
  404. package/lib/session/inbox-claims.test.mjs +0 -286
  405. package/lib/session/launch-args.test.mjs +0 -157
  406. package/lib/session/liveness.test.mjs +0 -100
  407. package/lib/session/status-summary.test.mjs +0 -118
  408. package/lib/session-permissions.test.mjs +0 -120
  409. package/lib/setup/claude-probe.test.mjs +0 -187
  410. package/lib/setup/completeness.test.mjs +0 -110
  411. package/lib/setup/context-pack.test.mjs +0 -89
  412. package/lib/setup/enrich.test.mjs +0 -115
  413. package/lib/setup/enroll-from-cohort.test.mjs +0 -300
  414. package/lib/setup/integration.test.mjs +0 -162
  415. package/lib/setup/io.test.mjs +0 -77
  416. package/lib/setup/runner.test.mjs +0 -132
  417. package/lib/setup/sections/identity.test.mjs +0 -234
  418. package/lib/setup/sections/inventory.test.mjs +0 -198
  419. package/lib/setup/sections/learning.test.mjs +0 -81
  420. package/lib/setup/sections/mandate.test.mjs +0 -388
  421. package/lib/setup/sections/messaging.test.mjs +0 -127
  422. package/lib/setup/sections/model.test.mjs +0 -240
  423. package/lib/setup/sections/org.test.mjs +0 -346
  424. package/lib/setup/sections/orgmail.test.mjs +0 -118
  425. package/lib/setup/sections/recovery.test.mjs +0 -98
  426. package/lib/setup/sections/subagents.test.mjs +0 -429
  427. package/lib/setup/sections/verify.test.mjs +0 -175
  428. package/lib/setup/sot.test.mjs +0 -81
  429. package/lib/setup/state.test.mjs +0 -115
  430. package/lib/singleton.test.mjs +0 -151
  431. package/lib/subagents/cli.test.mjs +0 -389
  432. package/lib/subagents/client.test.mjs +0 -309
  433. package/lib/subagents/gap.test.mjs +0 -234
  434. package/lib/subagents/lock.test.mjs +0 -248
  435. package/lib/subagents/manifest.test.mjs +0 -175
  436. package/lib/subagents/refs.test.mjs +0 -204
  437. package/lib/subagents/resolve.test.mjs +0 -422
  438. package/lib/subagents/schema.test.mjs +0 -328
  439. package/lib/telemetry/alerts.test.mjs +0 -109
  440. package/lib/telemetry/collect.test.mjs +0 -1274
  441. package/lib/tool-definitions-integration.test.mjs +0 -83
  442. package/lib/tool-definitions.test.mjs +0 -437
  443. package/lib/upgrade/global-refresh.test.mjs +0 -65
  444. package/lib/upgrade/launchd-reconcile.test.mjs +0 -272
  445. package/lib/upgrade/post-steps.test.mjs +0 -200
  446. package/lib/upgrade/verify.test.mjs +0 -164
  447. package/lib/util/fetch-timeout.test.mjs +0 -202
  448. package/lib/util/reconnect.test.mjs +0 -369
  449. package/lib/util/unhandled.test.mjs +0 -216
  450. package/lib/voice/outbound.test.mjs +0 -69
  451. package/lib/voice/session-rotation.test.mjs +0 -114
  452. package/lib/voice/stt.test.mjs +0 -226
  453. package/lib/voice/voice.test.mjs +0 -990
  454. package/scripts/cadence/enqueue-cadence-tick.test.mjs +0 -187
  455. package/scripts/ci/check-docs-accuracy.test.mjs +0 -409
  456. package/scripts/ci/check-durable-write-seam.test.mjs +0 -90
  457. package/scripts/ci/check-no-build-artifacts.test.mjs +0 -71
  458. package/scripts/ci/check-no-residual-identity.test.mjs +0 -202
  459. package/scripts/ci/check-skill-packs.test.mjs +0 -495
  460. package/scripts/ci/check-subagent-frontmatter.test.mjs +0 -124
  461. package/scripts/ci/check.test.mjs +0 -194
  462. package/scripts/ci/conformance-org-api.test.mjs +0 -425
  463. package/scripts/cloud-relay/voice/relay-identity.test.mjs +0 -96
  464. package/scripts/collective/hook-runner.test.mjs +0 -173
  465. package/scripts/cost/fleet-digest.test.mjs +0 -207
  466. package/scripts/cost/track-claude-usage-pricing.test.mjs +0 -183
  467. package/scripts/cost/track-claude-usage.test.mjs +0 -148
  468. package/scripts/daemon/agent-daemon-board-mine.test.mjs +0 -96
  469. package/scripts/daemon/agent-daemon-design.test.mjs +0 -238
  470. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +0 -60
  471. package/scripts/daemon/agent-daemon.test.mjs +0 -995
  472. package/scripts/daemon/assurance-e2e.test.mjs +0 -613
  473. package/scripts/daemon/assurance.test.mjs +0 -1791
  474. package/scripts/daemon/board-mirror.test.mjs +0 -165
  475. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +0 -393
  476. package/scripts/daemon/cadence-consumer-governance.test.mjs +0 -276
  477. package/scripts/daemon/cadence-consumer.test.mjs +0 -776
  478. package/scripts/daemon/cadence-handlers.test.mjs +0 -837
  479. package/scripts/daemon/classifier-identity.test.mjs +0 -137
  480. package/scripts/daemon/classifier.test.mjs +0 -266
  481. package/scripts/daemon/classify-kind.test.mjs +0 -40
  482. package/scripts/daemon/context-compiler.test.mjs +0 -406
  483. package/scripts/daemon/deliver.test.mjs +0 -564
  484. package/scripts/daemon/dispatcher-cooldown.test.mjs +0 -122
  485. package/scripts/daemon/dispatcher-governance.test.mjs +0 -1013
  486. package/scripts/daemon/dispatcher-resume.test.mjs +0 -166
  487. package/scripts/daemon/dispatcher-session-continuity.test.mjs +0 -365
  488. package/scripts/daemon/execution-ladder.test.mjs +0 -470
  489. package/scripts/daemon/goal-steward-cadence.test.mjs +0 -312
  490. package/scripts/daemon/inbox-deferral-session.test.mjs +0 -49
  491. package/scripts/daemon/inbox-deferral.test.mjs +0 -336
  492. package/scripts/daemon/inbox-wake.test.mjs +0 -199
  493. package/scripts/daemon/integration.test.mjs +0 -149
  494. package/scripts/daemon/lib/self-echo.test.mjs +0 -153
  495. package/scripts/daemon/lib/session-router.test.mjs +0 -554
  496. package/scripts/daemon/prompt-builder-preamble.test.mjs +0 -210
  497. package/scripts/daemon/prompt-builder.test.mjs +0 -556
  498. package/scripts/daemon/responder-cost.test.mjs +0 -68
  499. package/scripts/daemon/responder-history.test.mjs +0 -221
  500. package/scripts/daemon/sdk-version.test.mjs +0 -31
  501. package/scripts/daemon/session-lock.test.mjs +0 -252
  502. package/scripts/daemon/session-outcomes.test.mjs +0 -533
  503. package/scripts/daemon/typing-registry.test.mjs +0 -102
  504. package/scripts/hooks/pre-send-audit.test.mjs +0 -354
  505. package/scripts/huddle/huddle-prompt.test.mjs +0 -176
  506. package/scripts/local-triggers/autoupdate.test.mjs +0 -518
  507. package/scripts/local-triggers/generate-plists.test.mjs +0 -456
  508. package/scripts/media-generation/brand-clause.test.mjs +0 -135
  509. package/scripts/org/send-orgmail.first-contact.test.mjs +0 -102
  510. package/scripts/poller/inbox-privilege-injection.test.mjs +0 -167
  511. package/scripts/poller/inbox-scan-poller.test.mjs +0 -295
  512. package/scripts/poller/lib/cloud-relay-dedup.test.mjs +0 -133
  513. package/scripts/poller/slack-socket-mode.test.mjs +0 -805
  514. package/scripts/poller-launchd/install.test.mjs +0 -243
  515. package/scripts/restore-from-backup.test.mjs +0 -181
  516. package/scripts/session/feed.test.mjs +0 -196
  517. package/scripts/session/supervisor-sh.test.mjs +0 -218
  518. package/scripts/session/supervisor.test.mjs +0 -482
  519. package/scripts/setup/configure-macos.test.mjs +0 -306
  520. package/scripts/setup/gen-subagent-manifest.test.mjs +0 -124
  521. package/scripts/setup/generate-agent-package-json.test.mjs +0 -143
  522. package/scripts/setup/generate-capability.test.mjs +0 -134
  523. package/scripts/setup/init-agent.test.mjs +0 -370
  524. package/scripts/setup/init-skill-marketplace.test.mjs +0 -193
  525. package/scripts/vendor/sync-skill-packs.test.mjs +0 -103
  526. package/scripts/watchdog/memory-watchdog.test.mjs +0 -64
@@ -1,1206 +0,0 @@
1
- /**
2
- * client.test.mjs — Cohort /v1 HTTP client: header correctness, method routing,
3
- * read parsing, fail-open, and back-compat surface. Uses an injected fetchImpl
4
- * that captures requests and returns canned frames (no network).
5
- * Run: node --test lib/org/client.test.mjs
6
- */
7
- "use strict";
8
-
9
- import { test } from "node:test";
10
- import assert from "node:assert/strict";
11
- import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
12
- import { tmpdir } from "node:os";
13
- import { join } from "node:path";
14
-
15
- /** Run `fn` with console.warn captured; returns the captured lines. */
16
- function captureWarn(fn) {
17
- const lines = [];
18
- const real = console.warn;
19
- console.warn = (...a) => { lines.push(a.join(" ")); };
20
- try { fn(); } finally { console.warn = real; }
21
- return lines;
22
- }
23
-
24
- import {
25
- isEnabled,
26
- loadOrgConfig,
27
- configFromAgent,
28
- pairRequest,
29
- call,
30
- read,
31
- register,
32
- heartbeat,
33
- presenceBeat,
34
- createItem,
35
- claimItem,
36
- completeItem,
37
- listReady,
38
- listMine,
39
- listMineResult,
40
- trackWork,
41
- fetchEvents,
42
- fetchSnapshot,
43
- publishEntry,
44
- fetchDirectory,
45
- leaseClaim,
46
- leaseHeartbeat,
47
- leaseRelease,
48
- handoffOffer,
49
- handoffAccept,
50
- handoffDecline,
51
- handoffCancel,
52
- boardDecompose,
53
- boardAssign,
54
- boardLink,
55
- governanceStatus,
56
- approvalRequest,
57
- approvalResolve,
58
- approvalGet,
59
- approvalList,
60
- approvalWait,
61
- decisionPropose,
62
- decisionAdopt,
63
- decisionSupersede,
64
- decisionList,
65
- costReport,
66
- costRollup,
67
- policyPublish,
68
- policyFetch,
69
- knowledgeAppend,
70
- knowledgeReplace,
71
- knowledgeRewrite,
72
- knowledgeInvalidate,
73
- knowledgeSearch,
74
- contactsUpsert,
75
- contactsList,
76
- meetingsRecord,
77
- meetingsList,
78
- credentialLease,
79
- credentialPut,
80
- credentialList,
81
- credentialRevoke,
82
- fetchSelfProfile,
83
- fetchOrgChart,
84
- fetchRelationships,
85
- fetchStrategy,
86
- fetchHierarchy,
87
- callingStart,
88
- callingJoin,
89
- callingInvite,
90
- callingEnd,
91
- callingAddTranscriptLine,
92
- callingChat,
93
- callingAppShareStart,
94
- callingAppShareAct,
95
- callingAppShareEnd,
96
- callingGetAppShare,
97
- callingGetVisualContext,
98
- callingGetCallEvents,
99
- pairApprove,
100
- brandingRegenerate,
101
- brandingRegenerateTemplates,
102
- brandingRegenerateTemplate,
103
- brandingRegenerateImages,
104
- brandingUploadImage,
105
- brandingAmendArtifact,
106
- brandingAmendTemplate,
107
- brandingCloneTemplate,
108
- brandingDeleteTemplate,
109
- brandingRestoreVersion,
110
- brandingUndo,
111
- brandingRedo,
112
- brandingListVersions,
113
- brandingExportTemplate,
114
- } from "./client.mjs";
115
- import { PROTOCOL_VERSION } from "./protocol.mjs";
116
-
117
- const BASE = "https://org.cohortapp.com";
118
- const TOKEN = "tok-abc";
119
-
120
- // Ambient COHORT_* tokens would leak into the "no token configured" assertions
121
- // below; clear them so tests are deterministic regardless of the host env.
122
- delete process.env.COHORT_API_TOKEN;
123
- delete process.env.COHORT_TOKEN;
124
-
125
- /** A fake fetch that records calls and returns a canned res frame. */
126
- function fakeFetch(responder) {
127
- const calls = [];
128
- const impl = async (url, init) => {
129
- calls.push({ url, init, headers: (init && init.headers) || {} });
130
- const r = responder ? responder(url, init, calls.length - 1) : null;
131
- const status = r && typeof r.status === "number" ? r.status : 200;
132
- const ok = r && typeof r.ok === "boolean" ? r.ok : status >= 200 && status < 300;
133
- const body = r ? r.body : { ok: true, result: null };
134
- return {
135
- ok,
136
- status,
137
- headers: { get: (k) => (r && r.respHeaders ? r.respHeaders[k.toLowerCase()] : undefined) },
138
- json: async () => body,
139
- };
140
- };
141
- impl.calls = calls;
142
- return impl;
143
- }
144
-
145
- // --- config ----------------------------------------------------------------
146
-
147
- test("isEnabled: requires enabled + (base or apiUrl+orgId)", () => {
148
- assert.equal(isEnabled({ org: { cohort: { enabled: true, base: BASE } } }), true);
149
- assert.equal(isEnabled({ org: { cohort: { enabled: true, apiUrl: "x", orgId: "o" } } }), true);
150
- assert.equal(isEnabled({ org: { cohort: { enabled: false, base: BASE } } }), false);
151
- assert.equal(isEnabled({ org: { cohort: { enabled: true } } }), false);
152
- assert.equal(isEnabled(null), false);
153
- });
154
-
155
- test("configFromAgent: explicit base wins; legacy apiUrl/orgId derives base; env token", () => {
156
- const a = configFromAgent({ org: { cohort: { enabled: true, base: BASE + "/", token: "t1", trustedSignersPem: ["PEM"] } } });
157
- assert.equal(a.base, BASE);
158
- assert.equal(a.token, "t1");
159
- assert.deepEqual(a.trustedSignersPem, ["PEM"]);
160
- assert.equal(a.enabled, true);
161
-
162
- const b = configFromAgent({ org: { cohort: { enabled: true, apiUrl: "https://api.x/", orgId: "acme" } } });
163
- assert.equal(b.base, "https://api.x/acme");
164
-
165
- const prev = process.env.COHORT_API_TOKEN;
166
- process.env.COHORT_API_TOKEN = "env-tok";
167
- try {
168
- const c = configFromAgent({ org: { cohort: { enabled: true, base: BASE } } });
169
- assert.equal(c.token, "env-tok");
170
- } finally {
171
- if (prev === undefined) delete process.env.COHORT_API_TOKEN; else process.env.COHORT_API_TOKEN = prev;
172
- }
173
- });
174
-
175
- test("configFromAgent: COHORT_API_KEY populates token when no config/COHORT_API_TOKEN/COHORT_TOKEN; COHORT_ORG_ID populates orgId", () => {
176
- // Snapshot + clear all four hq-documented vars to stay hermetic.
177
- const snap = {
178
- tok: process.env.COHORT_API_TOKEN,
179
- legacy: process.env.COHORT_TOKEN,
180
- key: process.env.COHORT_API_KEY,
181
- org: process.env.COHORT_ORG_ID,
182
- };
183
- delete process.env.COHORT_API_TOKEN;
184
- delete process.env.COHORT_TOKEN;
185
- delete process.env.COHORT_API_KEY;
186
- delete process.env.COHORT_ORG_ID;
187
- try {
188
- process.env.COHORT_API_KEY = "raw-org-key";
189
- process.env.COHORT_ORG_ID = "acme";
190
- const c = configFromAgent({ org: { cohort: { enabled: true, base: BASE } } });
191
- assert.equal(c.token, "raw-org-key", "COHORT_API_KEY is a token source");
192
- assert.equal(c.orgId, "acme", "COHORT_ORG_ID is an orgId fallback");
193
-
194
- // config token still wins over the env key.
195
- const c2 = configFromAgent({ org: { cohort: { enabled: true, base: BASE, token: "cfg-tok" } } });
196
- assert.equal(c2.token, "cfg-tok");
197
-
198
- // COHORT_API_TOKEN takes precedence over COHORT_API_KEY.
199
- process.env.COHORT_API_TOKEN = "primary";
200
- const c3 = configFromAgent({ org: { cohort: { enabled: true, base: BASE } } });
201
- assert.equal(c3.token, "primary");
202
- } finally {
203
- for (const [k, v] of [["COHORT_API_TOKEN", snap.tok], ["COHORT_TOKEN", snap.legacy], ["COHORT_API_KEY", snap.key], ["COHORT_ORG_ID", snap.org]]) {
204
- if (v === undefined) delete process.env[k]; else process.env[k] = v;
205
- }
206
- }
207
- });
208
-
209
- test("call/read: send x-org-id pin only when an orgId is supplied", async () => {
210
- const f1 = fakeFetch(() => ({ body: { ok: true, result: null } }));
211
- await call("registry.heartbeat", { id: "a" }, { base: BASE, token: TOKEN, orgId: "acme", fetchImpl: f1 });
212
- assert.equal(f1.calls[0].headers["x-org-id"], "acme");
213
-
214
- const f2 = fakeFetch(() => ({ body: { ok: true, result: null } }));
215
- await call("registry.heartbeat", { id: "a" }, { base: BASE, token: TOKEN, fetchImpl: f2 });
216
- assert.equal(f2.calls[0].headers["x-org-id"], undefined);
217
-
218
- const f3 = fakeFetch(() => ({ body: { members: [] } }));
219
- await read("directory", { base: BASE, token: TOKEN, orgId: "acme", fetchImpl: f3 });
220
- assert.equal(f3.calls[0].headers["x-org-id"], "acme");
221
- });
222
-
223
- // --- RPC headers + routing -------------------------------------------------
224
-
225
- test("call: posts to /api/v1/{method} (hq's canonical mount) with Bearer + x-org-protocol headers", async () => {
226
- const f = fakeFetch(() => ({ body: { ok: true, result: { id: "x" } } }));
227
- const frame = await call("registry.heartbeat", { id: "a" }, { base: BASE, token: TOKEN, fetchImpl: f });
228
- assert.deepEqual(frame, { ok: true, result: { id: "x" } });
229
- assert.equal(f.calls[0].url, `${BASE}/api/v1/registry.heartbeat`);
230
- assert.equal(f.calls[0].init.method, "POST");
231
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
232
- assert.equal(f.calls[0].headers["x-org-protocol"], String(PROTOCOL_VERSION));
233
- assert.equal(f.calls[0].headers["content-type"], "application/json");
234
- assert.equal(f.calls[0].init.body, JSON.stringify({ id: "a" }));
235
- });
236
-
237
- test("call: side-effecting method sends x-idempotency-key when supplied", async () => {
238
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
239
- await call("board.claim", { id: "item-1" }, { base: BASE, token: TOKEN, idempotencyKey: "key-123", fetchImpl: f });
240
- assert.equal(f.calls[0].headers["x-idempotency-key"], "key-123");
241
- });
242
-
243
- test("call: back-compat — a base already carrying the /v1 or /api/v1 mount is respected, not double-prefixed", async () => {
244
- const f1 = fakeFetch(() => ({ body: { ok: true, result: null } }));
245
- await call("registry.heartbeat", { id: "a" }, { base: `${BASE}/api/v1`, token: TOKEN, fetchImpl: f1 });
246
- assert.equal(f1.calls[0].url, `${BASE}/api/v1/registry.heartbeat`);
247
- const f2 = fakeFetch(() => ({ body: { ok: true, result: null } }));
248
- await call("registry.heartbeat", { id: "a" }, { base: `${BASE}/v1`, token: TOKEN, fetchImpl: f2 });
249
- assert.equal(f2.calls[0].url, `${BASE}/v1/registry.heartbeat`, "legacy bare /v1 mount honoured for back-compat");
250
- });
251
-
252
- test("call: idempotent method auto-derives an idempotency key from id", async () => {
253
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
254
- await call("board.create", { id: "item-7" }, { base: BASE, token: TOKEN, fetchImpl: f });
255
- assert.equal(f.calls[0].headers["x-idempotency-key"], "board.create:item-7");
256
- });
257
-
258
- test("call: non-side-effecting read-style call sends NO idempotency key", async () => {
259
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
260
- // registry.heartbeat is side-effecting but NOT idempotent and no key passed → none synthesised
261
- await call("registry.heartbeat", { id: "a" }, { base: BASE, token: TOKEN, fetchImpl: f });
262
- assert.equal(f.calls[0].headers["x-idempotency-key"], undefined);
263
- });
264
-
265
- test("call: pre-auth method (pairing.request) sends NO bearer token", async () => {
266
- const f = fakeFetch(() => ({ body: { ok: true, result: { status: "pending", code: "ABCD" } } }));
267
- await call("pairing.request", { agentId: "a", pubkey: "P" }, { base: BASE, token: TOKEN, fetchImpl: f });
268
- assert.equal(f.calls[0].headers.authorization, undefined);
269
- });
270
-
271
- test("call: unknown method → NOT_FOUND error frame, no fetch", async () => {
272
- const f = fakeFetch();
273
- const frame = await call("bogus.method", {}, { base: BASE, token: TOKEN, fetchImpl: f });
274
- assert.equal(frame.ok, false);
275
- assert.equal(frame.error.code, "NOT_FOUND");
276
- assert.equal(f.calls.length, 0);
277
- });
278
-
279
- test("call: missing base → BAD_REQUEST error frame (fail-open)", async () => {
280
- const frame = await call("board.claim", { id: "x" }, { token: TOKEN });
281
- assert.equal(frame.ok, false);
282
- assert.equal(frame.error.code, "BAD_REQUEST");
283
- });
284
-
285
- test("call: transport throw → INTERNAL error frame (fail-open, no throw)", async () => {
286
- const f = async () => { throw new Error("ECONNREFUSED"); };
287
- const frame = await call("board.claim", { id: "x" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
288
- assert.equal(frame.ok, false);
289
- assert.equal(frame.error.code, "INTERNAL");
290
- });
291
-
292
- test("call: HTTP 409 (claim race loser) maps to CONFLICT error frame", async () => {
293
- const f = fakeFetch(() => ({ ok: false, status: 409, body: { ok: false, error: { code: "CONFLICT", message: "lost race" } } }));
294
- const frame = await call("board.claim", { id: "x" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
295
- assert.equal(frame.ok, false);
296
- assert.equal(frame.error.code, "CONFLICT");
297
- });
298
-
299
- // --- typed helpers route to the right methods ------------------------------
300
-
301
- test("typed helpers route to their methods", async () => {
302
- const seen = [];
303
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
304
- const o = { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f };
305
- await register({ id: "a" }, o);
306
- await heartbeat({ id: "a" }, o);
307
- await presenceBeat({ id: "a" }, o);
308
- await createItem({ id: "i" }, o);
309
- await claimItem({ id: "i" }, o);
310
- await completeItem({ id: "i" }, o);
311
- assert.deepEqual(seen, [
312
- `${BASE}/api/v1/registry.register`,
313
- `${BASE}/api/v1/registry.heartbeat`,
314
- `${BASE}/api/v1/presence.beat`,
315
- `${BASE}/api/v1/board.create`,
316
- `${BASE}/api/v1/board.claim`,
317
- `${BASE}/api/v1/board.complete`,
318
- ]);
319
- });
320
-
321
- test("presenceBeat: surfaces directives from result", async () => {
322
- const f = fakeFetch(() => ({ body: { ok: true, result: { directives: ["halt"] } } }));
323
- const frame = await presenceBeat({ id: "a" }, { base: BASE, token: TOKEN, fetchImpl: f });
324
- assert.deepEqual(frame.result.directives, ["halt"]);
325
- });
326
-
327
- // --- phase-2 typed helpers: lease / handoff / board DAG / governance --------
328
-
329
- test("phase-2 helpers route to their /v1 methods", async () => {
330
- const seen = [];
331
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
332
- const o = { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f };
333
- await leaseClaim({ scope: "thread-ownership", resourceId: "r" }, o);
334
- await leaseHeartbeat({ scope: "thread-ownership", resourceId: "r", leaseToken: "lt" }, o);
335
- await leaseRelease({ scope: "thread-ownership", resourceId: "r", leaseToken: "lt" }, o);
336
- await handoffOffer({ handoffId: "h1", to: "bob" }, o);
337
- await handoffAccept({ handoffId: "h1" }, o);
338
- await handoffDecline({ handoffId: "h1" }, o);
339
- await handoffCancel({ handoffId: "h1" }, o);
340
- await boardDecompose({ itemId: "i", children: [] }, o);
341
- await boardAssign({ itemId: "i", assignee: "bob" }, o);
342
- await boardLink({ fromItemId: "i", toItemId: "j" }, o);
343
- await governanceStatus(o);
344
- assert.deepEqual(seen, [
345
- `${BASE}/api/v1/lease.claim`,
346
- `${BASE}/api/v1/lease.heartbeat`,
347
- `${BASE}/api/v1/lease.release`,
348
- `${BASE}/api/v1/handoff.offer`,
349
- `${BASE}/api/v1/handoff.accept`,
350
- `${BASE}/api/v1/handoff.decline`,
351
- `${BASE}/api/v1/handoff.cancel`,
352
- `${BASE}/api/v1/board.decompose`,
353
- `${BASE}/api/v1/board.assign`,
354
- `${BASE}/api/v1/board.link`,
355
- `${BASE}/api/v1/governance.status`,
356
- ]);
357
- });
358
-
359
- test("leaseClaim: side-effecting → sends Bearer + x-idempotency-key when supplied", async () => {
360
- const f = fakeFetch(() => ({ body: { ok: true, result: { token: "lt-1" } } }));
361
- const frame = await leaseClaim({ scope: "thread-ownership", resourceId: "r" }, { base: BASE, token: TOKEN, idempotencyKey: "key-1", fetchImpl: f });
362
- assert.equal(frame.result.token, "lt-1");
363
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
364
- assert.equal(f.calls[0].headers["x-idempotency-key"], "key-1");
365
- });
366
-
367
- test("handoffOffer: governance-gated → surfaces GOVERNANCE_NOT_READY (HTTP 423)", async () => {
368
- const f = fakeFetch(() => ({ ok: false, status: 423, body: { ok: false, error: { code: "GOVERNANCE_NOT_READY", message: "not ready" } } }));
369
- const frame = await handoffOffer({ handoffId: "h1", to: "bob" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
370
- assert.equal(frame.ok, false);
371
- assert.equal(frame.error.code, "GOVERNANCE_NOT_READY");
372
- });
373
-
374
- test("governanceStatus: returns the readiness result frame", async () => {
375
- const f = fakeFetch(() => ({ body: { ok: true, result: { governanceReady: false, decisionRightsCount: 0, signingLive: true } } }));
376
- const frame = await governanceStatus({ base: BASE, token: TOKEN, fetchImpl: f });
377
- assert.equal(frame.result.governanceReady, false);
378
- assert.equal(frame.result.decisionRightsCount, 0);
379
- assert.equal(f.calls[0].url, `${BASE}/api/v1/governance.status`);
380
- });
381
-
382
- // --- pairing handshake -----------------------------------------------------
383
-
384
- test("pairRequest: POSTs pubkey pre-auth, returns code", async () => {
385
- const f = fakeFetch(() => ({ body: { ok: true, result: { status: "pending", code: "WXYZ" } } }));
386
- const frame = await pairRequest({ base: BASE, agentId: "alex", displayName: "Alex", pubkey: "PEM", fetchImpl: f });
387
- assert.equal(frame.ok, true);
388
- assert.equal(frame.result.code, "WXYZ");
389
- assert.equal(f.calls[0].url, `${BASE}/api/v1/pairing.request`);
390
- assert.equal(f.calls[0].headers.authorization, undefined);
391
- const body = JSON.parse(f.calls[0].init.body);
392
- assert.equal(body.agentId, "alex");
393
- assert.equal(body.pubkey, "PEM");
394
- });
395
-
396
- test("pairRequest: missing fields → BAD_REQUEST, no fetch", async () => {
397
- const f = fakeFetch();
398
- assert.equal((await pairRequest({ base: BASE, fetchImpl: f })).error.code, "BAD_REQUEST");
399
- assert.equal((await pairRequest({ agentId: "a", pubkey: "P", fetchImpl: f })).error.code, "BAD_REQUEST");
400
- assert.equal(f.calls.length, 0);
401
- });
402
-
403
- test("pairApprove: authed admin call routes to pairing.approve with Bearer", async () => {
404
- const f = fakeFetch(() => ({ body: { ok: true, result: { status: "approved" } } }));
405
- const frame = await pairApprove({ code: "WXYZ" }, { base: BASE, token: TOKEN, fetchImpl: f });
406
- assert.equal(frame.result.status, "approved");
407
- assert.equal(f.calls[0].url, `${BASE}/api/v1/pairing.approve`);
408
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
409
- assert.equal(JSON.parse(f.calls[0].init.body).code, "WXYZ");
410
- });
411
-
412
- // --- calling wrappers (SP3/SP10 lifecycle + agent-operability) --------------
413
-
414
- test("calling wrappers route to their /v1 methods", async () => {
415
- const seen = [];
416
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
417
- const o = { base: BASE, token: TOKEN, fetchImpl: f };
418
- await callingStart({ channelId: "c" }, o);
419
- await callingJoin({ callId: "k" }, o);
420
- await callingInvite({ callId: "k", memberIds: ["m"] }, o);
421
- await callingEnd({ callId: "k" }, o);
422
- await callingAddTranscriptLine({ callId: "k", text: "hi" }, o);
423
- await callingChat({ callId: "k", text: "yo" }, o);
424
- assert.deepEqual(seen, [
425
- `${BASE}/api/v1/calling.start`,
426
- `${BASE}/api/v1/calling.join`,
427
- `${BASE}/api/v1/calling.invite`,
428
- `${BASE}/api/v1/calling.end`,
429
- `${BASE}/api/v1/calling.addTranscriptLine`,
430
- `${BASE}/api/v1/calling.chat`,
431
- ]);
432
- });
433
-
434
- // --- calling working sessions + vision fusion (2026-08) ---------------------
435
-
436
- test("calling working-session wrappers route to their /v1 methods", async () => {
437
- const seen = [];
438
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
439
- const o = { base: BASE, token: TOKEN, fetchImpl: f };
440
- await callingAppShareStart({ callId: "k", surface: { kind: "doc", ref: "f-1", title: "Q3 plan" } }, o);
441
- await callingAppShareAct({ callId: "k", sessionId: "s1", steps: [{ k: "scroll", anchor: "top" }] }, o);
442
- await callingAppShareEnd({ callId: "k", sessionId: "s1" }, o);
443
- await callingGetAppShare({ callId: "k" }, o);
444
- await callingGetVisualContext({ callId: "k", limit: 20 }, o);
445
- await callingGetCallEvents({ callId: "k", limit: 30 }, o);
446
- assert.deepEqual(seen, [
447
- `${BASE}/api/v1/calling.appShareStart`,
448
- `${BASE}/api/v1/calling.appShareAct`,
449
- `${BASE}/api/v1/calling.appShareEnd`,
450
- `${BASE}/api/v1/calling.getAppShare`,
451
- `${BASE}/api/v1/calling.getVisualContext`,
452
- `${BASE}/api/v1/calling.getCallEvents`,
453
- ]);
454
- });
455
-
456
- test("callingAppShareAct: side-effecting → Bearer + supplied idempotency key, POSTs the step batch", async () => {
457
- const f = fakeFetch(() => ({ body: { ok: true, result: { seq: 2 } } }));
458
- const steps = [{ k: "highlight", anchor: "block:3", note: "revenue line" }];
459
- const frame = await callingAppShareAct(
460
- { callId: "k", sessionId: "s1", steps },
461
- { base: BASE, token: TOKEN, idempotencyKey: "ik-1", fetchImpl: f },
462
- );
463
- assert.equal(frame.result.seq, 2);
464
- assert.equal(f.calls[0].init.method, "POST");
465
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
466
- assert.equal(f.calls[0].headers["x-idempotency-key"], "ik-1");
467
- assert.deepEqual(JSON.parse(f.calls[0].init.body).steps, steps);
468
- });
469
-
470
- test("callingGetAppShare: read-style call sends NO idempotency key; null session is a normal result", async () => {
471
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
472
- const frame = await callingGetAppShare({ callId: "k" }, { base: BASE, token: TOKEN, fetchImpl: f });
473
- assert.equal(frame.ok, true);
474
- assert.equal(frame.result, null, "no active session is a result, not an error");
475
- assert.equal(f.calls[0].headers["x-idempotency-key"], undefined);
476
- });
477
-
478
- test("callingAppShareStart: CONFLICT while another member presents surfaces as an error frame (fail-open)", async () => {
479
- const f = fakeFetch(() => ({ ok: false, status: 409, body: { ok: false, error: { code: "CONFLICT", message: "another member is presenting" } } }));
480
- const frame = await callingAppShareStart({ callId: "k", surface: { kind: "doc", ref: "f-1" } }, { base: BASE, token: TOKEN, fetchImpl: f });
481
- assert.equal(frame.ok, false);
482
- assert.equal(frame.error.code, "CONFLICT");
483
- });
484
-
485
- test("callingAddTranscriptLine: side-effecting → sends Bearer, POSTs the line body", async () => {
486
- const f = fakeFetch(() => ({ body: { ok: true, result: { lineId: "l1" } } }));
487
- const frame = await callingAddTranscriptLine({ callId: "k", text: "final line" }, { base: BASE, token: TOKEN, fetchImpl: f });
488
- assert.equal(frame.result.lineId, "l1");
489
- assert.equal(f.calls[0].init.method, "POST");
490
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
491
- assert.equal(JSON.parse(f.calls[0].init.body).text, "final line");
492
- });
493
-
494
- test("callingChat: CONFLICT on an ended call surfaces as an error frame (fail-open)", async () => {
495
- const f = fakeFetch(() => ({ ok: false, status: 409, body: { ok: false, error: { code: "CONFLICT", message: "call has already ended" } } }));
496
- const frame = await callingChat({ callId: "k", text: "late" }, { base: BASE, token: TOKEN, fetchImpl: f });
497
- assert.equal(frame.ok, false);
498
- assert.equal(frame.error.code, "CONFLICT");
499
- });
500
-
501
- // --- branding wrappers (Brand Studio v2 write surface) ---------------------
502
-
503
- test("branding wrappers route to their /v1 methods", async () => {
504
- const seen = [];
505
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
506
- const o = { base: BASE, token: TOKEN, fetchImpl: f };
507
- await brandingRegenerate({}, o);
508
- await brandingRegenerateTemplates({}, o);
509
- await brandingRegenerateTemplate({ slug: "hero" }, o);
510
- await brandingRegenerateImages({}, o);
511
- await brandingUploadImage({ slot: "logo", dataUrl: "data:," }, o);
512
- await brandingAmendArtifact({ key: "tagline", instruction: "punchier" }, o);
513
- await brandingAmendTemplate({ slug: "hero", instruction: "warmer" }, o);
514
- await brandingCloneTemplate({ baseRef: "registry:hero" }, o);
515
- await brandingDeleteTemplate({ slug: "hero" }, o);
516
- await brandingRestoreVersion({ targetKind: "TEMPLATE", ref: "hero", seq: 2 }, o);
517
- await brandingUndo({ targetKind: "ARTIFACT", ref: "tagline" }, o);
518
- await brandingRedo({ targetKind: "ARTIFACT", ref: "tagline" }, o);
519
- await brandingListVersions({ targetKind: "TEMPLATE", ref: "hero" }, o);
520
- await brandingExportTemplate({ templateId: "hero", sizeId: "desktop", theme: "light" }, o);
521
- assert.deepEqual(seen, [
522
- `${BASE}/api/v1/branding.regenerate`,
523
- `${BASE}/api/v1/branding.regenerateTemplates`,
524
- `${BASE}/api/v1/branding.regenerateTemplate`,
525
- `${BASE}/api/v1/branding.regenerateImages`,
526
- `${BASE}/api/v1/branding.uploadImage`,
527
- `${BASE}/api/v1/branding.amendArtifact`,
528
- `${BASE}/api/v1/branding.amendTemplate`,
529
- `${BASE}/api/v1/branding.cloneTemplate`,
530
- `${BASE}/api/v1/branding.deleteTemplate`,
531
- `${BASE}/api/v1/branding.restoreVersion`,
532
- `${BASE}/api/v1/branding.undo`,
533
- `${BASE}/api/v1/branding.redo`,
534
- `${BASE}/api/v1/branding.listVersions`,
535
- `${BASE}/api/v1/branding.exportTemplate`,
536
- ]);
537
- });
538
-
539
- test("design read/propose wrappers route to their /v1 branding.* methods", async () => {
540
- const {
541
- brandingGetFoundation, brandingGetVoice, brandingListTemplates, brandingRenderTemplate,
542
- brandingRewriteInVoice, brandingExportKit, brandingGenerateImage, brandingProposeChange,
543
- brandingSaveFoundation, brandingRestoreFoundation,
544
- } = await import("./client.mjs");
545
- const seen = [];
546
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
547
- const o = { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f };
548
- await brandingGetFoundation({ historyLimit: 5 }, o);
549
- await brandingGetVoice({}, o);
550
- await brandingListTemplates({ category: "email" }, o);
551
- await brandingRenderTemplate({ templateId: "hero", format: "html" }, o);
552
- await brandingRewriteInVoice({ text: "we are excited to announce" }, o);
553
- await brandingExportKit({ unit: "rem" }, o);
554
- await brandingGenerateImage({ budgetCents: 0 }, o);
555
- await brandingProposeChange({ patch: { fonts: { display: "Söhne" } }, note: "tighter display face" }, o);
556
- await brandingSaveFoundation({ foundation: {}, expectedVersionId: null }, o);
557
- await brandingRestoreFoundation({ versionId: "v9" }, o);
558
- assert.deepEqual(seen, [
559
- `${BASE}/api/v1/branding.getFoundation`,
560
- `${BASE}/api/v1/branding.getVoice`,
561
- `${BASE}/api/v1/branding.listTemplates`,
562
- `${BASE}/api/v1/branding.renderTemplate`,
563
- `${BASE}/api/v1/branding.rewriteInVoice`,
564
- `${BASE}/api/v1/branding.exportKit`,
565
- `${BASE}/api/v1/branding.generateImage`,
566
- `${BASE}/api/v1/branding.proposeChange`,
567
- `${BASE}/api/v1/branding.saveFoundation`,
568
- `${BASE}/api/v1/branding.restoreFoundation`,
569
- ]);
570
- // budgetCents 0 is the QUOTE call — it must survive to the wire, not be
571
- // dropped as falsy, or a caller asking for a price silently spends money.
572
- assert.equal(JSON.parse(f.calls[6].init.body).budgetCents, 0);
573
- });
574
-
575
- test("branding writes send Bearer but NO idempotency key (surface owns its own versioned audit)", async () => {
576
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
577
- await brandingAmendTemplate({ slug: "hero", instruction: "warmer" }, { base: BASE, token: TOKEN, fetchImpl: f });
578
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
579
- assert.equal(f.calls[0].headers["x-idempotency-key"], undefined);
580
- });
581
-
582
- test("brandingExportTemplate: read surface returns the render result frame", async () => {
583
- const f = fakeFetch(() => ({ body: { ok: true, result: { dataUrl: "data:image/png;base64,AAAA" } } }));
584
- const frame = await brandingExportTemplate({ templateId: "hero" }, { base: BASE, token: TOKEN, fetchImpl: f });
585
- assert.equal(frame.result.dataUrl, "data:image/png;base64,AAAA");
586
- assert.equal(f.calls[0].url, `${BASE}/api/v1/branding.exportTemplate`);
587
- });
588
-
589
- // --- reads (GET) -----------------------------------------------------------
590
-
591
- test("read: GETs /v1/{path}, Bearer, no content-type, returns bare payload", async () => {
592
- const f = fakeFetch(() => ({ body: { seq: 9, agents: [] } }));
593
- const r = await read("snapshot", { base: BASE, token: TOKEN, fetchImpl: f });
594
- assert.equal(r.ok, true);
595
- assert.deepEqual(r.payload, { seq: 9, agents: [] });
596
- assert.equal(f.calls[0].init.method, "GET");
597
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
598
- assert.equal(f.calls[0].headers["x-org-protocol"], String(PROTOCOL_VERSION));
599
- assert.equal(f.calls[0].headers["content-type"], undefined);
600
- });
601
-
602
- test("read: passes If-None-Match and surfaces 304 notModified + ETag", async () => {
603
- const f = fakeFetch(() => ({ ok: true, status: 304, respHeaders: { etag: "v2" } }));
604
- const r = await read("directory", { base: BASE, token: TOKEN, etag: "v2", fetchImpl: f });
605
- assert.equal(r.notModified, true);
606
- assert.equal(r.status, 304);
607
- assert.equal(f.calls[0].headers["if-none-match"], "v2");
608
- });
609
-
610
- test("read: surfaces ETag on a 200 response", async () => {
611
- const f = fakeFetch(() => ({ body: { agents: [] }, respHeaders: { etag: "v3" } }));
612
- const r = await read("directory", { base: BASE, token: TOKEN, fetchImpl: f });
613
- assert.equal(r.etag, "v3");
614
- });
615
-
616
- test("read: HTTP error returns error frame body + status", async () => {
617
- const f = fakeFetch(() => ({ ok: false, status: 401, body: { ok: false, error: { code: "UNAUTHORIZED", message: "bad token" } } }));
618
- const r = await read("snapshot", { base: BASE, token: "stale", fetchImpl: f });
619
- assert.equal(r.ok, false);
620
- assert.equal(r.status, 401);
621
- assert.equal(r.error.code, "UNAUTHORIZED");
622
- });
623
-
624
- test("read: transport throw → fail-open error, no throw", async () => {
625
- const r = await read("snapshot", { base: BASE, token: TOKEN, fetchImpl: async () => { throw new Error("down"); } });
626
- assert.equal(r.ok, false);
627
- assert.equal(r.error.code, "INTERNAL");
628
- });
629
-
630
- // --- read helpers parse shapes + fail open ---------------------------------
631
-
632
- test("listReady: parses array and {items:[]}, [] on error", async () => {
633
- assert.deepEqual(await listReady({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: [{ id: "1" }] })) }), [{ id: "1" }]);
634
- assert.deepEqual(await listReady({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: { items: [{ id: "2" }] } })) }), [{ id: "2" }]);
635
- assert.deepEqual(await listReady({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), []);
636
- });
637
-
638
- test("fetchEvents: builds cursor+limit query, parses array/{events:[]}", async () => {
639
- const f = fakeFetch(() => ({ body: { events: [{ seq: 6 }] } }));
640
- const ev = await fetchEvents(5, { base: BASE, token: TOKEN, fetchImpl: f });
641
- assert.deepEqual(ev, [{ seq: 6 }]);
642
- assert.match(f.calls[0].url, /\/v1\/events\?cursor=5&limit=500$/);
643
- // custom limit
644
- const f2 = fakeFetch(() => ({ body: [] }));
645
- await fetchEvents(0, { base: BASE, token: TOKEN, limit: 50, fetchImpl: f2 });
646
- assert.match(f2.calls[0].url, /cursor=0&limit=50$/);
647
- });
648
-
649
- test("fetchEvents: [] on transport failure", async () => {
650
- assert.deepEqual(await fetchEvents(0, { base: BASE, token: TOKEN, fetchImpl: async () => { throw new Error("x"); } }), []);
651
- });
652
-
653
- test("fetchSnapshot: returns raw signed payload (does not verify), null on error", async () => {
654
- const snap = { seq: 3, agents: [], sig: "BASE64SIG" };
655
- assert.deepEqual(await fetchSnapshot({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: snap })) }), snap);
656
- assert.equal(await fetchSnapshot({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), null);
657
- });
658
-
659
- // --- back-compat surface (drop-in for cohort-client.mjs) ------------------
660
-
661
- const ON = { org: { cohort: { enabled: true, base: BASE } } };
662
- const OFF = { org: { cohort: { enabled: false } } };
663
-
664
- test("publishEntry: no-op disabled; registers via /v1 when enabled", async () => {
665
- assert.deepEqual(await publishEntry({ cfg: OFF, entry: { id: "a" } }), { ok: false, skipped: true });
666
- assert.deepEqual(await publishEntry({ cfg: ON, entry: {} }), { ok: false, skipped: false, reason: "no-entry" });
667
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
668
- const r = await publishEntry({ cfg: ON, entry: { id: "alex-ai", name: "Alex" }, fetchImpl: f });
669
- assert.equal(r.ok, true);
670
- assert.equal(r.status, 200);
671
- assert.equal(f.calls[0].url, `${BASE}/api/v1/registry.register`);
672
- assert.equal(f.calls[0].init.method, "POST");
673
- assert.equal(f.calls[0].headers["x-idempotency-key"], "registry.register:alex-ai");
674
- });
675
-
676
- test("publishEntry: server error → {ok:false} (fail-open shape preserved)", async () => {
677
- const f = fakeFetch(() => ({ ok: false, status: 500, body: { ok: false, error: { code: "INTERNAL", message: "boom" } } }));
678
- const r = await publishEntry({ cfg: ON, entry: { id: "x" }, fetchImpl: f });
679
- assert.equal(r.ok, false);
680
- });
681
-
682
- test("publishEntry: projects a rich assembleSelfEntry onto the strict registerSchema", async () => {
683
- // The hq registerSchema is .strict() — a raw entry with an archetype OBJECT and
684
- // extra fields would 400. publishEntry must trim to {displayName,archetype:string,
685
- // humanSponsor,card}; everything else rides under `card`.
686
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
687
- const entry = {
688
- id: "robin-ai",
689
- name: "Robin",
690
- fullName: "Robin Vega",
691
- archetype: { function: "engineering", altitude: "vp", label: "VP Eng" },
692
- principal: { fullName: "Sam Human", title: "CEO" },
693
- towers: [{ id: "t1", name: "Platform" }],
694
- focus: [{ title: "ship" }],
695
- presence: { active: 2 },
696
- };
697
- await publishEntry({ cfg: ON, entry, fetchImpl: f });
698
- const sent = JSON.parse(f.calls[0].init.body);
699
- assert.deepEqual(Object.keys(sent).sort(), ["archetype", "card", "displayName", "humanSponsor"].sort());
700
- assert.equal(sent.displayName, "Robin Vega");
701
- assert.equal(sent.archetype, "VP Eng");
702
- assert.equal(sent.humanSponsor, "Sam Human");
703
- assert.equal(sent.card.id, "robin-ai");
704
- assert.deepEqual(sent.card.towers, entry.towers);
705
- });
706
-
707
- test("fetchDirectory: [] disabled; parses array + {members:[]} + {agents:[]}; [] on error", async () => {
708
- assert.deepEqual(await fetchDirectory({ cfg: OFF }), []);
709
- const arr = await fetchDirectory({ cfg: ON, fetchImpl: fakeFetch(() => ({ body: [{ id: "x" }] })) });
710
- assert.equal(arr.length, 1);
711
- assert.equal(arr[0].id, "x");
712
- // hq shape: GET /v1/directory → { members: [...] } with per-member status snapshot
713
- const members = await fetchDirectory({ cfg: ON, fetchImpl: fakeFetch(() => ({ body: { members: [{ id: "m1", status: { state: "busy" } }, { id: "m2", status: null }] } })) });
714
- assert.equal(members.length, 2);
715
- assert.equal(members[0].status.state, "busy");
716
- const wrapped = await fetchDirectory({ cfg: ON, fetchImpl: fakeFetch(() => ({ body: { agents: [{ id: "y" }, { id: "z" }] } })) });
717
- assert.equal(wrapped.length, 2);
718
- const errd = await fetchDirectory({ cfg: ON, fetchImpl: async () => { throw new Error("net down"); } });
719
- assert.deepEqual(errd, []);
720
- });
721
-
722
- // --- phase-3 typed helpers: approvals / decisions / cost / policy ----------
723
-
724
- test("phase-3 RPC helpers route to their /v1 methods", async () => {
725
- const seen = [];
726
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
727
- const o = { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f };
728
- await approvalRequest({ id: "ap-1", kind: "exec", subject: "x", payload_hash: "h" }, o);
729
- await approvalResolve({ id: "ap-1", decision: "approved" }, o);
730
- await approvalGet({ id: "ap-1" }, o);
731
- await approvalList({ status: "pending" }, o);
732
- await decisionPropose({ id: "d-1", title: "t" }, o);
733
- await decisionAdopt({ id: "d-1" }, o);
734
- await decisionSupersede({ id: "d-1", supersededBy: "d-2" }, o);
735
- await costReport({ rows: [{ id: "r-1" }] }, o);
736
- await policyPublish({ bundleId: "b", version: 1, kind: "x", content: "{}", content_sig: "s", source_commit: "c" }, o);
737
- assert.deepEqual(seen, [
738
- `${BASE}/api/v1/approval.request`,
739
- `${BASE}/api/v1/approval.resolve`,
740
- `${BASE}/api/v1/approval.get`,
741
- `${BASE}/api/v1/approval.list`,
742
- `${BASE}/api/v1/decision.propose`,
743
- `${BASE}/api/v1/decision.adopt`,
744
- `${BASE}/api/v1/decision.supersede`,
745
- `${BASE}/api/v1/cost.report`,
746
- `${BASE}/api/v1/policy.publish`,
747
- ]);
748
- });
749
-
750
- test("approvalRequest: idempotent method auto-derives x-idempotency-key from id", async () => {
751
- const f = fakeFetch(() => ({ body: { ok: true, result: { id: "ap-9" } } }));
752
- await approvalRequest({ id: "ap-9", kind: "exec", payload_hash: "h" }, { base: BASE, token: TOKEN, fetchImpl: f });
753
- assert.equal(f.calls[0].headers["x-idempotency-key"], "approval.request:ap-9");
754
- });
755
-
756
- test("approvalResolve: needs approval.decide scope server-side → surfaces FORBIDDEN_SCOPE", async () => {
757
- const f = fakeFetch(() => ({ ok: false, status: 403, body: { ok: false, error: { code: "FORBIDDEN_SCOPE", message: "approval.decide required" } } }));
758
- const frame = await approvalResolve({ id: "ap-1", decision: "approved" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
759
- assert.equal(frame.ok, false);
760
- assert.equal(frame.error.code, "FORBIDDEN_SCOPE");
761
- });
762
-
763
- test("decisionAdopt: governance-gated → surfaces GOVERNANCE_NOT_READY (423)", async () => {
764
- const f = fakeFetch(() => ({ ok: false, status: 423, body: { ok: false, error: { code: "GOVERNANCE_NOT_READY", message: "x" } } }));
765
- const frame = await decisionAdopt({ id: "d-1" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
766
- assert.equal(frame.error.code, "GOVERNANCE_NOT_READY");
767
- });
768
-
769
- test("approvalWait: GETs the bounded long-poll, clamps timeoutMs to 55000", async () => {
770
- const f = fakeFetch(() => ({ body: { id: "ap-1", status: "approved" } }));
771
- const r = await approvalWait({ id: "ap-1", timeoutMs: 999999 }, { base: BASE, token: TOKEN, fetchImpl: f });
772
- assert.equal(r.ok, true);
773
- assert.equal(r.payload.status, "approved");
774
- assert.match(f.calls[0].url, /\/v1\/approval\.wait\?id=ap-1&timeoutMs=55000$/);
775
- assert.equal(f.calls[0].init.method, "GET");
776
- });
777
-
778
- test("approvalWait: default (no timeoutMs) uses the 55000 ceiling; missing id → BAD_REQUEST", async () => {
779
- const f = fakeFetch(() => ({ body: { id: "ap-2", status: "pending" } }));
780
- await approvalWait({ id: "ap-2" }, { base: BASE, token: TOKEN, fetchImpl: f });
781
- assert.match(f.calls[0].url, /timeoutMs=55000$/);
782
- const bad = await approvalWait({}, { base: BASE, token: TOKEN, fetchImpl: f });
783
- assert.equal(bad.ok, false);
784
- assert.equal(bad.error.code, "BAD_REQUEST");
785
- });
786
-
787
- test("decisionList: parses array + {decisions:[]}, [] on error; appends status query", async () => {
788
- assert.deepEqual(await decisionList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: [{ id: "d1" }] })) }), [{ id: "d1" }]);
789
- const f = fakeFetch(() => ({ body: { decisions: [{ id: "d2" }] } }));
790
- const r = await decisionList({ base: BASE, token: TOKEN, status: "adopted", fetchImpl: f });
791
- assert.deepEqual(r, [{ id: "d2" }]);
792
- assert.match(f.calls[0].url, /\/v1\/decision\.list\?status=adopted$/);
793
- assert.deepEqual(await decisionList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), []);
794
- });
795
-
796
- test("costRollup: returns bare payload, appends day/agent query, null on error", async () => {
797
- const f = fakeFetch(() => ({ body: { day: "2026-06-11", byAgent: {} } }));
798
- const r = await costRollup({ base: BASE, token: TOKEN, day: "2026-06-11", agent: "alex", fetchImpl: f });
799
- assert.equal(r.day, "2026-06-11");
800
- assert.match(f.calls[0].url, /\/v1\/cost\.rollup\?day=2026-06-11&agent=alex$/);
801
- assert.equal(await costRollup({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), null);
802
- });
803
-
804
- test("policyFetch: returns raw signed bundle (does not verify), null on error; appends kind", async () => {
805
- const bundle = { kind: "communication-style", version: 7, content: "{}", content_sig: "SIG" };
806
- const f = fakeFetch(() => ({ body: bundle }));
807
- const r = await policyFetch({ base: BASE, token: TOKEN, kind: "communication-style", fetchImpl: f });
808
- assert.deepEqual(r, bundle);
809
- assert.match(f.calls[0].url, /\/v1\/policy\?kind=communication-style$/);
810
- assert.equal(await policyFetch({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 404, body: {} })) }), null);
811
- });
812
-
813
- test("policyPublish: admin reserved namespace — surfaces FORBIDDEN_SCOPE for a non-admin token", async () => {
814
- const f = fakeFetch(() => ({ ok: false, status: 403, body: { ok: false, error: { code: "FORBIDDEN_SCOPE", message: "admin required" } } }));
815
- const frame = await policyPublish({ bundleId: "b", version: 1, kind: "x", content: "{}", content_sig: "s", source_commit: "c" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
816
- assert.equal(frame.error.code, "FORBIDDEN_SCOPE");
817
- });
818
-
819
- test("fetchDirectory: GETs /v1/directory; Bearer set when a token is configured", async () => {
820
- // no token configured on ON → no authorization header
821
- const f1 = fakeFetch(() => ({ body: { agents: [] } }));
822
- await fetchDirectory({ cfg: ON, fetchImpl: f1 });
823
- assert.equal(f1.calls[0].url, `${BASE}/api/v1/directory`);
824
- assert.equal(f1.calls[0].headers.authorization, undefined);
825
- // token in config → Bearer header present
826
- const f2 = fakeFetch(() => ({ body: { agents: [] } }));
827
- await fetchDirectory({ cfg: { org: { cohort: { enabled: true, base: BASE, token: "cfg-tok" } } }, fetchImpl: f2 });
828
- assert.equal(f2.calls[0].headers.authorization, "Bearer cfg-tok");
829
- });
830
-
831
- // --- phase-4 typed helpers: knowledge plane / contacts / meetings ----------
832
-
833
- test("phase-4 RPC helpers route to their /v1 methods", async () => {
834
- const seen = [];
835
- const f = fakeFetch((url) => { seen.push(url); return { body: { ok: true, result: null } }; });
836
- const o = { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f };
837
- await knowledgeAppend({ id: "k-1", text: "episode" }, o);
838
- await knowledgeReplace({ id: "k-1", expectedVersion: 2, text: "v2" }, o);
839
- await knowledgeRewrite({ id: "k-1", text: "owned rewrite" }, o);
840
- await knowledgeInvalidate({ id: "k-1", reason: "stale" }, o);
841
- await knowledgeSearch({ query: "deal terms" }, o);
842
- await contactsUpsert({ id: "c-1", name: "Jordan" }, o);
843
- await meetingsRecord({ id: "m-1", title: "board sync" }, o);
844
- assert.deepEqual(seen, [
845
- `${BASE}/api/v1/knowledge.append`,
846
- `${BASE}/api/v1/knowledge.replace`,
847
- `${BASE}/api/v1/knowledge.rewrite`,
848
- `${BASE}/api/v1/knowledge.invalidate`,
849
- `${BASE}/api/v1/knowledge.search`,
850
- `${BASE}/api/v1/contacts.upsert`,
851
- `${BASE}/api/v1/meetings.record`,
852
- ]);
853
- });
854
-
855
- test("knowledgeAppend: idempotent → auto-derives x-idempotency-key from id; Bearer set", async () => {
856
- const f = fakeFetch(() => ({ body: { ok: true, result: { id: "k-7" } } }));
857
- await knowledgeAppend({ id: "k-7", text: "episode" }, { base: BASE, token: TOKEN, fetchImpl: f });
858
- assert.equal(f.calls[0].headers["x-idempotency-key"], "knowledge.append:k-7");
859
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
860
- });
861
-
862
- test("knowledgeReplace: CAS stale version → surfaces CONFLICT (409)", async () => {
863
- const f = fakeFetch(() => ({ ok: false, status: 409, body: { ok: false, error: { code: "CONFLICT", message: "stale version" } } }));
864
- const frame = await knowledgeReplace({ id: "k-1", expectedVersion: 1, text: "x" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
865
- assert.equal(frame.ok, false);
866
- assert.equal(frame.error.code, "CONFLICT");
867
- });
868
-
869
- test("knowledgeRewrite: non-owner → surfaces FORBIDDEN_SCOPE (403)", async () => {
870
- const f = fakeFetch(() => ({ ok: false, status: 403, body: { ok: false, error: { code: "FORBIDDEN_SCOPE", message: "owner only" } } }));
871
- const frame = await knowledgeRewrite({ id: "k-1", text: "x" }, { base: BASE, token: TOKEN, idempotencyKey: "k", fetchImpl: f });
872
- assert.equal(frame.error.code, "FORBIDDEN_SCOPE");
873
- });
874
-
875
- test("knowledgeSearch: side-effecting (POST), Bearer set, posts the query body", async () => {
876
- const f = fakeFetch(() => ({ body: { ok: true, result: { facts: [{ id: "k-1" }], returned_ids: ["k-1"], groups_considered: ["org"] } } }));
877
- const frame = await knowledgeSearch({ query: "q", group: "org", limit: 5 }, { base: BASE, token: TOKEN, fetchImpl: f });
878
- assert.equal(f.calls[0].init.method, "POST");
879
- assert.equal(f.calls[0].url, `${BASE}/api/v1/knowledge.search`);
880
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
881
- // The wire contract canonicalises `query`→`q` (hq reads `p.q ?? p.query`) and
882
- // keeps the legacy name alongside for an older server.
883
- assert.deepEqual(JSON.parse(f.calls[0].init.body), { query: "q", q: "q", group: "org", limit: 5 });
884
- assert.deepEqual(frame.result.returned_ids, ["k-1"]);
885
- });
886
-
887
- test("contactsList: GETs /v1/contacts.list, parses array + {contacts:[]}, [] on error", async () => {
888
- assert.deepEqual(await contactsList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: [{ id: "c1" }] })) }), [{ id: "c1" }]);
889
- const f = fakeFetch(() => ({ body: { contacts: [{ id: "c2" }] } }));
890
- const r = await contactsList({ base: BASE, token: TOKEN, q: "jord", group: "org", limit: 10, fetchImpl: f });
891
- assert.deepEqual(r, [{ id: "c2" }]);
892
- assert.match(f.calls[0].url, /\/v1\/contacts\.list\?q=jord&group=org&limit=10$/);
893
- assert.deepEqual(await contactsList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), []);
894
- });
895
-
896
- test("meetingsList: GETs /v1/meetings.list, parses array + {meetings:[]}, [] on error; appends since", async () => {
897
- assert.deepEqual(await meetingsList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: [{ id: "m1" }] })) }), [{ id: "m1" }]);
898
- const f = fakeFetch(() => ({ body: { meetings: [{ id: "m2" }] } }));
899
- const r = await meetingsList({ base: BASE, token: TOKEN, since: "2026-06-01", fetchImpl: f });
900
- assert.deepEqual(r, [{ id: "m2" }]);
901
- assert.match(f.calls[0].url, /\/v1\/meetings\.list\?since=2026-06-01$/);
902
- assert.deepEqual(await meetingsList({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 500, body: {} })) }), []);
903
- });
904
-
905
- // --- org credential broker --------------------------------------------------
906
-
907
- test("credentialLease: POSTs /v1/credential.lease with Bearer + protocol; returns plaintext in the result", async () => {
908
- const f = fakeFetch(() => ({ body: { ok: true, result: { provider: "deepseek", value: "sk-leased", ttlMs: 600000, expiresAt: "2026-06-11T00:10:00Z" } } }));
909
- const frame = await credentialLease({ provider: "deepseek" }, { base: BASE, token: TOKEN, fetchImpl: f });
910
- assert.equal(f.calls[0].init.method, "POST");
911
- assert.equal(f.calls[0].url, `${BASE}/api/v1/credential.lease`);
912
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
913
- assert.equal(f.calls[0].headers["x-org-protocol"], String(PROTOCOL_VERSION));
914
- assert.deepEqual(JSON.parse(f.calls[0].init.body), { provider: "deepseek" });
915
- assert.equal(frame.result.value, "sk-leased");
916
- assert.equal(frame.result.ttlMs, 600000);
917
- });
918
-
919
- test("credentialLease: side-effecting, but NOT auto-idempotent (each lease is a fresh audited grant)", async () => {
920
- const f = fakeFetch(() => ({ body: { ok: true, result: { value: "x" } } }));
921
- await credentialLease({ provider: "moonshot" }, { base: BASE, token: TOKEN, fetchImpl: f });
922
- assert.equal(f.calls[0].headers["x-idempotency-key"], undefined, "no auto key on a non-idempotent method");
923
- });
924
-
925
- test("credentialLease: FORBIDDEN_SCOPE (role not permitted) surfaces as an error frame (403)", async () => {
926
- const f = fakeFetch(() => ({ ok: false, status: 403, body: { ok: false, error: { code: "FORBIDDEN_SCOPE", message: "role not permitted" } } }));
927
- const frame = await credentialLease({ provider: "deepseek" }, { base: BASE, token: TOKEN, fetchImpl: f });
928
- assert.equal(frame.ok, false);
929
- assert.equal(frame.error.code, "FORBIDDEN_SCOPE");
930
- });
931
-
932
- test("credentialLease: unconfigured provider → NOT_FOUND error frame (router falls through to missing_credential)", async () => {
933
- const f = fakeFetch(() => ({ ok: false, status: 404, body: { ok: false, error: { code: "NOT_FOUND", message: "no such credential" } } }));
934
- const frame = await credentialLease({ provider: "openai" }, { base: BASE, token: TOKEN, fetchImpl: f });
935
- assert.equal(frame.error.code, "NOT_FOUND");
936
- });
937
-
938
- test("credentialPut: admin — POSTs the value + scoping; auto-derives an idempotency key from provider", async () => {
939
- const f = fakeFetch(() => ({ body: { ok: true, result: { provider: "deepseek", version: 1 } } }));
940
- const frame = await credentialPut(
941
- { provider: "deepseek", value: "sk-org-secret", auth_env: "DEEPSEEK_API_KEY", allowedRoles: ["agent"] },
942
- { base: BASE, token: TOKEN, fetchImpl: f },
943
- );
944
- assert.equal(f.calls[0].url, `${BASE}/api/v1/credential.put`);
945
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
946
- assert.equal(f.calls[0].headers["x-idempotency-key"], "credential.put:deepseek");
947
- assert.deepEqual(JSON.parse(f.calls[0].init.body), {
948
- provider: "deepseek", value: "sk-org-secret", auth_env: "DEEPSEEK_API_KEY", allowedRoles: ["agent"],
949
- });
950
- assert.equal(frame.ok, true);
951
- });
952
-
953
- test("credentialPut: caller-supplied idempotency key wins over the derived one", async () => {
954
- const f = fakeFetch(() => ({ body: { ok: true, result: null } }));
955
- await credentialPut({ provider: "deepseek", value: "v" }, { base: BASE, token: TOKEN, idempotencyKey: "custom-key", fetchImpl: f });
956
- assert.equal(f.calls[0].headers["x-idempotency-key"], "custom-key");
957
- });
958
-
959
- test("credentialPut: non-admin token → FORBIDDEN_SCOPE error frame (403)", async () => {
960
- const f = fakeFetch(() => ({ ok: false, status: 403, body: { ok: false, error: { code: "FORBIDDEN_SCOPE", message: "admin only" } } }));
961
- const frame = await credentialPut({ provider: "deepseek", value: "v" }, { base: BASE, token: TOKEN, fetchImpl: f });
962
- assert.equal(frame.error.code, "FORBIDDEN_SCOPE");
963
- });
964
-
965
- test("credentialList: admin metadata-only read; never carries a value; returns the result frame", async () => {
966
- const f = fakeFetch(() => ({ body: { ok: true, result: { credentials: [{ provider: "deepseek", auth_env: "DEEPSEEK_API_KEY", allowedRoles: ["agent"] }] } } }));
967
- const frame = await credentialList({}, { base: BASE, token: TOKEN, fetchImpl: f });
968
- assert.equal(f.calls[0].url, `${BASE}/api/v1/credential.list`);
969
- assert.equal(frame.result.credentials[0].provider, "deepseek");
970
- assert.equal(frame.result.credentials[0].value, undefined, "list NEVER returns the value");
971
- });
972
-
973
- test("credentialRevoke: admin; POSTs the provider + reason", async () => {
974
- const f = fakeFetch(() => ({ body: { ok: true, result: { provider: "deepseek", revoked: true } } }));
975
- const frame = await credentialRevoke({ provider: "deepseek", reason: "rotated upstream" }, { base: BASE, token: TOKEN, fetchImpl: f });
976
- assert.equal(f.calls[0].url, `${BASE}/api/v1/credential.revoke`);
977
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
978
- assert.deepEqual(JSON.parse(f.calls[0].init.body), { provider: "deepseek", reason: "rotated upstream" });
979
- assert.equal(frame.result.revoked, true);
980
- });
981
-
982
- test("credential helpers all fail open on transport error (no throw)", async () => {
983
- const thrower = fakeFetch(() => { throw new Error("network"); });
984
- const lease = await credentialLease({ provider: "deepseek" }, { base: BASE, token: TOKEN, fetchImpl: thrower });
985
- const put = await credentialPut({ provider: "deepseek", value: "v" }, { base: BASE, token: TOKEN, fetchImpl: thrower });
986
- const list = await credentialList({}, { base: BASE, token: TOKEN, fetchImpl: thrower });
987
- const revoke = await credentialRevoke({ provider: "deepseek" }, { base: BASE, token: TOKEN, fetchImpl: thrower });
988
- for (const frame of [lease, put, list, revoke]) {
989
- assert.equal(frame.ok, false);
990
- assert.equal(frame.error.code, "INTERNAL");
991
- }
992
- });
993
-
994
- // --- org-data API: fetchSelfProfile (GET /api/v1/org/...) ------------------
995
-
996
- const PROFILE = { slug: "robin", kind: "agent", displayName: "Robin Vega", title: "VP Eng", agentEmail: "robin@example.com" };
997
-
998
- test("fetchSelfProfile: agentId selects GET /api/v1/org/members/<slug> with Bearer", async () => {
999
- const f = fakeFetch(() => ({ body: PROFILE }));
1000
- const frame = await fetchSelfProfile({ base: BASE, apiKey: "api-key", orgId: "acme", agentId: "robin", fetchImpl: f });
1001
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/members/robin?orgId=acme`);
1002
- assert.equal(f.calls[0].init.method, "GET");
1003
- assert.equal(f.calls[0].headers.authorization, "Bearer api-key");
1004
- assert.equal(frame.ok, true);
1005
- assert.equal(frame.result.slug, "robin");
1006
- });
1007
-
1008
- test("fetchSelfProfile: no agentId → GET /api/v1/org/whoami?orgId= (+ email hint), orgId pins via ?orgId + x-org-id (never as a member slug)", async () => {
1009
- const f = fakeFetch(() => ({ body: PROFILE }));
1010
- await fetchSelfProfile({ base: BASE, apiKey: "k", orgId: "acme", emailHint: "robin@example.com", fetchImpl: f });
1011
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/whoami?orgId=acme&email=robin%40example.com`);
1012
- // The org is the TENANT PIN (?orgId + x-org-id header), NOT whoami's member `slug` hint.
1013
- assert.equal(f.calls[0].url.includes("slug="), false, "org slug is never sent as the member-slug hint");
1014
- assert.equal(f.calls[0].headers["x-org-id"], "acme");
1015
- });
1016
-
1017
- test("fetchSelfProfile: whoami passes an explicit memberSlug as the ?slug= member hint (reserved for genuine member hints)", async () => {
1018
- const f = fakeFetch(() => ({ body: PROFILE }));
1019
- await fetchSelfProfile({ base: BASE, apiKey: "k", orgId: "acme", memberSlug: "robin", fetchImpl: f });
1020
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/whoami?orgId=acme&slug=robin`);
1021
- });
1022
-
1023
- test("fetchSelfProfile: unwraps a {member}-wrapped payload", async () => {
1024
- const f = fakeFetch(() => ({ body: { member: PROFILE } }));
1025
- const frame = await fetchSelfProfile({ base: BASE, apiKey: "k", orgId: "acme", agentId: "robin", fetchImpl: f });
1026
- assert.equal(frame.ok, true);
1027
- assert.equal(frame.result.slug, "robin");
1028
- });
1029
-
1030
- test("fetchSelfProfile: missing key/orgId → fail-open error frame (no throw)", async () => {
1031
- const noKey = await fetchSelfProfile({ base: BASE, orgId: "acme", fetchImpl: fakeFetch() });
1032
- assert.equal(noKey.ok, false);
1033
- assert.equal(noKey.error.code, "UNAUTHORIZED");
1034
- const noOrg = await fetchSelfProfile({ base: BASE, apiKey: "k", fetchImpl: fakeFetch() });
1035
- assert.equal(noOrg.ok, false);
1036
- assert.equal(noOrg.error.code, "BAD_REQUEST");
1037
- });
1038
-
1039
- test("fetchSelfProfile: non-200 maps the status code; fail-open", async () => {
1040
- const f = fakeFetch(() => ({ ok: false, status: 404, body: { error: { code: "NOT_FOUND", message: "no such member" } } }));
1041
- const frame = await fetchSelfProfile({ base: BASE, apiKey: "k", orgId: "acme", agentId: "nobody", fetchImpl: f });
1042
- assert.equal(frame.ok, false);
1043
- assert.equal(frame.error.code, "NOT_FOUND");
1044
- });
1045
-
1046
- test("fetchSelfProfile: transport throw → fail-open error frame", async () => {
1047
- const thrower = fakeFetch(() => { throw new Error("network"); });
1048
- const frame = await fetchSelfProfile({ base: BASE, apiKey: "k", orgId: "acme", agentId: "robin", fetchImpl: thrower });
1049
- assert.equal(frame.ok, false);
1050
- });
1051
-
1052
- // --- org-data API: structural reads (chart / relationships / strategy) ------
1053
-
1054
- test("fetchOrgChart: GET /api/v1/org/chart?slug= with Bearer; unwraps {ok,nodes,edges}", async () => {
1055
- const body = { ok: true, nodes: [{ slug: "a001", displayName: "Ada" }], edges: [{ kind: "reporting", from: "a001", to: "b002", type: "SOLID" }] };
1056
- const f = fakeFetch(() => ({ body }));
1057
- const frame = await fetchOrgChart({ base: BASE, apiKey: "api-key", orgId: "acme", fetchImpl: f });
1058
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/chart?orgId=acme`);
1059
- assert.equal(f.calls[0].init.method, "GET");
1060
- assert.equal(f.calls[0].headers.authorization, "Bearer api-key");
1061
- assert.equal(frame.ok, true);
1062
- assert.equal(frame.result.nodes.length, 1);
1063
- assert.equal(frame.result.edges[0].from, "a001");
1064
- });
1065
-
1066
- test("fetchOrgChart: missing key/orgId/base → fail-open error frame (no throw)", async () => {
1067
- assert.equal((await fetchOrgChart({ base: BASE, orgId: "acme", fetchImpl: fakeFetch() })).error.code, "UNAUTHORIZED");
1068
- assert.equal((await fetchOrgChart({ base: BASE, apiKey: "k", fetchImpl: fakeFetch() })).error.code, "BAD_REQUEST");
1069
- assert.equal((await fetchOrgChart({ apiKey: "k", orgId: "acme", fetchImpl: fakeFetch() })).error.code, "BAD_REQUEST");
1070
- });
1071
-
1072
- test("fetchOrgChart: non-200 maps the status; transport throw → fail-open", async () => {
1073
- const f404 = fakeFetch(() => ({ ok: false, status: 404, body: { error: { code: "NOT_FOUND", message: "x" } } }));
1074
- assert.equal((await fetchOrgChart({ base: BASE, apiKey: "k", orgId: "acme", fetchImpl: f404 })).error.code, "NOT_FOUND");
1075
- const thrower = fakeFetch(() => { throw new Error("network"); });
1076
- assert.equal((await fetchOrgChart({ base: BASE, apiKey: "k", orgId: "acme", fetchImpl: thrower })).ok, false);
1077
- });
1078
-
1079
- test("fetchRelationships: GET /api/v1/org/relationships?slug=&member=; unwraps the DTO", async () => {
1080
- const body = { ok: true, member: { slug: "robin" }, reportingLine: { manager: { slug: "layla", displayName: "Layla" } }, reports: [{ member: { slug: "kai" } }], governance: [] };
1081
- const f = fakeFetch(() => ({ body }));
1082
- const frame = await fetchRelationships({ base: BASE, apiKey: "k", orgId: "acme", member: "robin", fetchImpl: f });
1083
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/relationships?orgId=acme&member=robin`);
1084
- assert.equal(frame.ok, true);
1085
- assert.equal(frame.result.reportingLine.manager.slug, "layla");
1086
- assert.equal(frame.result.reports[0].member.slug, "kai");
1087
- });
1088
-
1089
- test("fetchRelationships: falls back to agentId for the member slug; missing → BAD_REQUEST", async () => {
1090
- const f = fakeFetch(() => ({ body: { ok: true, member: { slug: "robin" }, reportingLine: { manager: null }, reports: [], governance: [] } }));
1091
- await fetchRelationships({ base: BASE, apiKey: "k", orgId: "acme", agentId: "robin", fetchImpl: f });
1092
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/relationships?orgId=acme&member=robin`);
1093
- const noMember = await fetchRelationships({ base: BASE, apiKey: "k", orgId: "acme", fetchImpl: fakeFetch() });
1094
- assert.equal(noMember.ok, false);
1095
- assert.equal(noMember.error.code, "BAD_REQUEST");
1096
- });
1097
-
1098
- test("fetchStrategy: GET /api/v1/org/strategy?slug=; unwraps {ok,strategy}", async () => {
1099
- const body = { ok: true, strategy: { slug: "strategy", northStar: { goal: "win" }, phases: [], streams: [{ code: "S1", name: "Growth", raci: [{ role: "Accountable", member: { slug: "robin", displayName: "Robin" } }] }] } };
1100
- const f = fakeFetch(() => ({ body }));
1101
- const frame = await fetchStrategy({ base: BASE, apiKey: "k", orgId: "acme", fetchImpl: f });
1102
- assert.equal(f.calls[0].url, `${BASE}/api/v1/org/strategy?orgId=acme`);
1103
- assert.equal(frame.ok, true);
1104
- assert.equal(frame.result.streams[0].code, "S1");
1105
- });
1106
-
1107
- test("fetchStrategy: 404 (no strategy doc) → fail-open NOT_FOUND frame", async () => {
1108
- const f = fakeFetch(() => ({ ok: false, status: 404, body: { ok: false, error: { code: "NOT_FOUND", message: "none" } } }));
1109
- const frame = await fetchStrategy({ base: BASE, apiKey: "k", orgId: "acme", fetchImpl: f });
1110
- assert.equal(frame.ok, false);
1111
- assert.equal(frame.error.code, "NOT_FOUND");
1112
- });
1113
-
1114
- test("fetchHierarchy: GET /v1/hierarchy bare payload → {members,reporting}; null on failure", async () => {
1115
- const body = { members: [{ slug: "a001" }], reporting: [{ from: "a001", to: "b002" }] };
1116
- const f = fakeFetch(() => ({ body }));
1117
- const out = await fetchHierarchy({ base: BASE, token: TOKEN, orgId: "acme", fetchImpl: f });
1118
- assert.equal(f.calls[0].url, `${BASE}/api/v1/hierarchy`);
1119
- assert.equal(f.calls[0].headers.authorization, `Bearer ${TOKEN}`);
1120
- assert.equal(out.members.length, 1);
1121
- assert.equal(out.reporting[0].to, "b002");
1122
- // failure → null (fail-open)
1123
- const fail = fakeFetch(() => ({ ok: false, status: 503, body: { error: { code: "INTERNAL", message: "down" } } }));
1124
- assert.equal(await fetchHierarchy({ base: BASE, token: TOKEN, orgId: "acme", fetchImpl: fail }), null);
1125
- });
1126
-
1127
- // ---------------------------------------------------------------------------
1128
- // loadOrgConfig — an enrolled agent must never go quietly un-enrolled
1129
- // ---------------------------------------------------------------------------
1130
-
1131
- test("loadOrgConfig: absent org.yaml is silent (an un-enrolled agent is not a fault)", () => {
1132
- const dir = mkdtempSync(join(tmpdir(), "orgcfg-"));
1133
- const warnings = captureWarn(() => {
1134
- assert.deepEqual(loadOrgConfig(dir), {});
1135
- });
1136
- assert.deepEqual(warnings, [], "no file, no noise");
1137
- });
1138
-
1139
- test("loadOrgConfig: parses config/org.yaml", () => {
1140
- const dir = mkdtempSync(join(tmpdir(), "orgcfg-"));
1141
- mkdirSync(join(dir, "config"), { recursive: true });
1142
- writeFileSync(
1143
- join(dir, "config", "org.yaml"),
1144
- "org:\n cohort:\n enabled: true\n base: https://os.example.com\n",
1145
- );
1146
- const cfg = loadOrgConfig(dir);
1147
- assert.equal(cfg.org.cohort.enabled, true);
1148
- assert.equal(isEnabled(cfg), true);
1149
- });
1150
-
1151
- test("loadOrgConfig: a PRESENT but unparseable org.yaml WARNS (never silently un-enrols)", () => {
1152
- // Returning {} quietly is how an enrolled agent ends up out of the mesh:
1153
- // isEnabled({}) is false, so the daemon no-ops, never beats, and cannot
1154
- // receive `halt`. Fail-open is right; silence is not.
1155
- const dir = mkdtempSync(join(tmpdir(), "orgcfg-"));
1156
- mkdirSync(join(dir, "config"), { recursive: true });
1157
- writeFileSync(join(dir, "config", "org.yaml"), "org:\n cohort:\n - [unbalanced\n");
1158
- let cfg;
1159
- const warnings = captureWarn(() => { cfg = loadOrgConfig(dir); });
1160
- assert.deepEqual(cfg, {}, "still fail-open");
1161
- assert.match(warnings.join("\n"), /could not be loaded/, "the operator must be told");
1162
- assert.match(warnings.join("\n"), /NOT enrolled/, "and told what it means");
1163
- });
1164
-
1165
- // ── WP-M4: board.mine + board.track passthrough (front-door session §3.5) ──
1166
-
1167
- test("listMineResult: keeps the failure visible — {ok:false} on an error frame or a throwing transport, {ok:true, items:[]} for an empty board", async () => {
1168
- assert.deepEqual(await listMineResult({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: [{ itemId: "i1" }] })) }), { ok: true, items: [{ itemId: "i1" }] });
1169
- assert.deepEqual(await listMineResult({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: { items: [] } })) }), { ok: true, items: [] }, "an empty board is a real answer");
1170
- const failed = await listMineResult({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 503, body: { error: { code: "UNAVAILABLE", message: "hq down" } } })) });
1171
- assert.equal(failed.ok, false);
1172
- assert.deepEqual(failed.items, []);
1173
- assert.match(failed.error, /hq down/);
1174
- const threw = await listMineResult({ base: BASE, token: TOKEN, fetchImpl: () => { throw new Error("ECONNREFUSED"); } });
1175
- assert.equal(threw.ok, false);
1176
- assert.deepEqual(threw.items, []);
1177
- assert.deepEqual(await listMine({ base: BASE, token: TOKEN, fetchImpl: () => { throw new Error("ECONNREFUSED"); } }), [], "listMine stays the fail-open [] its other callers expect");
1178
- });
1179
-
1180
- test("listMine: GET /v1/board.mine; parses array and {items:[]}; [] on error / transport failure (fail-open)", async () => {
1181
- const f = fakeFetch(() => ({ body: [{ itemId: "i1", title: "Deck" }] }));
1182
- assert.deepEqual(await listMine({ base: BASE, token: TOKEN, fetchImpl: f }), [{ itemId: "i1", title: "Deck" }]);
1183
- assert.match(f.calls[0].url, /\/v1\/board\.mine$/);
1184
- assert.equal(f.calls[0].init.method, "GET");
1185
- assert.deepEqual(await listMine({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ body: { items: [{ itemId: "i2" }] } })) }), [{ itemId: "i2" }]);
1186
- assert.deepEqual(await listMine({ base: BASE, token: TOKEN, fetchImpl: fakeFetch(() => ({ ok: false, status: 404, body: { error: { code: "NOT_FOUND" } } })) }), [], "an hq without board.mine yet → []");
1187
- assert.deepEqual(await listMine({ base: BASE, token: TOKEN, fetchImpl: async () => { throw new Error("boom"); } }), []);
1188
- assert.deepEqual(await listMine({ base: "", token: TOKEN }), [], "no base → []");
1189
- });
1190
-
1191
- test("trackWork: title/why/stage (incl. accepted|done) pass through to board.track verbatim", async () => {
1192
- const f = fakeFetch(() => ({ body: { ok: true, result: { tracked: true, taskId: "t1" } } }));
1193
- const r = await trackWork(
1194
- { service: "cohort", channelId: "c1", messageId: "m1", stage: "accepted", title: "Build the deck", why: "asked in DM" },
1195
- { base: BASE, token: TOKEN, fetchImpl: f, idempotencyKey: "k1" },
1196
- );
1197
- assert.equal(r.ok, true);
1198
- const body = JSON.parse(f.calls[0].init.body);
1199
- assert.equal(body.stage, "accepted");
1200
- assert.equal(body.title, "Build the deck");
1201
- assert.equal(body.why, "asked in DM");
1202
- assert.equal(body.channelId, "c1");
1203
- const f2 = fakeFetch(() => ({ body: { ok: true, result: { tracked: true } } }));
1204
- await trackWork({ service: "cohort", channelId: "c1", messageId: "m1", stage: "done" }, { base: BASE, token: TOKEN, fetchImpl: f2 });
1205
- assert.equal(JSON.parse(f2.calls[0].init.body).stage, "done");
1206
- });