@cohortapp/agent-sdk 2.17.0 → 2.18.5

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 (531) 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-slots.mjs +234 -0
  23. package/lib/collective/capture.mjs +8 -6
  24. package/lib/collective/config.mjs +2 -0
  25. package/lib/collective/global-config.mjs +63 -1
  26. package/lib/collective/loop-guard.mjs +155 -0
  27. package/lib/collective/presence.mjs +142 -5
  28. package/lib/comms/send-gate.mjs +559 -1
  29. package/lib/diagnostics/alerts.mjs +49 -0
  30. package/lib/diagnostics/cadence-output-freshness.mjs +288 -0
  31. package/lib/engine/agents/definitions.mjs +343 -0
  32. package/lib/engine/agents/persist.mjs +275 -0
  33. package/lib/engine/agents/runtime.mjs +748 -0
  34. package/lib/engine/agents/usage.mjs +95 -0
  35. package/lib/engine/auth-status.mjs +139 -0
  36. package/lib/engine/budget.mjs +194 -0
  37. package/lib/engine/cli.mjs +1204 -0
  38. package/lib/engine/commands/index.mjs +269 -0
  39. package/lib/engine/context/budget.mjs +219 -0
  40. package/lib/engine/context/cache.mjs +125 -0
  41. package/lib/engine/context/child-env.mjs +215 -0
  42. package/lib/engine/context/compaction.mjs +342 -0
  43. package/lib/engine/context/images.mjs +90 -0
  44. package/lib/engine/context/instructions.mjs +327 -0
  45. package/lib/engine/context/lazy-instructions.mjs +169 -0
  46. package/lib/engine/context/manager.mjs +182 -0
  47. package/lib/engine/context/real-path.mjs +91 -0
  48. package/lib/engine/context/secret-values.mjs +163 -0
  49. package/lib/engine/context/settings.mjs +274 -0
  50. package/lib/engine/context/stream-input.mjs +159 -0
  51. package/lib/engine/guard.mjs +152 -0
  52. package/lib/engine/hooks.mjs +713 -0
  53. package/lib/engine/loop.mjs +560 -0
  54. package/lib/engine/mcp/client.mjs +254 -0
  55. package/lib/engine/mcp/config.mjs +301 -0
  56. package/lib/engine/mcp/http.mjs +201 -0
  57. package/lib/engine/mcp/index.mjs +146 -0
  58. package/lib/engine/mcp/jsonrpc.mjs +147 -0
  59. package/lib/engine/mcp/naming.mjs +66 -0
  60. package/lib/engine/mcp/resources.mjs +89 -0
  61. package/lib/engine/mcp/results.mjs +133 -0
  62. package/lib/engine/mcp/stdio.mjs +137 -0
  63. package/lib/engine/mcp/supervisor.mjs +116 -0
  64. package/lib/engine/messages.mjs +104 -0
  65. package/lib/engine/output/json.mjs +164 -0
  66. package/lib/engine/output/stream-json.mjs +266 -0
  67. package/lib/engine/permissions.mjs +845 -0
  68. package/lib/engine/process-identity.mjs +164 -0
  69. package/lib/engine/process-tree.mjs +551 -0
  70. package/lib/engine/prompt.mjs +60 -0
  71. package/lib/engine/session/store.mjs +299 -0
  72. package/lib/engine/session-runtime/args.mjs +97 -0
  73. package/lib/engine/session-runtime/host.mjs +143 -0
  74. package/lib/engine/session-runtime/inbox.mjs +122 -0
  75. package/lib/engine/session-runtime/notifications.mjs +129 -0
  76. package/lib/engine/session-runtime/registry.mjs +328 -0
  77. package/lib/engine/session-runtime/runner.mjs +344 -0
  78. package/lib/engine/session-runtime/socket.mjs +212 -0
  79. package/lib/engine/session-runtime/wakeup.mjs +115 -0
  80. package/lib/engine/skills/index.mjs +321 -0
  81. package/lib/engine/tools/bash-background.mjs +533 -0
  82. package/lib/engine/tools/bash.mjs +216 -0
  83. package/lib/engine/tools/edit.mjs +97 -0
  84. package/lib/engine/tools/glob.mjs +81 -0
  85. package/lib/engine/tools/grep.mjs +224 -0
  86. package/lib/engine/tools/index.mjs +84 -0
  87. package/lib/engine/tools/list-agents.mjs +32 -0
  88. package/lib/engine/tools/ls.mjs +127 -0
  89. package/lib/engine/tools/monitor.mjs +82 -0
  90. package/lib/engine/tools/notebook-edit.mjs +218 -0
  91. package/lib/engine/tools/read.mjs +103 -0
  92. package/lib/engine/tools/schedule-wakeup.mjs +45 -0
  93. package/lib/engine/tools/schema.mjs +144 -0
  94. package/lib/engine/tools/send-message.mjs +77 -0
  95. package/lib/engine/tools/session.mjs +70 -0
  96. package/lib/engine/tools/todo.mjs +144 -0
  97. package/lib/engine/tools/toolsearch.mjs +217 -0
  98. package/lib/engine/tools/walk.mjs +193 -0
  99. package/lib/engine/tools/web-switch.mjs +31 -0
  100. package/lib/engine/tools/webfetch-html.mjs +387 -0
  101. package/lib/engine/tools/webfetch-net.mjs +340 -0
  102. package/lib/engine/tools/webfetch.mjs +198 -0
  103. package/lib/engine/tools/websearch.mjs +91 -0
  104. package/lib/engine/tools/workflow.mjs +95 -0
  105. package/lib/engine/tools/write.mjs +76 -0
  106. package/lib/engine/tui/line-editor.mjs +137 -0
  107. package/lib/engine/tui/render.mjs +86 -0
  108. package/lib/engine/tui/tui.mjs +274 -0
  109. package/lib/engine/wire/anthropic-messages.mjs +263 -0
  110. package/lib/engine/wire/effort.mjs +36 -0
  111. package/lib/engine/wire/errors.mjs +496 -0
  112. package/lib/engine/wire/http.mjs +441 -0
  113. package/lib/engine/wire/index.mjs +76 -0
  114. package/lib/engine/wire/openai-chat.mjs +332 -0
  115. package/lib/engine/wire/prompt-cache.mjs +79 -0
  116. package/lib/engine/wire/search.mjs +140 -0
  117. package/lib/engine/wire/sse.mjs +114 -0
  118. package/lib/engine/wire/stall.mjs +349 -0
  119. package/lib/engine/wire/token-provider.mjs +175 -0
  120. package/lib/engine/wire/usage.mjs +192 -0
  121. package/lib/engine/workflow/host.mjs +524 -0
  122. package/lib/engine/workflow/journal.mjs +188 -0
  123. package/lib/engine/workflow/json-schema.mjs +171 -0
  124. package/lib/engine/workflow/meta.mjs +329 -0
  125. package/lib/engine/workflow/notifications.mjs +52 -0
  126. package/lib/engine/workflow/runtime.mjs +447 -0
  127. package/lib/engine/workflow/sandbox.mjs +534 -0
  128. package/lib/engine/workflow/worker.mjs +141 -0
  129. package/lib/engine/workflow/worktree.mjs +74 -0
  130. package/lib/execution/disposition.mjs +1 -1
  131. package/lib/execution/intake.mjs +10 -0
  132. package/lib/execution/surface-policy.mjs +15 -0
  133. package/lib/learning/curator.mjs +8 -6
  134. package/lib/learning/reflect.mjs +8 -6
  135. package/lib/model-router/catalog/cohort.yaml +137 -0
  136. package/lib/model-router/catalog.mjs +118 -1
  137. package/lib/model-router/failover.mjs +67 -16
  138. package/lib/model-router/llm-task.mjs +39 -3
  139. package/lib/model-router/resolve.mjs +89 -3
  140. package/lib/model-router/spawn.mjs +46 -47
  141. package/lib/model-router/taxonomy.mjs +126 -4
  142. package/lib/org/cost-sync.mjs +141 -11
  143. package/lib/org/inbound/broadcast.mjs +289 -0
  144. package/lib/org/inbound/collective.mjs +375 -0
  145. package/lib/org/inbound/directedness.mjs +96 -8
  146. package/lib/org/inbound/facts.mjs +78 -2
  147. package/lib/org/inbound/project.mjs +22 -0
  148. package/lib/org/inbound/surfaces.mjs +14 -0
  149. package/lib/org/llm-token.mjs +879 -0
  150. package/lib/org/mesh.mjs +61 -0
  151. package/lib/org/messaging.mjs +3 -1
  152. package/lib/org/protocol.checksum +1 -1
  153. package/lib/org/protocol.mjs +15 -0
  154. package/lib/org/quota.mjs +520 -0
  155. package/lib/org/tool-surface.mjs +104 -16
  156. package/lib/org/ui-parity.mjs +16 -1
  157. package/lib/org/work-ledger.mjs +37 -6
  158. package/lib/rate-guard.mjs +114 -1
  159. package/lib/resource-governor.mjs +41 -6
  160. package/lib/runtime/adapter.mjs +833 -0
  161. package/lib/runtime/child-env.mjs +191 -0
  162. package/lib/runtime/legacy-shell-guard.mjs +97 -0
  163. package/lib/runtime/seat-engine.mjs +162 -0
  164. package/lib/session/ask-ledger.mjs +271 -0
  165. package/lib/session/current-work.mjs +676 -0
  166. package/lib/session/feed-core.mjs +40 -3
  167. package/lib/session/launch-args.mjs +56 -4
  168. package/lib/session/status-summary.mjs +26 -9
  169. package/lib/session/upgrade-notice.mjs +42 -0
  170. package/lib/setup/claude-probe.mjs +117 -13
  171. package/lib/setup/enrich.mjs +13 -10
  172. package/lib/setup/sections/model.mjs +39 -13
  173. package/lib/telemetry/collect.mjs +229 -11
  174. package/lib/upgrade/ignored-drift.mjs +105 -0
  175. package/lib/voice/post-call-brief.mjs +30 -17
  176. package/package.json +13 -3
  177. package/plugins/maestro-skills/skills/board-work.md +5 -0
  178. package/plugins/maestro-skills/skills/inbound-triage.md +56 -15
  179. package/plugins/maestro-skills/skills/main-session.md +18 -7
  180. package/scaffold/config/collective.yaml +7 -0
  181. package/scripts/ci/check-durable-write-seam.mjs +3 -1
  182. package/scripts/ci/check-tarball-fidelity.mjs +126 -2
  183. package/scripts/ci/run-tests.mjs +47 -19
  184. package/scripts/cohort-llm/api-key-helper.mjs +92 -0
  185. package/scripts/collective/hook-runner.mjs +142 -19
  186. package/scripts/continuous-monitor.sh +13 -0
  187. package/scripts/cost/track-claude-usage.mjs +15 -0
  188. package/scripts/daemon/agent-daemon.mjs +408 -20
  189. package/scripts/daemon/assurance.mjs +48 -12
  190. package/scripts/daemon/cadence-consumer.mjs +218 -68
  191. package/scripts/daemon/cadence-handlers.mjs +73 -4
  192. package/scripts/daemon/classifier.mjs +75 -26
  193. package/scripts/daemon/context-compiler.mjs +51 -37
  194. package/scripts/daemon/deliver.mjs +30 -1
  195. package/scripts/daemon/dispatcher.mjs +595 -149
  196. package/scripts/daemon/health.mjs +14 -1
  197. package/scripts/daemon/maestro-daemon.mjs +11 -0
  198. package/scripts/daemon/prompt-builder.mjs +24 -0
  199. package/scripts/daemon/responder.mjs +246 -79
  200. package/scripts/daemon/sdk-version.mjs +98 -16
  201. package/scripts/eval/probe-gateway.mjs +635 -0
  202. package/scripts/eval/replay/extract.mjs +270 -0
  203. package/scripts/eval/replay/grade.mjs +260 -0
  204. package/scripts/eval/replay/lib/config.mjs +50 -0
  205. package/scripts/eval/replay/lib/effects.mjs +65 -0
  206. package/scripts/eval/replay/lib/fixture.mjs +188 -0
  207. package/scripts/eval/replay/lib/judge.mjs +72 -0
  208. package/scripts/eval/replay/lib/redact.mjs +136 -0
  209. package/scripts/eval/replay/lib/sandbox.mjs +170 -0
  210. package/scripts/eval/replay/lib/schema-check.mjs +63 -0
  211. package/scripts/eval/replay/lib/transcript.mjs +76 -0
  212. package/scripts/eval/replay/mcp-replay-stub.mjs +101 -0
  213. package/scripts/eval/replay/report.mjs +185 -0
  214. package/scripts/eval/replay/run.mjs +404 -0
  215. package/scripts/fleet/rollout.mjs +1151 -0
  216. package/scripts/hooks/pre-send-audit.sh +36 -245
  217. package/scripts/hooks/pre-write-yaml-validate.mjs +275 -0
  218. package/scripts/hooks/validate-state-yaml.sh +190 -0
  219. package/scripts/huddle/huddle-llm.mjs +361 -0
  220. package/scripts/huddle/huddle-server.mjs +46 -121
  221. package/scripts/local-triggers/autoupdate.sh +465 -81
  222. package/scripts/local-triggers/run-trigger.sh +13 -0
  223. package/scripts/maintenance/pin-integrity.mjs +364 -0
  224. package/scripts/poll-slack-events.sh +41 -9
  225. package/scripts/poller/slack-socket-mode.mjs +28 -3
  226. package/scripts/session/supervisor.mjs +80 -13
  227. package/scripts/spawn-session.sh +13 -0
  228. package/bin/maestro.test.mjs +0 -1574
  229. package/lib/action-executor.test.mjs +0 -871
  230. package/lib/archetype.test.mjs +0 -132
  231. package/lib/assurance/plan-note.test.mjs +0 -234
  232. package/lib/assurance/room-budget.test.mjs +0 -486
  233. package/lib/assurance/tier.test.mjs +0 -174
  234. package/lib/autonomy.test.mjs +0 -66
  235. package/lib/backlog.test.mjs +0 -302
  236. package/lib/backup/policy.test.mjs +0 -305
  237. package/lib/budget-escalate.test.mjs +0 -232
  238. package/lib/budget-guard.envelope.test.mjs +0 -476
  239. package/lib/budget-guard.test.mjs +0 -427
  240. package/lib/cadence-bus-requeue.test.mjs +0 -83
  241. package/lib/cadence-bus-schedule.test.mjs +0 -194
  242. package/lib/cadence-bus.test.mjs +0 -720
  243. package/lib/cadences.test.mjs +0 -230
  244. package/lib/capability/inventory.test.mjs +0 -232
  245. package/lib/capability.test.mjs +0 -78
  246. package/lib/channels/base-adapter.test.mjs +0 -590
  247. package/lib/channels/channels.test.mjs +0 -371
  248. package/lib/channels/contract.test.mjs +0 -162
  249. package/lib/channels/inbox-item.test.mjs +0 -368
  250. package/lib/channels/orgmail/adapter.test.mjs +0 -448
  251. package/lib/channels/pairing.test.mjs +0 -270
  252. package/lib/channels/repeat-suppressor.test.mjs +0 -134
  253. package/lib/channels/slack-adapter.test.mjs +0 -212
  254. package/lib/channels/telegram-adapter.test.mjs +0 -306
  255. package/lib/channels/voice/adapter.test.mjs +0 -278
  256. package/lib/channels/whatsapp/adapter-baileys.test.mjs +0 -359
  257. package/lib/channels/whatsapp/baileys-typing.test.mjs +0 -154
  258. package/lib/charter.test.mjs +0 -89
  259. package/lib/claude-bin.test.mjs +0 -131
  260. package/lib/cli/board.test.mjs +0 -227
  261. package/lib/cli/design.test.mjs +0 -270
  262. package/lib/cli/doctor-checks.test.mjs +0 -336
  263. package/lib/cli/global-setup-extras.test.mjs +0 -462
  264. package/lib/cli/inbox.test.mjs +0 -230
  265. package/lib/cli/session-ack.test.mjs +0 -63
  266. package/lib/cli/session.test.mjs +0 -613
  267. package/lib/collective/capture.test.mjs +0 -121
  268. package/lib/collective/cards.test.mjs +0 -114
  269. package/lib/collective/config.test.mjs +0 -123
  270. package/lib/collective/global-config.test.mjs +0 -220
  271. package/lib/collective/global-skills.test.mjs +0 -126
  272. package/lib/collective/presence.test.mjs +0 -95
  273. package/lib/collective/recall.test.mjs +0 -116
  274. package/lib/collective/vendor-skills.test.mjs +0 -306
  275. package/lib/comms/send-gate.test.mjs +0 -770
  276. package/lib/comms.test.mjs +0 -41
  277. package/lib/context/budget.test.mjs +0 -252
  278. package/lib/context/history-scope.test.mjs +0 -79
  279. package/lib/cost/ledger-row.test.mjs +0 -183
  280. package/lib/design/design-md.test.mjs +0 -318
  281. package/lib/design/fixtures/DESIGN.golden.md +0 -238
  282. package/lib/design/fixtures/PRODUCT.golden.md +0 -67
  283. package/lib/design/fixtures/foundation.json +0 -133
  284. package/lib/design/refresh-gate.test.mjs +0 -144
  285. package/lib/design/write.test.mjs +0 -241
  286. package/lib/diagnostics/alerts.test.mjs +0 -318
  287. package/lib/diagnostics/backup-freshness.test.mjs +0 -185
  288. package/lib/diagnostics/counters.test.mjs +0 -206
  289. package/lib/diagnostics/events.test.mjs +0 -290
  290. package/lib/diagnostics/otel.test.mjs +0 -196
  291. package/lib/diagnostics/trace.test.mjs +0 -251
  292. package/lib/env-compat.test.mjs +0 -104
  293. package/lib/execution/disposition.test.mjs +0 -553
  294. package/lib/execution/drive.test.mjs +0 -270
  295. package/lib/execution/effects.test.mjs +0 -344
  296. package/lib/execution/intake.test.mjs +0 -389
  297. package/lib/execution/journal.test.mjs +0 -261
  298. package/lib/execution/match.test.mjs +0 -235
  299. package/lib/execution/pipeline.test.mjs +0 -392
  300. package/lib/execution/route.test.mjs +0 -186
  301. package/lib/execution/surface-policy.test.mjs +0 -162
  302. package/lib/fs-atomic.test.mjs +0 -72
  303. package/lib/fs-ownership.test.mjs +0 -158
  304. package/lib/goals/admission.test.mjs +0 -164
  305. package/lib/goals/classify.test.mjs +0 -167
  306. package/lib/goals/collaborate.test.mjs +0 -336
  307. package/lib/goals/gaps.test.mjs +0 -284
  308. package/lib/goals/loop.test.mjs +0 -845
  309. package/lib/hooks/bus.test.mjs +0 -387
  310. package/lib/identity/persona.test.mjs +0 -142
  311. package/lib/kpi-sensors.test.mjs +0 -278
  312. package/lib/kpi.test.mjs +0 -244
  313. package/lib/learning/config.test.mjs +0 -75
  314. package/lib/learning/counters.test.mjs +0 -69
  315. package/lib/learning/curator-consolidate.test.mjs +0 -238
  316. package/lib/learning/curator.test.mjs +0 -106
  317. package/lib/learning/reflect.test.mjs +0 -0
  318. package/lib/learning/session-index.test.mjs +0 -125
  319. package/lib/learning/skill-writer.test.mjs +0 -210
  320. package/lib/mandate/audit.test.mjs +0 -195
  321. package/lib/mandate/contract.test.mjs +0 -185
  322. package/lib/mandate/derive.test.mjs +0 -274
  323. package/lib/mandate/model.test.mjs +0 -164
  324. package/lib/mandate/refresh.test.mjs +0 -389
  325. package/lib/mcp/server.test.mjs +0 -426
  326. package/lib/model-router/auth-profiles.test.mjs +0 -580
  327. package/lib/model-router/catalog.test.mjs +0 -385
  328. package/lib/model-router/economics.test.mjs +0 -438
  329. package/lib/model-router/failover.test.mjs +0 -439
  330. package/lib/model-router/health.test.mjs +0 -338
  331. package/lib/model-router/integration-coverage.test.mjs +0 -831
  332. package/lib/model-router/integration.test.mjs +0 -564
  333. package/lib/model-router/ledger.test.mjs +0 -415
  334. package/lib/model-router/llm-task.test.mjs +0 -392
  335. package/lib/model-router/org-credentials.test.mjs +0 -265
  336. package/lib/model-router/pricing-refresh.test.mjs +0 -286
  337. package/lib/model-router/reconcile.test.mjs +0 -316
  338. package/lib/model-router/repair.test.mjs +0 -180
  339. package/lib/model-router/spawn.test.mjs +0 -446
  340. package/lib/model-router/taxonomy.test.mjs +0 -410
  341. package/lib/model-router.test.mjs +0 -1207
  342. package/lib/org/activity.test.mjs +0 -134
  343. package/lib/org/approvals.test.mjs +0 -216
  344. package/lib/org/awareness.test.mjs +0 -159
  345. package/lib/org/board-mine-cache.test.mjs +0 -53
  346. package/lib/org/board.test.mjs +0 -187
  347. package/lib/org/bootstrap-context.test.mjs +0 -153
  348. package/lib/org/client.test.mjs +0 -1206
  349. package/lib/org/cohort-client.test.mjs +0 -126
  350. package/lib/org/cost-sync.test.mjs +0 -153
  351. package/lib/org/doctor.test.mjs +0 -346
  352. package/lib/org/engagement-ledger.test.mjs +0 -112
  353. package/lib/org/engagement.test.mjs +0 -739
  354. package/lib/org/handoff.test.mjs +0 -269
  355. package/lib/org/inbound/directedness.test.mjs +0 -668
  356. package/lib/org/inbound/facts.test.mjs +0 -471
  357. package/lib/org/inbound/hydrate.test.mjs +0 -908
  358. package/lib/org/inbound/index.test.mjs +0 -429
  359. package/lib/org/inbound/project.test.mjs +0 -287
  360. package/lib/org/integration-tools.test.mjs +0 -160
  361. package/lib/org/keys.test.mjs +0 -92
  362. package/lib/org/knowledge.test.mjs +0 -326
  363. package/lib/org/leases.test.mjs +0 -235
  364. package/lib/org/mesh-directives.test.mjs +0 -110
  365. package/lib/org/mesh-integration.test.mjs +0 -127
  366. package/lib/org/mesh.test.mjs +0 -400
  367. package/lib/org/messaging.test.mjs +0 -471
  368. package/lib/org/param-contract.test.mjs +0 -477
  369. package/lib/org/policy.test.mjs +0 -237
  370. package/lib/org/protocol.checksum.test.mjs +0 -90
  371. package/lib/org/protocol.test.mjs +0 -323
  372. package/lib/org/push.test.mjs +0 -792
  373. package/lib/org/registry.test.mjs +0 -100
  374. package/lib/org/resource-tools.test.mjs +0 -361
  375. package/lib/org/tool-access.test.mjs +0 -144
  376. package/lib/org/tool-surface-integration.test.mjs +0 -120
  377. package/lib/org/tool-surface.test.mjs +0 -1268
  378. package/lib/org/typing.test.mjs +0 -291
  379. package/lib/org/ui-parity.test.mjs +0 -560
  380. package/lib/org/verify.test.mjs +0 -194
  381. package/lib/org/work-ledger.test.mjs +0 -273
  382. package/lib/plan/adoption-e2e.test.mjs +0 -366
  383. package/lib/plan/budget-enforcement.test.mjs +0 -400
  384. package/lib/plan/compile.test.mjs +0 -382
  385. package/lib/plan/emit.test.mjs +0 -269
  386. package/lib/plan/explain.test.mjs +0 -188
  387. package/lib/prompts/parallelism.test.mjs +0 -177
  388. package/lib/rag/rag.test.mjs +0 -505
  389. package/lib/rate-guard.test.mjs +0 -272
  390. package/lib/reactive-gate.test.mjs +0 -57
  391. package/lib/render.test.mjs +0 -68
  392. package/lib/resource-governor.test.mjs +0 -488
  393. package/lib/scheduling/dynamic-jobs.test.mjs +0 -344
  394. package/lib/scheduling/jitter.test.mjs +0 -140
  395. package/lib/secrets/broker.test.mjs +0 -280
  396. package/lib/secrets/providers.test.mjs +0 -274
  397. package/lib/security/audit-engine.test.mjs +0 -424
  398. package/lib/security/coerce-args.test.mjs +0 -281
  399. package/lib/security/dangerous-tools.test.mjs +0 -68
  400. package/lib/security/external-content.test.mjs +0 -84
  401. package/lib/security/redact.test.mjs +0 -441
  402. package/lib/security/secret-equal.test.mjs +0 -55
  403. package/lib/session/config.test.mjs +0 -92
  404. package/lib/session/feed-core.test.mjs +0 -198
  405. package/lib/session/first-run.test.mjs +0 -121
  406. package/lib/session/frontdoor.test.mjs +0 -205
  407. package/lib/session/handoffs.test.mjs +0 -183
  408. package/lib/session/identity.test.mjs +0 -180
  409. package/lib/session/inbox-claims.test.mjs +0 -286
  410. package/lib/session/launch-args.test.mjs +0 -157
  411. package/lib/session/liveness.test.mjs +0 -100
  412. package/lib/session/status-summary.test.mjs +0 -118
  413. package/lib/session-permissions.test.mjs +0 -120
  414. package/lib/setup/claude-probe.test.mjs +0 -187
  415. package/lib/setup/completeness.test.mjs +0 -110
  416. package/lib/setup/context-pack.test.mjs +0 -89
  417. package/lib/setup/enrich.test.mjs +0 -115
  418. package/lib/setup/enroll-from-cohort.test.mjs +0 -300
  419. package/lib/setup/integration.test.mjs +0 -162
  420. package/lib/setup/io.test.mjs +0 -77
  421. package/lib/setup/runner.test.mjs +0 -132
  422. package/lib/setup/sections/identity.test.mjs +0 -234
  423. package/lib/setup/sections/inventory.test.mjs +0 -198
  424. package/lib/setup/sections/learning.test.mjs +0 -81
  425. package/lib/setup/sections/mandate.test.mjs +0 -388
  426. package/lib/setup/sections/messaging.test.mjs +0 -127
  427. package/lib/setup/sections/model.test.mjs +0 -240
  428. package/lib/setup/sections/org.test.mjs +0 -346
  429. package/lib/setup/sections/orgmail.test.mjs +0 -118
  430. package/lib/setup/sections/recovery.test.mjs +0 -98
  431. package/lib/setup/sections/subagents.test.mjs +0 -429
  432. package/lib/setup/sections/verify.test.mjs +0 -175
  433. package/lib/setup/sot.test.mjs +0 -81
  434. package/lib/setup/state.test.mjs +0 -115
  435. package/lib/singleton.test.mjs +0 -151
  436. package/lib/subagents/cli.test.mjs +0 -389
  437. package/lib/subagents/client.test.mjs +0 -309
  438. package/lib/subagents/gap.test.mjs +0 -234
  439. package/lib/subagents/lock.test.mjs +0 -248
  440. package/lib/subagents/manifest.test.mjs +0 -175
  441. package/lib/subagents/refs.test.mjs +0 -204
  442. package/lib/subagents/resolve.test.mjs +0 -422
  443. package/lib/subagents/schema.test.mjs +0 -328
  444. package/lib/telemetry/alerts.test.mjs +0 -109
  445. package/lib/telemetry/collect.test.mjs +0 -1274
  446. package/lib/tool-definitions-integration.test.mjs +0 -83
  447. package/lib/tool-definitions.test.mjs +0 -437
  448. package/lib/upgrade/global-refresh.test.mjs +0 -65
  449. package/lib/upgrade/launchd-reconcile.test.mjs +0 -272
  450. package/lib/upgrade/post-steps.test.mjs +0 -200
  451. package/lib/upgrade/verify.test.mjs +0 -164
  452. package/lib/util/fetch-timeout.test.mjs +0 -202
  453. package/lib/util/reconnect.test.mjs +0 -369
  454. package/lib/util/unhandled.test.mjs +0 -216
  455. package/lib/voice/outbound.test.mjs +0 -69
  456. package/lib/voice/session-rotation.test.mjs +0 -114
  457. package/lib/voice/stt.test.mjs +0 -226
  458. package/lib/voice/voice.test.mjs +0 -990
  459. package/scripts/cadence/enqueue-cadence-tick.test.mjs +0 -187
  460. package/scripts/ci/check-docs-accuracy.test.mjs +0 -409
  461. package/scripts/ci/check-durable-write-seam.test.mjs +0 -90
  462. package/scripts/ci/check-no-build-artifacts.test.mjs +0 -71
  463. package/scripts/ci/check-no-residual-identity.test.mjs +0 -202
  464. package/scripts/ci/check-skill-packs.test.mjs +0 -495
  465. package/scripts/ci/check-subagent-frontmatter.test.mjs +0 -124
  466. package/scripts/ci/check.test.mjs +0 -194
  467. package/scripts/ci/conformance-org-api.test.mjs +0 -425
  468. package/scripts/cloud-relay/voice/relay-identity.test.mjs +0 -96
  469. package/scripts/collective/hook-runner.test.mjs +0 -173
  470. package/scripts/cost/fleet-digest.test.mjs +0 -207
  471. package/scripts/cost/track-claude-usage-pricing.test.mjs +0 -183
  472. package/scripts/cost/track-claude-usage.test.mjs +0 -148
  473. package/scripts/daemon/agent-daemon-board-mine.test.mjs +0 -96
  474. package/scripts/daemon/agent-daemon-design.test.mjs +0 -238
  475. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +0 -60
  476. package/scripts/daemon/agent-daemon.test.mjs +0 -995
  477. package/scripts/daemon/assurance-e2e.test.mjs +0 -613
  478. package/scripts/daemon/assurance.test.mjs +0 -1791
  479. package/scripts/daemon/board-mirror.test.mjs +0 -165
  480. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +0 -393
  481. package/scripts/daemon/cadence-consumer-governance.test.mjs +0 -276
  482. package/scripts/daemon/cadence-consumer.test.mjs +0 -776
  483. package/scripts/daemon/cadence-handlers.test.mjs +0 -837
  484. package/scripts/daemon/classifier-identity.test.mjs +0 -137
  485. package/scripts/daemon/classifier.test.mjs +0 -266
  486. package/scripts/daemon/classify-kind.test.mjs +0 -40
  487. package/scripts/daemon/context-compiler.test.mjs +0 -406
  488. package/scripts/daemon/deliver.test.mjs +0 -564
  489. package/scripts/daemon/dispatcher-cooldown.test.mjs +0 -122
  490. package/scripts/daemon/dispatcher-governance.test.mjs +0 -1013
  491. package/scripts/daemon/dispatcher-resume.test.mjs +0 -166
  492. package/scripts/daemon/dispatcher-session-continuity.test.mjs +0 -365
  493. package/scripts/daemon/execution-ladder.test.mjs +0 -470
  494. package/scripts/daemon/goal-steward-cadence.test.mjs +0 -312
  495. package/scripts/daemon/inbox-deferral-session.test.mjs +0 -49
  496. package/scripts/daemon/inbox-deferral.test.mjs +0 -336
  497. package/scripts/daemon/inbox-wake.test.mjs +0 -199
  498. package/scripts/daemon/integration.test.mjs +0 -149
  499. package/scripts/daemon/lib/self-echo.test.mjs +0 -153
  500. package/scripts/daemon/lib/session-router.test.mjs +0 -554
  501. package/scripts/daemon/prompt-builder-preamble.test.mjs +0 -210
  502. package/scripts/daemon/prompt-builder.test.mjs +0 -556
  503. package/scripts/daemon/responder-cost.test.mjs +0 -68
  504. package/scripts/daemon/responder-history.test.mjs +0 -221
  505. package/scripts/daemon/sdk-version.test.mjs +0 -31
  506. package/scripts/daemon/session-lock.test.mjs +0 -252
  507. package/scripts/daemon/session-outcomes.test.mjs +0 -533
  508. package/scripts/daemon/typing-registry.test.mjs +0 -102
  509. package/scripts/hooks/pre-send-audit.test.mjs +0 -354
  510. package/scripts/huddle/huddle-prompt.test.mjs +0 -176
  511. package/scripts/local-triggers/autoupdate.test.mjs +0 -518
  512. package/scripts/local-triggers/generate-plists.test.mjs +0 -456
  513. package/scripts/media-generation/brand-clause.test.mjs +0 -135
  514. package/scripts/org/send-orgmail.first-contact.test.mjs +0 -102
  515. package/scripts/poller/inbox-privilege-injection.test.mjs +0 -167
  516. package/scripts/poller/inbox-scan-poller.test.mjs +0 -295
  517. package/scripts/poller/lib/cloud-relay-dedup.test.mjs +0 -133
  518. package/scripts/poller/slack-socket-mode.test.mjs +0 -805
  519. package/scripts/poller-launchd/install.test.mjs +0 -243
  520. package/scripts/restore-from-backup.test.mjs +0 -181
  521. package/scripts/session/feed.test.mjs +0 -196
  522. package/scripts/session/supervisor-sh.test.mjs +0 -218
  523. package/scripts/session/supervisor.test.mjs +0 -482
  524. package/scripts/setup/configure-macos.test.mjs +0 -306
  525. package/scripts/setup/gen-subagent-manifest.test.mjs +0 -124
  526. package/scripts/setup/generate-agent-package-json.test.mjs +0 -143
  527. package/scripts/setup/generate-capability.test.mjs +0 -134
  528. package/scripts/setup/init-agent.test.mjs +0 -370
  529. package/scripts/setup/init-skill-marketplace.test.mjs +0 -193
  530. package/scripts/vendor/sync-skill-packs.test.mjs +0 -103
  531. package/scripts/watchdog/memory-watchdog.test.mjs +0 -64
@@ -0,0 +1,676 @@
1
+ /**
2
+ * lib/session/current-work.mjs — "what am I doing right now, across the
3
+ * sessions on this machine", as a fact the agent can answer from.
4
+ *
5
+ * THE QUESTION THIS ANSWERS. A human asks, in a channel or a DM, "what are you
6
+ * doing right now?". Before this module the reply had nothing to read: the
7
+ * compiled context carried `state/sessions/active.json` (the daemon's own
8
+ * `--print` children, summary + model + sender) and nothing else — not the
9
+ * front-door session, not its peers, not the board items already in progress,
10
+ * and not the fact that a person has an interactive session open on the box.
11
+ * The quick-reply path carried none of it. So the honest answer was
12
+ * unavailable and the model either confabulated or hedged.
13
+ *
14
+ * ONE derivation, four readers. `summarizeCurrentWork` is PURE over injected
15
+ * snapshots of the five state files the writers already keep:
16
+ *
17
+ * state/session/heartbeat.json the front door's beat (feed.mjs, 15 s)
18
+ * state/session/main-session.json {sessionId, createdAt}
19
+ * state/session/peers.json {peers:[{name, purpose, startedAt}]}
20
+ * state/sessions/active.json the dispatcher's live children (this
21
+ * module also defines that entry's shape —
22
+ * {@link activeEntryFor} — so the writer
23
+ * and the reader cannot drift)
24
+ * state/collective/presence/*.json every Claude Code session on the machine
25
+ * (lib/collective/presence.mjs)
26
+ * state/org/board-mine.json the daemon's 5-minute `board.mine` cache
27
+ * state/session/handoffs/*.json cadence ticks handed to the front door
28
+ * (counted, never read)
29
+ *
30
+ * `renderCurrentWork` turns the summary into a BOUNDED block (≤ 8 lines by
31
+ * default) for a prompt: the spawn path's compiled context and the quick-reply
32
+ * path's user content both inject it, so a "what are you doing" question is
33
+ * answered from fact on either path.
34
+ *
35
+ * THE SINGLE SOURCE. This is the ONLY renderer of "what am I doing". The
36
+ * 2.18.0 roll-call work briefly had a second one (`renderSelfActivity` in
37
+ * lib/org/inbound/broadcast.mjs, fed by the daemon's own file reads) and the
38
+ * quick reply injected both — two overlapping accounts of the same state,
39
+ * one of which quoted session names. Everything that renderer carried and
40
+ * this one lacked — the front door being absent, the board rows that are
41
+ * queued or blocked (not only in progress), the open handoffs — lives here
42
+ * now, behind the same audience and barrier predicate as the rest, and a
43
+ * roll-call reply calls this once (`explicitEmpty`, below, is the roll-call's
44
+ * "nothing is running" line). responder-single-source.test.mjs pins that no
45
+ * second renderer is imported by the responder again.
46
+ *
47
+ * The block is SHARED by readers the responder is not — `maestro session
48
+ * status`, the `session_status` tool, the spawned session's compiled context
49
+ * — so it states only what is true from every seat. The one line whose
50
+ * explanation depends on who is asking (an absent front door: "…and so this
51
+ * reply comes from the background responder" is true of the responder and
52
+ * false of a peer or a person at the CLI) takes that explanation from the
53
+ * caller (`mainAbsentNote`) and otherwise says only that the front door is
54
+ * not running. Likewise `explicitEmpty`: today only the quick-reply path
55
+ * asks for it, because agent-daemon routes every roll-call to that path and
56
+ * a live front door always renders a block; a spawned child or a
57
+ * tool-answering session composing a roll-call from nothing would get "" and
58
+ * no "do not invent" line — a known edge, not a reachable one today.
59
+ *
60
+ * THE PRIVACY FLOOR. A human's interactive Claude Code session on an agent box
61
+ * is reported as EXISTING — "an interactive session is open since T" — and
62
+ * nothing else: not its cwd, not its repo, not its intent, never its prompt.
63
+ * The 2.11.10 reaper fix made those sessions invisible to reap/count; this
64
+ * keeps them invisible to reporting beyond existence. The agent's OWN sessions
65
+ * (the front door, its peers, the daemon's children) are the ones described.
66
+ *
67
+ * THE AUDIENCE RULE ({@link scopeCurrentWorkFor}). A dispatched session's
68
+ * summary is the classifier's paraphrase of SOMEONE'S message — "draft the
69
+ * termination letter for X for Dana" is Dana's DM, restated. Design §5.5:
70
+ * per-person facts may inform a reply but are never quoted into a room they
71
+ * did not come from. So the block is rendered FOR an audience, and a
72
+ * dispatched session is described to that audience only when it came from
73
+ * the same conversation (the same channel id, or — in a private conversation
74
+ * — the same person); every other session is reported as EXISTING ("a request
75
+ * from another conversation"), with no summary, no sender, no channel and no
76
+ * board id. A session that is nobody's message — a backlog row with no sender
77
+ * and no ask — is the agent's own work and is described, barrier permitting. The information-barrier keyword filter the context compiler
78
+ * applies to history (`forbidsText`) is applied to whatever survives: a
79
+ * disclosable summary, a board title, a peer's purpose. An audience of `{}` —
80
+ * no identity — sees nothing cross-conversation; `null` is the operator's own
81
+ * view (`maestro session status --all`) and scopes nothing.
82
+ *
83
+ * Everything is fail-open: a missing or corrupt snapshot reads as absent.
84
+ * `now` is a parameter wherever it changes the answer. Node builtins only.
85
+ *
86
+ * @module lib/session/current-work
87
+ */
88
+
89
+ "use strict";
90
+
91
+ import { existsSync, readFileSync } from "node:fs";
92
+ import { join } from "node:path";
93
+ import { summarizeSessionStatus, listOpenHandoffs } from "./status-summary.mjs";
94
+ import { TERMINAL_STATUS } from "../org/protocol.mjs";
95
+
96
+ /** Lines the rendered block may not exceed (one of them is the header). */
97
+ export const CURRENT_WORK_MAX_LINES = 8;
98
+
99
+ /** Board columns that mean "in progress" across the column vocabularies hq has used. */
100
+ const IN_PROGRESS_COLS = Object.freeze(["running", "doing", "in_progress", "in-progress"]);
101
+ /** Board columns that mean "stuck": reported as blocked, which a roll-call asks about by name. */
102
+ const BLOCKED_COLS = Object.freeze(["blocked"]);
103
+ /**
104
+ * Board columns that mean "done on my side, waiting on a reviewer": not in
105
+ * progress, not queued (the work is finished), not terminal (it can come
106
+ * back). protocol's A2A map puts `review` with `blocked` (`input-required`),
107
+ * which is the honest reading for a roll-call: it is waiting on someone.
108
+ */
109
+ const REVIEW_COLS = Object.freeze(["review", "in_review", "in-review"]);
110
+ /**
111
+ * Board columns with no further work — never "queued". The protocol's own
112
+ * TERMINAL_STATUS is the base so the two cannot drift; the extra spellings
113
+ * are the ones other boards hq has fed `board.mine` from have used.
114
+ */
115
+ const TERMINAL_COLS = Object.freeze([...TERMINAL_STATUS, "closed", "cancelled", "canceled", "complete", "completed"]);
116
+
117
+ /** A `--name <first>-main` front door, or a `--name <first>-<slug>` peer. */
118
+ const MAIN_NAME_RE = /-main$/;
119
+
120
+ function toMs(v) {
121
+ if (typeof v === "number" && Number.isFinite(v)) return v;
122
+ if (typeof v === "string") {
123
+ const n = Date.parse(v);
124
+ if (Number.isFinite(n)) return n;
125
+ const asNum = Number(v);
126
+ if (Number.isFinite(asNum) && v.trim() !== "") return asNum;
127
+ }
128
+ return null;
129
+ }
130
+
131
+ function iso(ms) {
132
+ return ms === null ? null : new Date(ms).toISOString();
133
+ }
134
+
135
+ function clip(s, n) {
136
+ const t = String(s == null ? "" : s).replace(/\s+/g, " ").trim();
137
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
138
+ }
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // The active.json entry (written by the dispatcher, read here)
142
+ // ---------------------------------------------------------------------------
143
+
144
+ /**
145
+ * The board item a queue row is FOR, when it is for one.
146
+ *
147
+ * The execution ladder queues a `task_assigned` / `task_comment` event as a
148
+ * backlog row carrying `source_ref: cohort:<surface>:<entityId>:<seq>` and
149
+ * `entity_id: <taskId>` (lib/execution/effects.scheduleToQueue). That row is
150
+ * the daemon's only handle on "a board item was assigned to me" — so it is the
151
+ * one place the item id can be read back from, and the reason a dispatched
152
+ * backlog session can name the board item it is working.
153
+ *
154
+ * Also honours a live inbox item of the same surfaces (`kind` +
155
+ * `channel_id`/`entity_id`), so both dispatch paths agree.
156
+ *
157
+ * PURE. Returns null when the row is not about a board item.
158
+ *
159
+ * @param {object} item a queue row (lib/backlog.parseQueueItems) or inbox item
160
+ * @returns {{itemId:string, surface:string}|null}
161
+ */
162
+ export function boardItemRefFor(item) {
163
+ if (!item || typeof item !== "object") return null;
164
+ const ref = String(item.source_ref || item.raw_ref || "").trim();
165
+ if (ref.startsWith("cohort:")) {
166
+ const parts = ref.split(":");
167
+ const surface = parts[1] || "";
168
+ if (surface === "task_assigned" || surface === "task_comment") {
169
+ const id = String(item.entity_id || parts[2] || "").trim();
170
+ return id ? { itemId: id, surface } : null;
171
+ }
172
+ }
173
+ const kind = String(item.kind || "").trim();
174
+ if (kind === "task_assigned" || kind === "task_comment") {
175
+ const id = String(item.entity_id || item.channel_id || item.channel || "").trim();
176
+ return id ? { itemId: id, surface: kind } : null;
177
+ }
178
+ return null;
179
+ }
180
+
181
+ /**
182
+ * The record the dispatcher writes for one live child under
183
+ * `state/sessions/active.json[sessionId]`.
184
+ *
185
+ * Carries the ASK IDENTITY (`ask.channelId` + `ask.messageId`, the pair hq's
186
+ * `board.track` dedupes on) so the board row the daemon opens for an inbox
187
+ * ask can be linked back to the session ({@link linkBoardTask}); carries the
188
+ * board item id when the session is a backlog row for one; and carries the
189
+ * queue row id and title so a backlog session can be named. PURE.
190
+ *
191
+ * @param {object} o
192
+ * @param {object} [o.item]
193
+ * @param {object} [o.classResult]
194
+ * @param {string} [o.source] "inbox" | "backlog"
195
+ * @param {number} [o.now]
196
+ */
197
+ export function activeEntryFor(o = {}) {
198
+ const item = o.item && typeof o.item === "object" ? o.item : {};
199
+ const cr = o.classResult && typeof o.classResult === "object" ? o.classResult : {};
200
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
201
+ const service = String(item.service || "").trim().toLowerCase();
202
+ const channelId = String(item.cohort_channel_id || item.channel_id || "").trim();
203
+ let messageId = null;
204
+ const raw = String(item.raw_ref || "").trim();
205
+ if (raw.startsWith("cohort:")) {
206
+ const parts = raw.split(":");
207
+ if (parts.length >= 3 && parts[2]) messageId = parts[2];
208
+ }
209
+ if (!messageId) {
210
+ const id = String(item.id || "").trim();
211
+ if (id.startsWith("cohort-")) messageId = id.slice("cohort-".length) || null;
212
+ }
213
+ const ask = service === "cohort" && channelId && messageId ? { channelId, messageId } : null;
214
+ const board = boardItemRefFor(item);
215
+ return {
216
+ sender: item.sender || null,
217
+ channel: item.channel || item.channel_id || null,
218
+ summary: cr.summary || item.title || "unknown",
219
+ model: cr.model || "sonnet",
220
+ startTime: now,
221
+ source: o.source || "inbox",
222
+ itemId: item.id ? String(item.id) : null,
223
+ title: item.title ? clip(item.title, 160) : null,
224
+ ask,
225
+ boardItemId: board ? board.itemId : null,
226
+ // Filled by linkBoardTask once the daemon's `working` board.track resolves.
227
+ boardTaskId: null,
228
+ boardCol: null,
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Attach the board row hq opened for an ask to the live session that is
234
+ * working it. PURE over the active map: returns a NEW map, and the id of the
235
+ * entry it changed (or null when no live entry carries that ask).
236
+ *
237
+ * The daemon's `accepted`→`working` board.track is fire-and-forget and
238
+ * resolves AFTER the dispatch (agent-daemon.mjs), so the link is a second
239
+ * write, matched on the ask identity the entry already carries.
240
+ *
241
+ * @param {object} active the parsed active.json
242
+ * @param {{channelId:string, messageId:string}} ask
243
+ * @param {{taskId:string, col?:string|null}} row
244
+ * @returns {{active:object, sessionId:string|null}}
245
+ */
246
+ export function linkBoardTask(active, ask, row) {
247
+ const cur = active && typeof active === "object" && !Array.isArray(active) ? active : {};
248
+ const out = { ...cur };
249
+ if (!ask || !ask.channelId || !ask.messageId || !row || !row.taskId) return { active: out, sessionId: null };
250
+ let hit = null;
251
+ for (const [id, e] of Object.entries(cur)) {
252
+ const a = e && e.ask;
253
+ if (a && a.channelId === ask.channelId && a.messageId === ask.messageId) {
254
+ out[id] = { ...e, boardTaskId: String(row.taskId), boardCol: row.col ? String(row.col) : e.boardCol || null };
255
+ hit = id;
256
+ break;
257
+ }
258
+ }
259
+ return { active: out, sessionId: hit };
260
+ }
261
+
262
+ // ---------------------------------------------------------------------------
263
+ // The summary (pure)
264
+ // ---------------------------------------------------------------------------
265
+
266
+ function peersOf(peers) {
267
+ if (Array.isArray(peers)) return peers.filter((p) => p && typeof p === "object");
268
+ if (peers && typeof peers === "object" && Array.isArray(peers.peers)) return peers.peers.filter((p) => p && typeof p === "object");
269
+ return [];
270
+ }
271
+
272
+ function activeOf(active) {
273
+ if (Array.isArray(active)) return active.filter((e) => e && typeof e === "object").map((e, i) => [e.sessionId || e.id || `s${i}`, e]);
274
+ if (active && typeof active === "object") return Object.entries(active).filter(([, e]) => e && typeof e === "object");
275
+ return [];
276
+ }
277
+
278
+ function itemsOf(boardMine) {
279
+ if (Array.isArray(boardMine)) return boardMine;
280
+ if (boardMine && typeof boardMine === "object" && Array.isArray(boardMine.items)) return boardMine.items;
281
+ return [];
282
+ }
283
+
284
+ /**
285
+ * Derive the current-work summary from snapshots. PURE.
286
+ *
287
+ * @param {object} o
288
+ * @param {object|null} [o.heartbeat] state/session/heartbeat.json
289
+ * @param {object|null} [o.mainSession] state/session/main-session.json
290
+ * @param {object|object[]|null} [o.peers] state/session/peers.json
291
+ * @param {object|null} [o.active] state/sessions/active.json
292
+ * @param {object[]|null} [o.presence] lib/collective/presence.list() records
293
+ * @param {object|object[]|null} [o.boardMine] state/org/board-mine.json
294
+ * @param {string[]|null} [o.handoffs] names of open handoff files (state/session/handoffs)
295
+ * @param {number} [o.now]
296
+ * @param {number} [o.staleMs]
297
+ * @param {string} [o.excludeSessionId] the session composing the reply (never lists itself as "another")
298
+ */
299
+ export function summarizeCurrentWork(o = {}) {
300
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
301
+ const status = summarizeSessionStatus({ heartbeat: o.heartbeat, peers: o.peers, handoffs: o.handoffs, now, staleMs: o.staleMs });
302
+ const main = o.mainSession && typeof o.mainSession === "object" ? o.mainSession : null;
303
+ const mainSessionId = (main && typeof main.sessionId === "string" && main.sessionId) || status.sessionId || null;
304
+ const mainSince = main ? toMs(main.createdAt) : null;
305
+
306
+ const peers = peersOf(o.peers).map((p) => ({
307
+ name: typeof p.name === "string" ? p.name : null,
308
+ purpose: typeof p.purpose === "string" ? clip(p.purpose, 140) : null,
309
+ startedAt: toMs(p.startedAt) !== null ? iso(toMs(p.startedAt)) : null,
310
+ }));
311
+ const peerNames = new Set(peers.map((p) => p.name).filter(Boolean));
312
+
313
+ const dispatched = activeOf(o.active).map(([id, e]) => {
314
+ const started = toMs(e.startTime || e.started_at || e.startedAt);
315
+ return {
316
+ sessionId: String(id),
317
+ source: e.source || "inbox",
318
+ summary: clip(e.summary || e.title || "unknown", 140),
319
+ sender: e.sender || null,
320
+ channel: e.channel || null,
321
+ startedAt: iso(started),
322
+ ageMs: started === null ? null : Math.max(0, now - started),
323
+ itemId: e.itemId || null,
324
+ boardItemId: e.boardItemId || null,
325
+ boardTaskId: e.boardTaskId || null,
326
+ ask: e.ask && typeof e.ask === "object" ? { channelId: e.ask.channelId || null, messageId: e.ask.messageId || null } : null,
327
+ };
328
+ });
329
+
330
+ // Interactive sessions that are NOT the agent's own: existence only.
331
+ const presence = Array.isArray(o.presence) ? o.presence.filter((r) => r && typeof r === "object") : [];
332
+ let interactiveOpen = 0;
333
+ let interactiveSince = null;
334
+ for (const r of presence) {
335
+ if (r.kind === "daemon") continue;
336
+ if (o.excludeSessionId && r.sessionId === o.excludeSessionId) continue;
337
+ if (mainSessionId && r.sessionId === mainSessionId) continue;
338
+ const name = typeof r.agentName === "string" ? r.agentName : "";
339
+ if (name && (MAIN_NAME_RE.test(name) || peerNames.has(name))) continue;
340
+ interactiveOpen += 1;
341
+ const s = toMs(r.startedAt);
342
+ if (s !== null && (interactiveSince === null || s < interactiveSince)) interactiveSince = s;
343
+ }
344
+
345
+ // Board rows, split the way a roll-call asks about them: in progress,
346
+ // blocked, queued. A terminal row (done/archived) is history, not work.
347
+ const boardRows = itemsOf(o.boardMine)
348
+ .filter((i) => i && typeof i === "object")
349
+ .map((i) => ({
350
+ itemId: i.itemId ? String(i.itemId) : null,
351
+ title: clip(i.title || "", 120),
352
+ boardName: i.boardName || null,
353
+ col: String(i.col || i.stage || i.status || "").toLowerCase() || null,
354
+ updatedAt: toMs(i.updatedAt) !== null ? iso(toMs(i.updatedAt)) : null,
355
+ }))
356
+ .filter((i) => i.itemId);
357
+ const boardInProgress = boardRows.filter((i) => IN_PROGRESS_COLS.includes(i.col)).map(({ col, ...rest }) => rest);
358
+ const boardBlocked = boardRows.filter((i) => BLOCKED_COLS.includes(i.col));
359
+ const boardInReview = boardRows.filter((i) => REVIEW_COLS.includes(i.col)).map(({ col, ...rest }) => rest);
360
+ const boardQueued = boardRows.filter((i) =>
361
+ i.col && !IN_PROGRESS_COLS.includes(i.col) && !BLOCKED_COLS.includes(i.col) && !REVIEW_COLS.includes(i.col) && !TERMINAL_COLS.includes(i.col));
362
+
363
+ return {
364
+ now: iso(now),
365
+ main: {
366
+ live: status.live,
367
+ state: status.state,
368
+ sessionId: mainSessionId,
369
+ since: iso(mainSince),
370
+ beatAgeMs: status.ageMs,
371
+ },
372
+ dispatched,
373
+ peers,
374
+ interactiveOpen,
375
+ interactiveSince: iso(interactiveSince),
376
+ boardInProgress,
377
+ boardBlocked,
378
+ boardInReview,
379
+ boardQueued,
380
+ handoffsOpen: Number.isFinite(status.handoffsOpen) ? status.handoffsOpen : 0,
381
+ };
382
+ }
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // The audience (pure)
386
+ // ---------------------------------------------------------------------------
387
+
388
+ /** What a redacted dispatched entry says instead of its summary. */
389
+ export const REDACTED_WORK = "a request from another conversation";
390
+ /** What a redacted peer purpose says. */
391
+ export const REDACTED_PURPOSE = "(purpose not shareable here)";
392
+
393
+ function sameConversation(d, audience) {
394
+ // Work that is nobody's message — a backlog row with no sender and no ask
395
+ // (the agent's own queue, or a board item assigned to it) — is the agent's
396
+ // own to describe, subject only to the barrier. The rule below is about
397
+ // summaries that restate a PERSON's message.
398
+ if (!d.sender && !d.ask) return true;
399
+ const chanId = String(audience.channelId || "").trim();
400
+ const chan = String(audience.channel || "").trim();
401
+ const askChan = d.ask && d.ask.channelId ? String(d.ask.channelId) : "";
402
+ const dChan = d.channel ? String(d.channel) : "";
403
+ if (chanId && askChan && chanId === askChan) return true;
404
+ if (chanId && dChan && chanId === dChan) return true;
405
+ if (chan && dChan && chan === dChan) return true;
406
+ // The same PERSON, in a PRIVATE conversation with them: their own asks may
407
+ // be described back to them. In a room, only the room's own asks — a
408
+ // person's DM ask is not quoted into a channel even for that person (§5.5).
409
+ const sender = String(audience.sender || "").trim().toLowerCase();
410
+ if (audience.isPrivate === true && sender && d.sender && String(d.sender).trim().toLowerCase() === sender) return true;
411
+ return false;
412
+ }
413
+
414
+ /**
415
+ * Scope a summary to an audience. PURE; returns a NEW summary.
416
+ *
417
+ * @param {object} summary from {@link summarizeCurrentWork}
418
+ * @param {{sender?:string, channelId?:string, channel?:string, isPrivate?:boolean, forbidsText?:(text:string)=>boolean}|null} audience
419
+ * `null` → the operator's own view: nothing is scoped. `{}` → an audience
420
+ * with no identity: every dispatched session is reported as existing only.
421
+ * @returns {object}
422
+ */
423
+ export function scopeCurrentWorkFor(summary, audience) {
424
+ const s = summary && typeof summary === "object" ? summary : summarizeCurrentWork({});
425
+ if (audience === null) return s;
426
+ const a = audience && typeof audience === "object" ? audience : {};
427
+ const forbids = typeof a.forbidsText === "function"
428
+ ? (t) => { try { return Boolean(a.forbidsText(String(t || ""))); } catch { return true; } }
429
+ : () => false;
430
+
431
+ const dispatched = (s.dispatched || []).map((d) => {
432
+ const visible = sameConversation(d, a) && !forbids(d.summary);
433
+ if (visible) return { ...d, redacted: false };
434
+ return {
435
+ sessionId: d.sessionId, source: d.source, startedAt: d.startedAt, ageMs: d.ageMs,
436
+ summary: null, sender: null, channel: null, itemId: null, boardItemId: null, boardTaskId: null, ask: null,
437
+ redacted: true,
438
+ };
439
+ });
440
+ const boardInProgress = (s.boardInProgress || []).filter((b) => !forbids(b.title));
441
+ const boardBlocked = (s.boardBlocked || []).filter((b) => !forbids(b.title));
442
+ const boardInReview = (s.boardInReview || []).filter((b) => !forbids(b.title));
443
+ const boardQueued = (s.boardQueued || []).filter((b) => !forbids(b.title));
444
+ const peers = (s.peers || []).map((p) => (p.purpose && forbids(p.purpose) ? { ...p, purpose: null, redacted: true } : { ...p, redacted: false }));
445
+ return { ...s, dispatched, boardInProgress, boardBlocked, boardInReview, boardQueued, peers, scoped: true };
446
+ }
447
+
448
+ // ---------------------------------------------------------------------------
449
+ // The block (pure)
450
+ // ---------------------------------------------------------------------------
451
+
452
+ function ageLabel(ms) {
453
+ if (!Number.isFinite(ms) || ms < 0) return "just now";
454
+ const m = Math.round(ms / 60_000);
455
+ if (m < 1) return "just now";
456
+ if (m < 60) return `${m}m`;
457
+ const h = Math.round(m / 60);
458
+ if (h < 48) return `${h}h`;
459
+ return `${Math.round(h / 24)}d`;
460
+ }
461
+
462
+ function sinceLabel(isoTs, now) {
463
+ const t = toMs(isoTs);
464
+ if (t === null) return "";
465
+ return ` (since ${isoTs.slice(0, 16).replace("T", " ")}Z, ${ageLabel(now - t)})`;
466
+ }
467
+
468
+ /** The block's header. Exported so a test can count it in a prompt. */
469
+ export const CURRENT_WORK_HEADER = "## Current Work (your own sessions on this machine, right now)";
470
+
471
+ /**
472
+ * The one line a roll-call gets when nothing at all is known. A roll-call
473
+ * answer composed from NO block would be composed from nothing — and the
474
+ * model fills nothing with invention. So the roll-call asks for this line
475
+ * instead of "", and the instruction to say so travels with it.
476
+ */
477
+ export const CURRENT_WORK_EMPTY_LINE =
478
+ "- Nothing is recorded as running, queued or blocked on this machine right now — say so plainly; do not invent activity.";
479
+
480
+ /**
481
+ * Render the summary as a bounded prompt block. PURE.
482
+ *
483
+ * Priority when the cap bites: dispatched sessions (the live work), then
484
+ * board items in progress, then blocked, then awaiting review, then peers,
485
+ * then the front door, then queued board items, then open handoffs, then the
486
+ * interactive-session line. The cap counts the header. Returns "" when there
487
+ * is genuinely nothing to say AND no front door — the caller then omits the
488
+ * section; a live-but-idle front door still renders, because "nothing else
489
+ * is running" is itself the honest answer. `explicitEmpty` (the roll-call)
490
+ * renders {@link CURRENT_WORK_EMPTY_LINE} under the header instead of "".
491
+ *
492
+ * `mainAbsentNote` is the caller's explanation of an absent front door,
493
+ * rendered in parentheses after "Main session: not running" — the daemon's
494
+ * quick reply says "this reply comes from the background responder"; every
495
+ * other reader (`maestro session status`, `session_status`, the compiled
496
+ * context of a spawned session) passes nothing, because from those seats
497
+ * that sentence would be false.
498
+ *
499
+ * @param {object} summary from {@link summarizeCurrentWork}
500
+ * @param {{max?:number, now?:number, explicitEmpty?:boolean, mainAbsentNote?:string}} [o]
501
+ * @returns {string}
502
+ */
503
+ export function renderCurrentWork(summary, o = {}) {
504
+ const s = summary && typeof summary === "object" ? summary : summarizeCurrentWork({});
505
+ const max = Number.isFinite(o.max) && o.max > 1 ? o.max : CURRENT_WORK_MAX_LINES;
506
+ const now = Number.isFinite(o.now) ? o.now : toMs(s.now) ?? Date.now();
507
+ const blocked = Array.isArray(s.boardBlocked) ? s.boardBlocked : [];
508
+ const inReview = Array.isArray(s.boardInReview) ? s.boardInReview : [];
509
+ const queued = Array.isArray(s.boardQueued) ? s.boardQueued : [];
510
+ const handoffs = Number.isFinite(s.handoffsOpen) ? s.handoffsOpen : 0;
511
+ const mainAbsentNote = typeof o.mainAbsentNote === "string" ? clip(o.mainAbsentNote, 120) : "";
512
+ const nothing =
513
+ !s.main.live && s.main.state !== "stale" &&
514
+ s.dispatched.length === 0 && s.peers.length === 0 && s.boardInProgress.length === 0 &&
515
+ blocked.length === 0 && inReview.length === 0 && queued.length === 0 && handoffs === 0 && s.interactiveOpen === 0;
516
+ if (nothing) return o.explicitEmpty === true ? [CURRENT_WORK_HEADER, CURRENT_WORK_EMPTY_LINE].join("\n") : "";
517
+
518
+ const lines = [];
519
+ for (const d of s.dispatched) {
520
+ if (d.redacted) {
521
+ lines.push(`- Working now${sinceLabel(d.startedAt, now)}: ${REDACTED_WORK} — you can say you are busy with it; you cannot say what it is or who it is for`);
522
+ continue;
523
+ }
524
+ const who = d.sender ? ` for ${d.sender}` : "";
525
+ const where = d.channel ? ` in ${d.channel}` : "";
526
+ const board = d.boardTaskId ? ` — board item ${d.boardTaskId}` : d.boardItemId ? ` — board item ${d.boardItemId}` : "";
527
+ lines.push(`- Working now${sinceLabel(d.startedAt, now)}: ${d.summary}${who}${where}${board}`);
528
+ }
529
+ for (const b of s.boardInProgress) {
530
+ lines.push(`- In progress on the board: ${b.title} — board item ${b.itemId}${b.boardName ? ` (${b.boardName})` : ""}`);
531
+ }
532
+ for (const b of blocked) {
533
+ lines.push(`- Blocked on the board: ${b.title} — board item ${b.itemId}${b.boardName ? ` (${b.boardName})` : ""}`);
534
+ }
535
+ for (const b of inReview) {
536
+ lines.push(`- Awaiting review on the board: ${b.title} — board item ${b.itemId}${b.boardName ? ` (${b.boardName})` : ""}`);
537
+ }
538
+ for (const p of s.peers) {
539
+ lines.push(`- Parallel work${sinceLabel(p.startedAt, now)}: ${p.redacted ? REDACTED_PURPOSE : p.purpose || "(no stated purpose)"}`);
540
+ }
541
+ if (s.main.live) {
542
+ const busy = s.dispatched.length > 0 || s.peers.length > 0;
543
+ lines.push(`- Main session: live${sinceLabel(s.main.since, now)}${busy ? "" : " — idle apart from this reply"}`);
544
+ } else if (s.main.state === "stale") {
545
+ lines.push("- Main session: stale (stopped beating)");
546
+ } else {
547
+ lines.push(`- Main session: not running${mainAbsentNote ? ` (${mainAbsentNote})` : ""}`);
548
+ }
549
+ for (const b of queued) {
550
+ lines.push(`- Queued on the board: ${b.title} — board item ${b.itemId}${b.col ? ` [${b.col}]` : ""}${b.boardName ? ` (${b.boardName})` : ""}`);
551
+ }
552
+ if (handoffs > 0) {
553
+ lines.push(`- ${handoffs} open handoff${handoffs === 1 ? "" : "s"} waiting on the main session`);
554
+ }
555
+ if (s.interactiveOpen > 0) {
556
+ const n = s.interactiveOpen;
557
+ lines.push(
558
+ `- ${n} interactive session${n === 1 ? "" : "s"} open on this machine${sinceLabel(s.interactiveSince, now)} — you can say it is open; you cannot see what is in it.`,
559
+ );
560
+ }
561
+
562
+ const header = CURRENT_WORK_HEADER;
563
+ const budget = max - 1;
564
+ const body = lines.length > budget ? [...lines.slice(0, budget - 1), `- …and ${lines.length - (budget - 1)} more`] : lines;
565
+ return [header, ...body].join("\n");
566
+ }
567
+
568
+ // ---------------------------------------------------------------------------
569
+ // The reader (I/O; thin)
570
+ // ---------------------------------------------------------------------------
571
+
572
+ function readJson(p) {
573
+ try {
574
+ if (!existsSync(p)) return null;
575
+ return JSON.parse(readFileSync(p, "utf8"));
576
+ } catch {
577
+ return null;
578
+ }
579
+ }
580
+
581
+ /**
582
+ * Read every snapshot under an agent root and summarise. Fail-open; READ-ONLY
583
+ * (presence is listed with `reap:false` so a reader never deletes a record;
584
+ * handoff files are counted, never opened).
585
+ *
586
+ * @param {string} agentRoot
587
+ * @param {{now?:number, staleMs?:number, excludeSessionId?:string, presenceList?:Function, activePath?:string, audience?:object|null}} [o]
588
+ * `activePath` overrides where active.json is read from (the context
589
+ * compiler's test seam points its session dir elsewhere). `audience` is
590
+ * applied through {@link scopeCurrentWorkFor}; ABSENT is `{}` (an audience
591
+ * with no identity, which sees nothing cross-conversation) — the operator's
592
+ * unscoped view must be asked for with an explicit `null`.
593
+ */
594
+ export async function readCurrentWork(agentRoot, o = {}) {
595
+ const root = String(agentRoot || "");
596
+ const sess = join(root, "state", "session");
597
+ let presence = [];
598
+ try {
599
+ const list = o.presenceList || (await import("../collective/presence.mjs")).list;
600
+ presence = list(root, { nowMs: o.now, reap: false }) || [];
601
+ } catch {
602
+ presence = [];
603
+ }
604
+ const summary = summarizeCurrentWork({
605
+ heartbeat: readJson(join(sess, "heartbeat.json")),
606
+ mainSession: readJson(join(sess, "main-session.json")),
607
+ peers: readJson(join(sess, "peers.json")),
608
+ active: readJson(o.activePath || join(root, "state", "sessions", "active.json")),
609
+ presence,
610
+ boardMine: readJson(join(root, "state", "org", "board-mine.json")),
611
+ handoffs: listOpenHandoffs(root),
612
+ now: o.now,
613
+ staleMs: o.staleMs,
614
+ excludeSessionId: o.excludeSessionId,
615
+ });
616
+ return scopeCurrentWorkFor(summary, o.audience === undefined ? {} : o.audience);
617
+ }
618
+
619
+ /**
620
+ * The audience an inbound item's reply is for. PURE. `isPrivate` is decided
621
+ * by lib/context/history-scope's rule (unknown is a room), passed in by the
622
+ * caller so this module stays free of that import's defaults.
623
+ *
624
+ * @param {object} item an inbox item
625
+ * @param {{isPrivate?:boolean, forbidsText?:Function}} [o]
626
+ */
627
+ export function audienceForItem(item, o = {}) {
628
+ const it = item && typeof item === "object" ? item : {};
629
+ return {
630
+ sender: it.sender ? String(it.sender) : "",
631
+ channelId: String(it.cohort_channel_id || it.channel_id || it.channelId || "").trim(),
632
+ channel: it.channel ? String(it.channel) : "",
633
+ isPrivate: o.isPrivate === true,
634
+ ...(typeof o.forbidsText === "function" ? { forbidsText: o.forbidsText } : {}),
635
+ };
636
+ }
637
+
638
+ /**
639
+ * The block for a prompt, straight from disk, scoped to `o.audience` (see
640
+ * {@link readCurrentWork} — absent means "no identity", which discloses no
641
+ * cross-conversation work). "" when there is nothing to say, unless
642
+ * `explicitEmpty` (a roll-call) asks for the header + the "nothing" line.
643
+ * `mainAbsentNote` is passed through to {@link renderCurrentWork}.
644
+ * @param {string} agentRoot
645
+ * @param {{now?:number, max?:number, excludeSessionId?:string, activePath?:string, audience?:object|null, explicitEmpty?:boolean, mainAbsentNote?:string}} [o]
646
+ */
647
+ export async function currentWorkBlock(agentRoot, o = {}) {
648
+ try {
649
+ const s = await readCurrentWork(agentRoot, o);
650
+ return renderCurrentWork(s, { max: o.max, now: o.now, explicitEmpty: o.explicitEmpty, mainAbsentNote: o.mainAbsentNote });
651
+ } catch {
652
+ // A roll-call still gets its "nothing" line: the instruction not to invent
653
+ // must reach the composer even when the read itself failed. (readCurrentWork
654
+ // absorbs a throwing presence lister and unreadable files; what reaches
655
+ // here is a defect further in — a poisoned record, say — and the answer
656
+ // to a roll-call is still "say nothing is known", not silence.)
657
+ return o.explicitEmpty === true ? [CURRENT_WORK_HEADER, CURRENT_WORK_EMPTY_LINE].join("\n") : "";
658
+ }
659
+ }
660
+
661
+ export default {
662
+ CURRENT_WORK_MAX_LINES,
663
+ CURRENT_WORK_HEADER,
664
+ CURRENT_WORK_EMPTY_LINE,
665
+ REDACTED_WORK,
666
+ REDACTED_PURPOSE,
667
+ boardItemRefFor,
668
+ activeEntryFor,
669
+ linkBoardTask,
670
+ summarizeCurrentWork,
671
+ scopeCurrentWorkFor,
672
+ audienceForItem,
673
+ renderCurrentWork,
674
+ readCurrentWork,
675
+ currentWorkBlock,
676
+ };