@ouro.bot/cli 0.1.0-alpha.9 → 0.1.0-alpha.900

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 (712) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +249 -176
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/SerpentGuide.ouro/agent.json +83 -0
  11. package/SerpentGuide.ouro/psyche/SOUL.md +25 -0
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  13. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  14. package/assets/bluebubbles-host +264 -0
  15. package/assets/ouroboros.png +0 -0
  16. package/assets/sanctuary-host-launcher.sh +16 -0
  17. package/changelog.json +6224 -0
  18. package/deploy/unraid/Dockerfile +58 -0
  19. package/deploy/unraid/README.txt +2997 -0
  20. package/deploy/unraid/audit-container-spec.sh +4 -0
  21. package/deploy/unraid/container-runtime.json +1 -0
  22. package/deploy/unraid/docker-man-template-transaction.mjs +711 -0
  23. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  24. package/deploy/unraid/migrate-sanctuary-bundle.mjs +60 -0
  25. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  26. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  27. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  28. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  29. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  30. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  31. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  32. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  33. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  34. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  35. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1254 -0
  36. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  37. package/deploy/unraid/sanctuary-replay-gate.mjs +1614 -0
  38. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  39. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2086 -0
  40. package/deploy/unraid/sanctuary-unit16-run.sh +560 -0
  41. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  42. package/deploy/unraid/sanctuary.ouro/agent.json +66 -0
  43. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  44. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  45. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  46. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  47. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2231 -0
  48. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  49. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  50. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +5 -0
  51. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +27 -0
  52. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +27 -0
  53. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +22 -0
  54. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  55. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +232 -0
  56. package/deploy/unraid/sanctuary.xml +30 -0
  57. package/dist/a2a/card.js +57 -0
  58. package/dist/a2a/client.js +250 -0
  59. package/dist/a2a/config.js +50 -0
  60. package/dist/a2a/delegated-command-grants.js +93 -0
  61. package/dist/a2a/delegated-command.js +197 -0
  62. package/dist/a2a/delegation-stores.js +56 -0
  63. package/dist/a2a/did-resolution.js +93 -0
  64. package/dist/a2a/escalation-grants.js +84 -0
  65. package/dist/a2a/escalation-wiring.js +60 -0
  66. package/dist/a2a/identity.js +258 -0
  67. package/dist/a2a/inbound-share.js +110 -0
  68. package/dist/a2a/mission-result-wire.js +196 -0
  69. package/dist/a2a/onboarding.js +133 -0
  70. package/dist/a2a/operator-trust.js +382 -0
  71. package/dist/a2a/outbox-client.js +57 -0
  72. package/dist/a2a/outbox-store.js +188 -0
  73. package/dist/a2a/outbox-wire.js +95 -0
  74. package/dist/a2a/pin-store.js +132 -0
  75. package/dist/a2a/replay-grant-holders.js +33 -0
  76. package/dist/a2a/replay-harness.js +188 -0
  77. package/dist/a2a/resolution-proof.js +53 -0
  78. package/dist/a2a/sealed-chat.js +113 -0
  79. package/dist/a2a/seen-ledger.js +120 -0
  80. package/dist/a2a/server.js +771 -0
  81. package/dist/a2a/task-store.js +69 -0
  82. package/dist/a2a/transport.js +45 -0
  83. package/dist/a2a/trust-commands.js +203 -0
  84. package/dist/a2a/trusted-files.js +185 -0
  85. package/dist/a2a/types.js +3 -0
  86. package/dist/arc/attention-types.js +8 -0
  87. package/dist/arc/cares.js +360 -0
  88. package/dist/arc/episodes.js +118 -0
  89. package/dist/arc/evolution.js +490 -0
  90. package/dist/arc/flight-recorder.js +1034 -0
  91. package/dist/arc/intentions.js +134 -0
  92. package/dist/arc/json-store.js +117 -0
  93. package/dist/arc/obligations.js +386 -0
  94. package/dist/arc/packets.js +336 -0
  95. package/dist/arc/presence.js +185 -0
  96. package/dist/arc/task-lifecycle.js +57 -0
  97. package/dist/commerce/store.js +755 -0
  98. package/dist/commerce/types.js +3 -0
  99. package/dist/heart/active-work.js +1009 -0
  100. package/dist/heart/agent-entry.js +252 -3
  101. package/dist/heart/approval-files.js +113 -0
  102. package/dist/heart/approval-store.js +960 -0
  103. package/dist/heart/attachments/image-normalize.js +194 -0
  104. package/dist/heart/attachments/materialize.js +97 -0
  105. package/dist/heart/attachments/originals.js +88 -0
  106. package/dist/heart/attachments/render.js +29 -0
  107. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  108. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  109. package/dist/heart/attachments/sources/index.js +18 -0
  110. package/dist/heart/attachments/sources/telegram.js +71 -0
  111. package/dist/heart/attachments/store.js +132 -0
  112. package/dist/heart/attachments/types.js +93 -0
  113. package/dist/heart/auth/auth-flow.js +495 -0
  114. package/dist/heart/autonomy-budget.js +478 -0
  115. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  116. package/dist/heart/awaiting/await-alert.js +152 -0
  117. package/dist/heart/awaiting/await-expiry.js +143 -0
  118. package/dist/heart/awaiting/await-loader.js +91 -0
  119. package/dist/heart/awaiting/await-parser.js +152 -0
  120. package/dist/heart/awaiting/await-runtime-state.js +111 -0
  121. package/dist/heart/awaiting/await-scheduler.js +391 -0
  122. package/dist/heart/background-operations.js +281 -0
  123. package/dist/heart/bridges/manager.js +478 -0
  124. package/dist/heart/bridges/state-machine.js +135 -0
  125. package/dist/heart/bridges/store.js +135 -0
  126. package/dist/heart/bundle-state.js +168 -0
  127. package/dist/heart/commitments.js +135 -0
  128. package/dist/heart/config-registry.js +331 -0
  129. package/dist/heart/config.js +225 -137
  130. package/dist/heart/context-loss-gauntlet.js +387 -0
  131. package/dist/heart/context-loss-sentinel.js +1157 -0
  132. package/dist/heart/core.js +2442 -343
  133. package/dist/heart/cross-chat-delivery.js +133 -0
  134. package/dist/heart/daemon/agent-config-check.js +451 -0
  135. package/dist/heart/daemon/agent-discovery.js +355 -0
  136. package/dist/heart/daemon/agent-home.js +319 -0
  137. package/dist/heart/daemon/agent-service.js +542 -0
  138. package/dist/heart/daemon/agentic-repair.js +547 -0
  139. package/dist/heart/daemon/await-private-wake.js +59 -0
  140. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  141. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  142. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  143. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  144. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  145. package/dist/heart/daemon/cadence.js +180 -0
  146. package/dist/heart/daemon/cli-defaults.js +859 -0
  147. package/dist/heart/daemon/cli-desk.js +322 -0
  148. package/dist/heart/daemon/cli-exec.js +9003 -0
  149. package/dist/heart/daemon/cli-help.js +729 -0
  150. package/dist/heart/daemon/cli-parse.js +3140 -0
  151. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  152. package/dist/heart/daemon/cli-render.js +804 -0
  153. package/dist/heart/daemon/cli-types.js +8 -0
  154. package/dist/heart/daemon/connect-bay.js +323 -0
  155. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  156. package/dist/heart/daemon/container-healthcheck.js +112 -0
  157. package/dist/heart/daemon/container-runtime.js +97 -0
  158. package/dist/heart/daemon/container-spec-auditor-main.js +171 -0
  159. package/dist/heart/daemon/container-spec-auditor.js +235 -0
  160. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  161. package/dist/heart/daemon/daemon-cli.js +30 -882
  162. package/dist/heart/daemon/daemon-entry.js +1002 -13
  163. package/dist/heart/daemon/daemon-health.js +186 -0
  164. package/dist/heart/daemon/daemon-rollup.js +57 -0
  165. package/dist/heart/daemon/daemon-runtime-sync.js +287 -0
  166. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  167. package/dist/heart/daemon/daemon.js +2213 -28
  168. package/dist/heart/daemon/dns-workflow.js +394 -0
  169. package/dist/heart/daemon/doctor-types.js +8 -0
  170. package/dist/heart/daemon/doctor.js +1755 -0
  171. package/dist/heart/daemon/freshness.js +345 -0
  172. package/dist/heart/daemon/habit-private-wake.js +61 -0
  173. package/dist/heart/daemon/health-monitor.js +142 -11
  174. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  175. package/dist/heart/daemon/hooks/bundle-meta.js +226 -0
  176. package/dist/heart/daemon/http-health-probe.js +80 -0
  177. package/dist/heart/daemon/human-command-screens.js +234 -0
  178. package/dist/heart/daemon/human-readiness.js +114 -0
  179. package/dist/heart/daemon/inner-status.js +78 -0
  180. package/dist/heart/daemon/interactive-repair.js +394 -0
  181. package/dist/heart/daemon/launchd.js +188 -0
  182. package/dist/heart/daemon/log-tailer.js +82 -12
  183. package/dist/heart/daemon/logs-prune.js +132 -0
  184. package/dist/heart/daemon/mcp-canary.js +524 -0
  185. package/dist/heart/daemon/message-router.js +80 -11
  186. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  187. package/dist/heart/daemon/os-cron-deps.js +135 -0
  188. package/dist/heart/daemon/os-cron.js +22 -14
  189. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  190. package/dist/heart/daemon/ouro-entry.js +3 -1
  191. package/dist/heart/daemon/plugin-cli.js +432 -0
  192. package/dist/heart/daemon/process-manager.js +766 -54
  193. package/dist/heart/daemon/provider-discovery.js +137 -0
  194. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  195. package/dist/heart/daemon/prunable-bundle.js +144 -0
  196. package/dist/heart/daemon/pulse.js +511 -0
  197. package/dist/heart/daemon/readiness-repair.js +365 -0
  198. package/dist/heart/daemon/run-hooks.js +39 -0
  199. package/dist/heart/daemon/runtime-logging.js +92 -16
  200. package/dist/heart/daemon/runtime-metadata.js +191 -0
  201. package/dist/{repertoire/tasks/lifecycle.js → heart/daemon/runtime-mode.js} +37 -39
  202. package/dist/heart/daemon/safe-mode.js +161 -0
  203. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2654 -0
  204. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1830 -0
  205. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  206. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +955 -0
  207. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  208. package/dist/heart/daemon/sanctuary-authority-epoch.js +281 -0
  209. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  210. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  211. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1267 -0
  212. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  213. package/dist/heart/daemon/sanctuary-bundle-migration.js +730 -0
  214. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  215. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  216. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  217. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  218. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +207 -0
  219. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  220. package/dist/heart/daemon/sanctuary-package-management.js +103 -0
  221. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  222. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  223. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +475 -0
  224. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +585 -0
  225. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +676 -0
  226. package/dist/heart/daemon/sense-manager.js +975 -0
  227. package/dist/heart/daemon/session-id-resolver.js +131 -0
  228. package/dist/heart/daemon/skill-management-installer.js +94 -0
  229. package/dist/heart/daemon/socket-client.js +370 -0
  230. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  231. package/dist/heart/daemon/startup-tui.js +339 -0
  232. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  233. package/dist/heart/daemon/task-scheduler.js +117 -39
  234. package/dist/heart/daemon/terminal-ui.js +499 -0
  235. package/dist/heart/daemon/thoughts.js +591 -0
  236. package/dist/heart/daemon/up-progress.js +366 -0
  237. package/dist/heart/daemon/vault-items.js +56 -0
  238. package/dist/heart/delegation.js +59 -0
  239. package/dist/heart/external-events/router.js +1516 -0
  240. package/dist/heart/failure-reports.js +335 -0
  241. package/dist/heart/file-lock.js +109 -0
  242. package/dist/heart/frontend-approval-runtime.js +506 -0
  243. package/dist/heart/frontend-journal.js +215 -0
  244. package/dist/heart/frontend-session-service.js +237 -0
  245. package/dist/heart/frontend-socket-client.js +164 -0
  246. package/dist/heart/frontend-socket.js +400 -0
  247. package/dist/heart/habits/habit-cancel.js +810 -0
  248. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  249. package/dist/heart/habits/habit-migration.js +194 -0
  250. package/dist/heart/habits/habit-parser.js +278 -0
  251. package/dist/heart/habits/habit-runtime-state.js +93 -0
  252. package/dist/heart/habits/habit-scheduler.js +653 -0
  253. package/dist/heart/habits/habit-session-summary.js +318 -0
  254. package/dist/heart/habits/habit-session.js +636 -0
  255. package/dist/heart/{daemon → hatch}/hatch-animation.js +10 -3
  256. package/dist/heart/{daemon → hatch}/hatch-flow.js +57 -139
  257. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  258. package/dist/heart/hatch/specialist-orchestrator.js +129 -0
  259. package/dist/heart/hatch/specialist-prompt.js +102 -0
  260. package/dist/heart/hatch/specialist-tools.js +318 -0
  261. package/dist/heart/identity.js +312 -67
  262. package/dist/heart/kept-notes.js +289 -0
  263. package/dist/heart/kicks.js +2 -20
  264. package/dist/heart/machine-identity.js +175 -0
  265. package/dist/heart/mail-import-discovery.js +356 -0
  266. package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
  267. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  268. package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
  269. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  270. package/dist/heart/mailbox/mailbox-http-transport.js +272 -0
  271. package/dist/heart/mailbox/mailbox-http.js +99 -0
  272. package/dist/heart/mailbox/mailbox-read.js +39 -0
  273. package/dist/heart/mailbox/mailbox-types.js +27 -0
  274. package/dist/heart/mailbox/mailbox-view.js +197 -0
  275. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  276. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  277. package/dist/heart/mailbox/readers/mail.js +375 -0
  278. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  279. package/dist/heart/mailbox/readers/sessions.js +231 -0
  280. package/dist/heart/mailbox/readers/shared.js +111 -0
  281. package/dist/heart/mcp/mcp-server.js +696 -0
  282. package/dist/heart/migrate-config.js +100 -0
  283. package/dist/heart/model-capabilities.js +59 -0
  284. package/dist/heart/orientation-frame.js +345 -0
  285. package/dist/heart/platform.js +81 -0
  286. package/dist/heart/primitives.js +1 -1
  287. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  288. package/dist/heart/private-runtime/index.js +18 -0
  289. package/dist/heart/private-runtime/ledger.js +221 -0
  290. package/dist/heart/private-runtime/policy.js +260 -0
  291. package/dist/heart/private-runtime/types.js +2 -0
  292. package/dist/heart/progress-story.js +42 -0
  293. package/dist/heart/provider-attempt.js +137 -0
  294. package/dist/heart/provider-binding-resolver.js +273 -0
  295. package/dist/heart/provider-credentials.js +449 -0
  296. package/dist/heart/provider-failover.js +311 -0
  297. package/dist/heart/provider-models.js +96 -0
  298. package/dist/heart/provider-ping.js +265 -0
  299. package/dist/heart/provider-readiness-cache.js +119 -0
  300. package/dist/heart/provider-visibility.js +188 -0
  301. package/dist/heart/providers/anthropic-token.js +131 -0
  302. package/dist/heart/providers/anthropic.js +236 -58
  303. package/dist/heart/providers/azure.js +104 -13
  304. package/dist/heart/providers/error-classification.js +127 -0
  305. package/dist/heart/providers/github-copilot.js +145 -0
  306. package/dist/heart/providers/minimax-vlm.js +189 -0
  307. package/dist/heart/providers/minimax.js +29 -7
  308. package/dist/heart/providers/openai-codex-token.js +349 -0
  309. package/dist/heart/providers/openai-codex.js +63 -39
  310. package/dist/heart/providers/openai-compatible.js +177 -0
  311. package/dist/heart/reply-style.js +56 -0
  312. package/dist/heart/run-ledger.js +247 -0
  313. package/dist/heart/runtime-capability-check.js +170 -0
  314. package/dist/heart/runtime-credentials.js +607 -0
  315. package/dist/heart/runtime-cwd.js +87 -0
  316. package/dist/heart/sense-truth.js +81 -0
  317. package/dist/heart/session-activity.js +237 -0
  318. package/dist/heart/session-events.js +1504 -0
  319. package/dist/heart/session-playback-cli-main.js +5 -0
  320. package/dist/heart/session-playback-cli.js +36 -0
  321. package/dist/heart/session-playback.js +231 -0
  322. package/dist/heart/session-redaction-repair-cli-main.js +31 -0
  323. package/dist/heart/session-redaction-repair.js +552 -0
  324. package/dist/heart/session-stats-cli-main.js +5 -0
  325. package/dist/heart/session-stats.js +183 -0
  326. package/dist/heart/session-transcript.js +133 -0
  327. package/dist/heart/shepherd-config.js +113 -0
  328. package/dist/heart/source-grounding.js +283 -0
  329. package/dist/heart/start-of-turn-packet.js +372 -0
  330. package/dist/heart/steward-policy.js +656 -0
  331. package/dist/heart/streaming.js +682 -207
  332. package/dist/heart/structured-output.js +196 -0
  333. package/dist/heart/sync-classification.js +176 -0
  334. package/dist/heart/sync.js +505 -0
  335. package/dist/heart/target-resolution.js +127 -0
  336. package/dist/heart/tempo.js +93 -0
  337. package/dist/heart/temporal-view.js +41 -0
  338. package/dist/heart/timeouts.js +101 -0
  339. package/dist/heart/tool-activity-callbacks.js +59 -0
  340. package/dist/heart/tool-approval.js +382 -0
  341. package/dist/heart/tool-description.js +155 -0
  342. package/dist/heart/tool-friction.js +55 -0
  343. package/dist/heart/tool-loop.js +206 -0
  344. package/dist/heart/turn-context.js +494 -0
  345. package/dist/heart/turn-coordinator.js +28 -0
  346. package/dist/heart/turn-execution-lease.js +30 -0
  347. package/dist/heart/versioning/ouro-bot-global-installer.js +129 -0
  348. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  349. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  350. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  351. package/dist/heart/{daemon → versioning}/ouro-uti.js +11 -2
  352. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  353. package/dist/heart/versioning/staged-restart.js +146 -0
  354. package/dist/heart/versioning/update-checker.js +116 -0
  355. package/dist/heart/versioning/update-hooks.js +154 -0
  356. package/dist/heart/versioning/version-intent.js +114 -0
  357. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  358. package/dist/heart/work-card.js +380 -0
  359. package/dist/mailbox-ui/assets/index-Cyv4mw3Y.js +1 -0
  360. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  361. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  362. package/dist/mailbox-ui/index.html +16 -0
  363. package/dist/mailroom/attention.js +167 -0
  364. package/dist/mailroom/autonomy.js +209 -0
  365. package/dist/mailroom/blob-store.js +889 -0
  366. package/dist/mailroom/body-cache.js +61 -0
  367. package/dist/mailroom/cache-sync-cli.js +58 -0
  368. package/dist/mailroom/core.js +803 -0
  369. package/dist/mailroom/entry.js +160 -0
  370. package/dist/mailroom/file-store.js +568 -0
  371. package/dist/mailroom/hosted-cache-sync.js +384 -0
  372. package/dist/mailroom/mbox-import.js +393 -0
  373. package/dist/mailroom/migration.js +164 -0
  374. package/dist/mailroom/outbound.js +380 -0
  375. package/dist/mailroom/policy.js +263 -0
  376. package/dist/mailroom/reader.js +292 -0
  377. package/dist/mailroom/search-cache.js +513 -0
  378. package/dist/mailroom/search-relevance.js +319 -0
  379. package/dist/mailroom/smtp-ingress.js +176 -0
  380. package/dist/mailroom/source-state.js +176 -0
  381. package/dist/mailroom/thread.js +109 -0
  382. package/dist/mailroom/travel-extract.js +89 -0
  383. package/dist/mind/bundle-manifest.js +93 -1
  384. package/dist/mind/context.js +318 -104
  385. package/dist/mind/desk-section.js +362 -0
  386. package/dist/mind/diary-integrity.js +60 -0
  387. package/dist/mind/{memory.js → diary.js} +90 -98
  388. package/dist/mind/embedding-provider.js +60 -0
  389. package/dist/mind/file-state.js +179 -0
  390. package/dist/mind/first-impressions.js +16 -2
  391. package/dist/mind/{associative-recall.js → note-search.js} +61 -60
  392. package/dist/mind/obligation-steering.js +227 -0
  393. package/dist/mind/pending.js +103 -10
  394. package/dist/mind/phrases.js +1 -0
  395. package/dist/mind/prompt-budget.js +479 -0
  396. package/dist/mind/prompt-refresh.js +3 -2
  397. package/dist/mind/prompt.js +1417 -140
  398. package/dist/mind/provenance-trust.js +26 -0
  399. package/dist/mind/record-paths.js +312 -0
  400. package/dist/mind/scrutiny.js +173 -0
  401. package/dist/mind/session-transaction.js +564 -0
  402. package/dist/mind/token-estimate.js +8 -12
  403. package/dist/nerves/cli-logging.js +22 -3
  404. package/dist/nerves/coverage/audit-rules.js +15 -6
  405. package/dist/nerves/coverage/audit.js +28 -2
  406. package/dist/nerves/coverage/cli.js +1 -1
  407. package/dist/nerves/coverage/contract.js +5 -5
  408. package/dist/nerves/coverage/file-completeness.js +139 -5
  409. package/dist/nerves/coverage/run-artifacts.js +56 -36
  410. package/dist/nerves/coverage/source-scanner.js +4 -4
  411. package/dist/nerves/event-buffer.js +111 -0
  412. package/dist/nerves/index.js +305 -9
  413. package/dist/nerves/observation.js +20 -0
  414. package/dist/nerves/redact.js +79 -0
  415. package/dist/nerves/review/cli-main.js +5 -0
  416. package/dist/nerves/review/cli.js +156 -0
  417. package/dist/nerves/review/core.js +159 -0
  418. package/dist/nerves/runtime.js +17 -1
  419. package/dist/repertoire/ado-client.js +17 -56
  420. package/dist/repertoire/ado-semantic.js +16 -10
  421. package/dist/repertoire/api-client.js +97 -0
  422. package/dist/repertoire/bitwarden-store.js +1191 -0
  423. package/dist/repertoire/bundle-templates.js +71 -0
  424. package/dist/repertoire/bw-installer.js +180 -0
  425. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  426. package/dist/repertoire/coding/context-pack.js +331 -0
  427. package/dist/repertoire/coding/feedback.js +322 -0
  428. package/dist/repertoire/coding/index.js +18 -3
  429. package/dist/repertoire/coding/manager.js +228 -14
  430. package/dist/repertoire/coding/spawner.js +61 -14
  431. package/dist/repertoire/coding/tools.js +279 -12
  432. package/dist/repertoire/coding/workbench-client.js +272 -0
  433. package/dist/repertoire/coding/workbench-manager.js +346 -0
  434. package/dist/repertoire/commerce-errors.js +109 -0
  435. package/dist/repertoire/commerce-self-test.js +156 -0
  436. package/dist/repertoire/credential-access.js +182 -0
  437. package/dist/repertoire/data/ado-endpoints.json +188 -0
  438. package/dist/repertoire/desk/classifier.js +362 -0
  439. package/dist/repertoire/duffel-client.js +185 -0
  440. package/dist/repertoire/github-client.js +14 -55
  441. package/dist/repertoire/graph-client.js +11 -52
  442. package/dist/repertoire/guardrails.js +1232 -0
  443. package/dist/repertoire/house-sweep.js +469 -0
  444. package/dist/repertoire/mcp-client.js +307 -0
  445. package/dist/repertoire/mcp-manager.js +483 -0
  446. package/dist/repertoire/mcp-tools.js +132 -0
  447. package/dist/repertoire/mcp-write-guard.js +46 -0
  448. package/dist/repertoire/plugin-mcp.js +175 -0
  449. package/dist/repertoire/plugins.js +253 -0
  450. package/dist/repertoire/relationship-authorization.js +322 -0
  451. package/dist/repertoire/sanctuary-container-policy.js +46 -0
  452. package/dist/repertoire/shell-sessions.js +134 -0
  453. package/dist/repertoire/skills.js +45 -24
  454. package/dist/repertoire/stripe-client.js +131 -0
  455. package/dist/repertoire/tool-arguments.js +182 -0
  456. package/dist/repertoire/tool-results.js +29 -0
  457. package/dist/repertoire/tools-a2a.js +699 -0
  458. package/dist/repertoire/tools-attachments.js +322 -0
  459. package/dist/repertoire/tools-awaiting.js +870 -0
  460. package/dist/repertoire/tools-base.js +84 -706
  461. package/dist/repertoire/tools-bluebubbles.js +95 -0
  462. package/dist/repertoire/tools-bridge.js +144 -0
  463. package/dist/repertoire/tools-bundle.js +993 -0
  464. package/dist/repertoire/tools-commerce.js +253 -0
  465. package/dist/repertoire/tools-config.js +186 -0
  466. package/dist/repertoire/tools-continuity.js +575 -0
  467. package/dist/repertoire/tools-credential.js +383 -0
  468. package/dist/repertoire/tools-escalation.js +84 -0
  469. package/dist/repertoire/tools-evolution.js +527 -0
  470. package/dist/repertoire/tools-files.js +344 -0
  471. package/dist/repertoire/tools-flight.js +290 -0
  472. package/dist/repertoire/tools-flow.js +119 -0
  473. package/dist/repertoire/tools-github.js +3 -8
  474. package/dist/repertoire/tools-habits.js +103 -0
  475. package/dist/repertoire/tools-house-care.js +174 -0
  476. package/dist/repertoire/tools-mail.js +1828 -0
  477. package/dist/repertoire/tools-notes.js +496 -0
  478. package/dist/repertoire/tools-obligations.js +182 -0
  479. package/dist/repertoire/tools-orientation.js +31 -0
  480. package/dist/repertoire/tools-record.js +482 -0
  481. package/dist/repertoire/tools-rsvp.js +139 -0
  482. package/dist/repertoire/tools-runtime.js +238 -0
  483. package/dist/repertoire/tools-sanctuary-host.js +202 -0
  484. package/dist/repertoire/tools-session.js +1133 -0
  485. package/dist/repertoire/tools-shell.js +149 -0
  486. package/dist/repertoire/tools-shepherd.js +180 -0
  487. package/dist/repertoire/tools-steward-policy.js +147 -0
  488. package/dist/repertoire/tools-stripe.js +224 -0
  489. package/dist/repertoire/tools-surface.js +369 -0
  490. package/dist/repertoire/tools-teams.js +67 -61
  491. package/dist/repertoire/tools-telegram-contacts.js +37 -0
  492. package/dist/repertoire/tools-travel.js +125 -0
  493. package/dist/repertoire/tools-trip.js +982 -0
  494. package/dist/repertoire/tools-unraid.js +556 -0
  495. package/dist/repertoire/tools-user-profile.js +146 -0
  496. package/dist/repertoire/tools-vault.js +40 -0
  497. package/dist/repertoire/tools-voice-local.js +198 -0
  498. package/dist/repertoire/tools-voice.js +145 -0
  499. package/dist/repertoire/tools.js +534 -123
  500. package/dist/repertoire/travel-api-client.js +360 -0
  501. package/dist/repertoire/unraid-client.js +155 -0
  502. package/dist/repertoire/unraid-restart.js +339 -0
  503. package/dist/repertoire/user-profile.js +131 -0
  504. package/dist/repertoire/vault-setup.js +246 -0
  505. package/dist/repertoire/vault-unlock.js +686 -0
  506. package/dist/rsvp/aisleplanner-client.js +354 -0
  507. package/dist/rsvp/cli.js +926 -0
  508. package/dist/rsvp/config.js +327 -0
  509. package/dist/rsvp/cutover.js +433 -0
  510. package/dist/rsvp/diagnostics.js +232 -0
  511. package/dist/rsvp/diff-renderer.js +176 -0
  512. package/dist/rsvp/habit-policy.js +110 -0
  513. package/dist/rsvp/habit-stage.js +123 -0
  514. package/dist/rsvp/incident-bundle.js +97 -0
  515. package/dist/rsvp/migration.js +204 -0
  516. package/dist/rsvp/native-habit-runner.js +630 -0
  517. package/dist/rsvp/outbound-state.js +628 -0
  518. package/dist/rsvp/query.js +118 -0
  519. package/dist/rsvp/replay.js +233 -0
  520. package/dist/rsvp/snapshot.js +232 -0
  521. package/dist/rsvp/spend-ledger.js +175 -0
  522. package/dist/scripts/claude-code-hook.js +41 -0
  523. package/dist/scripts/claude-code-stop-hook.js +47 -0
  524. package/dist/senses/a2a-entry.js +132 -0
  525. package/dist/senses/acp-server.js +386 -0
  526. package/dist/senses/attention-queue.js +186 -0
  527. package/dist/senses/await-turn-message.js +65 -0
  528. package/dist/senses/bluebubbles/active-turns.js +216 -0
  529. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  530. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  531. package/dist/senses/bluebubbles/client.js +799 -0
  532. package/dist/senses/bluebubbles/context-packet.js +207 -0
  533. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  534. package/dist/senses/bluebubbles/entry.js +90 -0
  535. package/dist/senses/bluebubbles/inbound-log.js +127 -0
  536. package/dist/senses/bluebubbles/index.js +3841 -0
  537. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  538. package/dist/senses/bluebubbles/media.js +389 -0
  539. package/dist/senses/bluebubbles/model.js +392 -0
  540. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +57 -6
  541. package/dist/senses/bluebubbles/outbound-state.js +308 -0
  542. package/dist/senses/bluebubbles/processed-log.js +133 -0
  543. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  544. package/dist/senses/bluebubbles/replay.js +284 -0
  545. package/dist/senses/bluebubbles/runtime-state.js +137 -0
  546. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  547. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  548. package/dist/senses/bluebubbles/webhook-registration.js +228 -0
  549. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  550. package/dist/senses/cli/bracketed-paste.js +82 -0
  551. package/dist/senses/cli/image-paste.js +287 -0
  552. package/dist/senses/cli/image-ref-navigation.js +75 -0
  553. package/dist/senses/cli/ink-app.js +156 -0
  554. package/dist/senses/cli/inline-diff.js +64 -0
  555. package/dist/senses/cli/input-keys.js +174 -0
  556. package/dist/senses/cli/kill-ring.js +86 -0
  557. package/dist/senses/cli/message-list.js +51 -0
  558. package/dist/senses/cli/ouro-tui.js +607 -0
  559. package/dist/senses/cli/spinner-imperative.js +135 -0
  560. package/dist/senses/cli/spinner.js +101 -0
  561. package/dist/senses/cli/status-line.js +60 -0
  562. package/dist/senses/cli/streaming-markdown.js +526 -0
  563. package/dist/senses/cli/tool-display.js +85 -0
  564. package/dist/senses/cli/tool-render.js +85 -0
  565. package/dist/senses/cli/tui-store.js +241 -0
  566. package/dist/senses/cli/virtual-list.js +35 -0
  567. package/dist/senses/cli-entry.js +60 -8
  568. package/dist/senses/cli-layout.js +187 -0
  569. package/dist/senses/cli.js +814 -281
  570. package/dist/senses/commands.js +66 -3
  571. package/dist/senses/context-packet-ledger.js +371 -0
  572. package/dist/senses/context-packets.js +154 -0
  573. package/dist/senses/continuity.js +94 -0
  574. package/dist/senses/habit-lifecycle-guard.js +24 -0
  575. package/dist/senses/habit-turn-message.js +160 -0
  576. package/dist/senses/ingress-evidence.js +2 -0
  577. package/dist/senses/mail-entry.js +66 -0
  578. package/dist/senses/mail.js +524 -0
  579. package/dist/senses/pipeline.js +1236 -0
  580. package/dist/senses/private-runtime-worker.js +859 -0
  581. package/dist/senses/private-runtime.js +1627 -0
  582. package/dist/senses/proactive-content-guard.js +51 -0
  583. package/dist/senses/root-host-approval-port.js +345 -0
  584. package/dist/senses/root-host-approval-runtime.js +393 -0
  585. package/dist/senses/sanctuary-authority-resident.js +102 -0
  586. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  587. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  588. package/dist/senses/sanctuary-grounding.js +118 -0
  589. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  590. package/dist/senses/sanctuary-health-acceptance-probe.js +774 -0
  591. package/dist/senses/sanctuary-health-runner.js +104 -0
  592. package/dist/senses/sanctuary-health.js +422 -0
  593. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  594. package/dist/senses/sanctuary-interactive-control.js +410 -0
  595. package/dist/senses/sanctuary-media-catalog-contract.js +297 -0
  596. package/dist/senses/sanctuary-media-optimization.js +514 -0
  597. package/dist/senses/sanctuary-runtime.js +369 -0
  598. package/dist/senses/sanctuary-sab.js +85 -0
  599. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  600. package/dist/senses/shared-turn.js +793 -0
  601. package/dist/senses/shepherd/client.js +196 -0
  602. package/dist/senses/shepherd/cmux.js +332 -0
  603. package/dist/senses/shepherd/herdr.js +311 -0
  604. package/dist/senses/shepherd/host.js +14 -0
  605. package/dist/senses/shepherd/judge.js +98 -0
  606. package/dist/senses/shepherd/redact.js +37 -0
  607. package/dist/senses/shepherd/returns.js +79 -0
  608. package/dist/senses/shepherd/sense.js +288 -0
  609. package/dist/senses/shepherd-entry.js +78 -0
  610. package/dist/senses/surface-tool.js +109 -0
  611. package/dist/senses/teams-entry.js +60 -8
  612. package/dist/senses/teams.js +956 -211
  613. package/dist/senses/telegram-admission.js +718 -0
  614. package/dist/senses/telegram-approval-runtime.js +793 -0
  615. package/dist/senses/telegram-attachments.js +186 -0
  616. package/dist/senses/telegram-audit-ledger.js +220 -0
  617. package/dist/senses/telegram-authority-transport.js +231 -0
  618. package/dist/senses/telegram-client.js +1749 -0
  619. package/dist/senses/telegram-effect-adapter.js +900 -0
  620. package/dist/senses/telegram-entry.js +83 -0
  621. package/dist/senses/telegram.js +2351 -0
  622. package/dist/senses/trust-gate.js +207 -2
  623. package/dist/senses/voice/audio-playback.js +237 -0
  624. package/dist/senses/voice/audio-routing.js +119 -0
  625. package/dist/senses/voice/call-auth.js +250 -0
  626. package/dist/senses/voice/elevenlabs.js +202 -0
  627. package/dist/senses/voice/floor-control.js +431 -0
  628. package/dist/senses/voice/floor-controller.js +115 -0
  629. package/dist/senses/voice/golden-path.js +116 -0
  630. package/dist/senses/voice/index.js +29 -0
  631. package/dist/senses/voice/local-audio-control.js +344 -0
  632. package/dist/senses/voice/local-audio-devices.js +516 -0
  633. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  634. package/dist/senses/voice/local-audio-identity.js +103 -0
  635. package/dist/senses/voice/local-audio-join.js +325 -0
  636. package/dist/senses/voice/local-audio-mute.js +199 -0
  637. package/dist/senses/voice/local-audio-notify.js +121 -0
  638. package/dist/senses/voice/local-audio-prompts.js +116 -0
  639. package/dist/senses/voice/local-audio-transport.js +427 -0
  640. package/dist/senses/voice/local-audio.js +281 -0
  641. package/dist/senses/voice/local-media-stream.js +145 -0
  642. package/dist/senses/voice/meeting.js +113 -0
  643. package/dist/senses/voice/outbound.js +190 -0
  644. package/dist/senses/voice/phone.js +33 -0
  645. package/dist/senses/voice/playback.js +139 -0
  646. package/dist/senses/voice/process-guards.js +51 -0
  647. package/dist/senses/voice/realtime-eval.js +496 -0
  648. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  649. package/dist/senses/voice/realtime-trace.js +531 -0
  650. package/dist/senses/voice/transcript.js +70 -0
  651. package/dist/senses/voice/turn.js +191 -0
  652. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  653. package/dist/senses/voice/twilio-phone.js +5454 -0
  654. package/dist/senses/voice/types.js +2 -0
  655. package/dist/senses/voice/whisper.js +161 -0
  656. package/dist/senses/voice-entry.js +83 -0
  657. package/dist/senses/voice-realtime-eval-command.js +99 -0
  658. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  659. package/dist/senses/voice-twilio-entry.js +87 -0
  660. package/dist/trips/core.js +138 -0
  661. package/dist/trips/store.js +265 -0
  662. package/dist/util/frontmatter.js +69 -0
  663. package/npm-shrinkwrap.json +8100 -0
  664. package/package.json +83 -12
  665. package/skills/agent-commerce.md +113 -0
  666. package/skills/browser-navigation.md +117 -0
  667. package/skills/commerce-setup-guide.md +116 -0
  668. package/skills/commerce-setup.md +84 -0
  669. package/skills/configure-dev-tools.md +99 -0
  670. package/skills/travel-planning.md +138 -0
  671. package/AdoptionSpecialist.ouro/agent.json +0 -20
  672. package/AdoptionSpecialist.ouro/psyche/SOUL.md +0 -22
  673. package/dist/heart/daemon/specialist-orchestrator.js +0 -160
  674. package/dist/heart/daemon/specialist-prompt.js +0 -47
  675. package/dist/heart/daemon/specialist-session.js +0 -142
  676. package/dist/heart/daemon/specialist-tools.js +0 -132
  677. package/dist/heart/daemon/subagent-installer.js +0 -125
  678. package/dist/inner-worker-entry.js +0 -4
  679. package/dist/mind/friends/channel.js +0 -49
  680. package/dist/mind/friends/resolver.js +0 -84
  681. package/dist/mind/friends/store-file.js +0 -171
  682. package/dist/mind/friends/store.js +0 -4
  683. package/dist/mind/friends/tokens.js +0 -26
  684. package/dist/mind/friends/types.js +0 -21
  685. package/dist/repertoire/tasks/board.js +0 -122
  686. package/dist/repertoire/tasks/index.js +0 -210
  687. package/dist/repertoire/tasks/middleware.js +0 -65
  688. package/dist/repertoire/tasks/parser.js +0 -173
  689. package/dist/repertoire/tasks/scanner.js +0 -132
  690. package/dist/repertoire/tasks/transitions.js +0 -145
  691. package/dist/senses/bluebubbles-client.js +0 -279
  692. package/dist/senses/bluebubbles-entry.js +0 -11
  693. package/dist/senses/bluebubbles-model.js +0 -253
  694. package/dist/senses/bluebubbles.js +0 -332
  695. package/dist/senses/inner-dialog-worker.js +0 -61
  696. package/dist/senses/inner-dialog.js +0 -231
  697. package/subagents/README.md +0 -73
  698. package/subagents/work-doer.md +0 -233
  699. package/subagents/work-merger.md +0 -624
  700. package/subagents/work-planner.md +0 -373
  701. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  702. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  703. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  704. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  705. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  706. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  707. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  708. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  709. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  710. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  711. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  712. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
@@ -34,19 +34,477 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.messageFromHabitPokeError = messageFromHabitPokeError;
38
+ exports.parseOrphanPidsFromPs = parseOrphanPidsFromPs;
39
+ exports.filterPidfilePidsToActualOrphans = filterPidfilePidsToActualOrphans;
40
+ exports.mergeUniqueOrphanPids = mergeUniqueOrphanPids;
41
+ exports.waitForOrphanProcessesToSettle = waitForOrphanProcessesToSettle;
42
+ exports.assertOrphanCleanupComplete = assertOrphanCleanupComplete;
43
+ exports.drainOrphanProcessesBeforeStartup = drainOrphanProcessesBeforeStartup;
44
+ exports.killOrphanProcesses = killOrphanProcesses;
45
+ exports.writePidfile = writePidfile;
46
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
47
+ exports.handleAgentAskTurn = handleAgentAskTurn;
37
48
  const fs = __importStar(require("fs"));
38
49
  const net = __importStar(require("net"));
50
+ const os = __importStar(require("os"));
39
51
  const path = __importStar(require("path"));
52
+ const node_crypto_1 = require("node:crypto");
40
53
  const identity_1 = require("../identity");
54
+ const agent_discovery_1 = require("./agent-discovery");
41
55
  const runtime_1 = require("../../nerves/runtime");
42
- function formatStatusSummary(snapshots) {
43
- if (snapshots.length === 0)
56
+ const runtime_metadata_1 = require("./runtime-metadata");
57
+ const runtime_mode_1 = require("./runtime-mode");
58
+ const update_hooks_1 = require("../versioning/update-hooks");
59
+ const bundle_meta_1 = require("./hooks/bundle-meta");
60
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
61
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
62
+ const update_checker_1 = require("../versioning/update-checker");
63
+ const child_process_1 = require("child_process");
64
+ const pending_1 = require("../../mind/pending");
65
+ const agent_service_1 = require("./agent-service");
66
+ const friends_1 = require("@ouro.bot/friends");
67
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
68
+ const mcp_tools_1 = require("../../repertoire/mcp-tools");
69
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
70
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
71
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
72
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
73
+ const provider_visibility_1 = require("../provider-visibility");
74
+ const provider_binding_resolver_1 = require("../provider-binding-resolver");
75
+ const private_runtime_1 = require("../private-runtime");
76
+ const socket_client_1 = require("./socket-client");
77
+ const flight_recorder_1 = require("../../arc/flight-recorder");
78
+ const await_private_wake_1 = require("./await-private-wake");
79
+ const habit_private_wake_1 = require("./habit-private-wake");
80
+ const habit_parser_1 = require("../habits/habit-parser");
81
+ const habit_runtime_state_1 = require("../habits/habit-runtime-state");
82
+ const router_1 = require("../external-events/router");
83
+ const habit_policy_1 = require("../../rsvp/habit-policy");
84
+ const container_runtime_1 = require("./container-runtime");
85
+ const habit_session_1 = require("../habits/habit-session");
86
+ const turn_execution_lease_1 = require("../turn-execution-lease");
87
+ const frontend_session_service_1 = require("../frontend-session-service");
88
+ const frontend_socket_1 = require("../frontend-socket");
89
+ const frontend_journal_1 = require("../frontend-journal");
90
+ const frontend_approval_runtime_1 = require("../frontend-approval-runtime");
91
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
92
+ /**
93
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
94
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
95
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
96
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
97
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
98
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
99
+ * by a vitest test that called daemon.start()).
100
+ *
101
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
102
+ * to make the production pidfile sacred. Tests that need to verify these
103
+ * functions' behavior should use the extracted pure helpers
104
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
105
+ */
106
+ function isVitestProcess() {
107
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
108
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
109
+ return false;
110
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
111
+ }
112
+ function messageFromHabitPokeError(error) {
113
+ if (error instanceof Error)
114
+ return error.message;
115
+ /* v8 ignore next -- defensive fallback for hostile/non-Error throws from filesystem or parsers @preserve */
116
+ return String(error);
117
+ }
118
+ /**
119
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
120
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
121
+ * that are safe to SIGTERM — true orphans, not children of live sibling
122
+ * daemons running from worktrees, test suites, or other users of the harness.
123
+ *
124
+ * Exported so unit tests can exercise the filter without shelling out.
125
+ */
126
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
127
+ const orphans = [];
128
+ for (const line of psOutput.split("\n")) {
129
+ // Explicitly exclude MCP server processes — they share a harness entry
130
+ // point but are not daemon children and must never be killed.
131
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
132
+ continue;
133
+ // Match only daemon-owned JS entry points.
134
+ if (!line.includes("agent-entry.js")
135
+ && !line.includes("daemon-entry.js")
136
+ && !line.includes("bluebubbles/entry.js")
137
+ && !line.includes("mail-entry.js")
138
+ && !line.includes("teams-entry.js")
139
+ && !line.includes("a2a-entry.js")
140
+ && !line.includes("telegram-entry.js")
141
+ && !line.includes("voice-entry.js"))
142
+ continue;
143
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
144
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
145
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
146
+ if (!match)
147
+ continue;
148
+ const pid = parseInt(match[1], 10);
149
+ const ppid = parseInt(match[2], 10);
150
+ if (pid === selfPid)
151
+ continue;
152
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
153
+ // PPID means the process belongs to another daemon instance (parallel
154
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
155
+ // Killing those will crash unrelated harnesses — we saw this in B6
156
+ // when a vitest worker's daemon killed a production agent's children.
157
+ if (ppid !== 1)
158
+ continue;
159
+ orphans.push(pid);
160
+ }
161
+ return orphans;
162
+ }
163
+ /**
164
+ * Given a list of PIDs from the pidfile, return only those that are actual
165
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
166
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
167
+ *
168
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
169
+ * Returns the empty list if ps fails — safer to skip cleanup than to
170
+ * wildcard-kill on a bad read.
171
+ *
172
+ * Exported for direct unit coverage.
173
+ */
174
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
175
+ if (candidatePids.length === 0)
176
+ return [];
177
+ const psOutput = psRunner(candidatePids);
178
+ if (psOutput === null)
179
+ return [];
180
+ const survivingOrphans = [];
181
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
182
+ // PIDs not found (already exited) are silently omitted — which is the
183
+ // correct behavior for us: we only want to kill live orphans.
184
+ for (const line of psOutput.split("\n")) {
185
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
186
+ if (!match)
187
+ continue;
188
+ const pid = parseInt(match[1], 10);
189
+ const ppid = parseInt(match[2], 10);
190
+ if (ppid !== 1)
191
+ continue;
192
+ if (!candidatePids.includes(pid))
193
+ continue;
194
+ survivingOrphans.push(pid);
195
+ }
196
+ return survivingOrphans;
197
+ }
198
+ function mergeUniqueOrphanPids(...sources) {
199
+ const merged = [];
200
+ const seen = new Set();
201
+ for (const source of sources) {
202
+ for (const pid of source) {
203
+ if (seen.has(pid))
204
+ continue;
205
+ seen.add(pid);
206
+ merged.push(pid);
207
+ }
208
+ }
209
+ return merged;
210
+ }
211
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
212
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
213
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
214
+ function defaultIsPidAlive(pid) {
215
+ try {
216
+ process.kill(pid, 0);
217
+ return true;
218
+ }
219
+ catch (error) {
220
+ return error.code === "EPERM";
221
+ }
222
+ }
223
+ /* v8 ignore stop */
224
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
225
+ async function defaultSettleSleep(ms) {
226
+ await new Promise((resolve) => setTimeout(resolve, ms));
227
+ }
228
+ /* v8 ignore stop */
229
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
230
+ if (pids.length === 0)
231
+ return [];
232
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
233
+ const now = deps.now ?? Date.now;
234
+ const sleep = deps.sleep ?? defaultSettleSleep;
235
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
236
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
237
+ const deadline = now() + timeoutMs;
238
+ let survivors = pids.filter(isPidAlive);
239
+ while (survivors.length > 0 && now() < deadline) {
240
+ await sleep(pollIntervalMs);
241
+ survivors = pids.filter(isPidAlive);
242
+ }
243
+ return survivors;
244
+ }
245
+ function assertOrphanCleanupComplete(survivingPids) {
246
+ if (survivingPids.length === 0)
247
+ return;
248
+ const errorReason = `refusing startup while ${survivingPids.length} orphaned Ouro processes remain: ${survivingPids.join(", ")}`;
249
+ (0, runtime_1.emitNervesEvent)({
250
+ level: "error",
251
+ component: "daemon",
252
+ event: "daemon.orphan_cleanup_incomplete",
253
+ message: errorReason,
254
+ meta: { survivingPids },
255
+ });
256
+ throw new Error(errorReason);
257
+ }
258
+ const ORPHAN_CLEANUP_MAX_SIGNAL_PASSES = 8;
259
+ async function drainOrphanProcessesBeforeStartup(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, deps = {}) {
260
+ const signalOrphans = deps.signalOrphans ?? killOrphanProcesses;
261
+ const settleOrphans = deps.settleOrphans ?? waitForOrphanProcessesToSettle;
262
+ const maxSignalPasses = deps.maxSignalPasses ?? ORPHAN_CLEANUP_MAX_SIGNAL_PASSES;
263
+ for (let pass = 0; pass < maxSignalPasses; pass += 1) {
264
+ const signaledPids = signalOrphans(socketPath);
265
+ if (signaledPids.length === 0)
266
+ return;
267
+ const survivingPids = await settleOrphans(signaledPids);
268
+ assertOrphanCleanupComplete(survivingPids);
269
+ }
270
+ const errorReason = `orphan cleanup did not reach a fixed point after ${maxSignalPasses} signaling round(s)`;
271
+ (0, runtime_1.emitNervesEvent)({
272
+ level: "error",
273
+ component: "daemon",
274
+ event: "daemon.orphan_cleanup_not_converged",
275
+ message: errorReason,
276
+ meta: { maxSignalPasses },
277
+ });
278
+ throw new Error(errorReason);
279
+ }
280
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
281
+ function runPsCheck(pids) {
282
+ try {
283
+ const csv = pids.join(",");
284
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
285
+ }
286
+ catch {
287
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
288
+ // "no survivors" rather than an error.
289
+ return "";
290
+ }
291
+ }
292
+ /* v8 ignore stop */
293
+ /**
294
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
295
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
296
+ * deletes the file. The new daemon writes its own PIDs after spawning.
297
+ *
298
+ * Safety: pidfile contents are verified before being killed — each PID must
299
+ * be an actual orphan (PPID reparented to init/PID 1) via
300
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
301
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
302
+ * OS) could SIGTERM unrelated processes.
303
+ *
304
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
305
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
306
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
307
+ */
308
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
309
+ function isProductionDaemonSocketPath(socketPath) {
310
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
311
+ }
312
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
313
+ if (!isProductionDaemonSocketPath(socketPath)) {
314
+ (0, runtime_1.emitNervesEvent)({
315
+ level: "warn",
316
+ component: "daemon",
317
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
318
+ message: "blocked orphan cleanup for non-production daemon socket",
319
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
320
+ });
321
+ return [];
322
+ }
323
+ if (isVitestProcess()) {
324
+ (0, runtime_1.emitNervesEvent)({
325
+ level: "warn",
326
+ component: "daemon",
327
+ event: "daemon.orphan_cleanup_test_blocked",
328
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
329
+ meta: { pidfilePath: PIDFILE_PATH },
330
+ });
331
+ return [];
332
+ }
333
+ try {
334
+ let pidfileOrphans = [];
335
+ let scanOrphans = [];
336
+ // Primary: read pidfile from previous daemon
337
+ try {
338
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
339
+ const candidates = raw.split("\n")
340
+ .map((s) => parseInt(s.trim(), 10))
341
+ .filter((n) => !isNaN(n) && n !== process.pid);
342
+ // Verify each candidate is an actual live orphan before killing. See
343
+ // docstring above for why this matters.
344
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
345
+ fs.unlinkSync(PIDFILE_PATH);
346
+ }
347
+ catch {
348
+ // No pidfile — the ps scan below still covers true orphans.
349
+ }
350
+ // Always supplement the pidfile with the scoped ps scan. A stale or
351
+ // partial pidfile can otherwise kill one old daemon while leaving a
352
+ // sibling PPID=1 daemon alive without a socket.
353
+ try {
354
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
355
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
356
+ }
357
+ catch (error) {
358
+ const detail = error instanceof Error ? error.message : String(error);
359
+ throw new Error(`could not discover orphaned Ouro processes: ${detail}`);
360
+ }
361
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
362
+ if (pidsToKill.length > 0) {
363
+ for (const pid of pidsToKill) {
364
+ try {
365
+ process.kill(pid, "SIGTERM");
366
+ }
367
+ catch { /* already exited */ }
368
+ }
369
+ (0, runtime_1.emitNervesEvent)({
370
+ component: "daemon",
371
+ event: "daemon.orphan_cleanup",
372
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
373
+ meta: { pids: pidsToKill },
374
+ });
375
+ }
376
+ return pidsToKill;
377
+ }
378
+ catch (error) {
379
+ (0, runtime_1.emitNervesEvent)({
380
+ level: "error",
381
+ component: "daemon",
382
+ event: "daemon.orphan_cleanup_error",
383
+ message: "failed to clean up orphaned ouro processes",
384
+ meta: { error: error instanceof Error ? error.message : String(error) },
385
+ });
386
+ throw error instanceof Error ? error : new Error(String(error));
387
+ }
388
+ }
389
+ /**
390
+ * Write all managed PIDs (daemon + children) to the pidfile.
391
+ * Called after all agents and senses are spawned.
392
+ */
393
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
394
+ if (!isProductionDaemonSocketPath(socketPath)) {
395
+ (0, runtime_1.emitNervesEvent)({
396
+ level: "warn",
397
+ component: "daemon",
398
+ event: "daemon.write_pidfile_nonproduction_blocked",
399
+ message: "blocked production pidfile write for non-production daemon socket",
400
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
401
+ });
402
+ return;
403
+ }
404
+ if (isVitestProcess()) {
405
+ (0, runtime_1.emitNervesEvent)({
406
+ level: "warn",
407
+ component: "daemon",
408
+ event: "daemon.write_pidfile_test_blocked",
409
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
410
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
411
+ });
412
+ return;
413
+ }
414
+ try {
415
+ const pids = [process.pid, ...extraPids].filter(Boolean);
416
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
417
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
418
+ }
419
+ catch { /* best effort */ }
420
+ }
421
+ function readSocketIdentity(socketPath) {
422
+ try {
423
+ const stats = fs.lstatSync(socketPath);
424
+ return {
425
+ dev: stats.dev,
426
+ ino: stats.ino,
427
+ ctimeMs: stats.ctimeMs,
428
+ };
429
+ }
430
+ catch {
431
+ return null;
432
+ }
433
+ }
434
+ function sameSocketIdentity(left, right) {
435
+ if (!left || !right)
436
+ return false;
437
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
438
+ }
439
+ function buildWorkerRows(snapshots) {
440
+ return snapshots.map((snapshot) => ({
441
+ agent: snapshot.name,
442
+ worker: snapshot.channel,
443
+ autoStart: snapshot.autoStart ?? true,
444
+ status: snapshot.status,
445
+ pid: snapshot.pid,
446
+ restartCount: snapshot.restartCount,
447
+ startedAt: snapshot.startedAt,
448
+ lastExitCode: snapshot.lastExitCode ?? null,
449
+ lastSignal: snapshot.lastSignal ?? null,
450
+ errorReason: snapshot.errorReason ?? null,
451
+ fixHint: snapshot.fixHint ?? null,
452
+ }));
453
+ }
454
+ function unhealthySenseRows(senses) {
455
+ return senses.filter((row) => {
456
+ if (!row.enabled)
457
+ return false;
458
+ if (row.status === "disabled" || row.status === "not_attached")
459
+ return false;
460
+ if (row.status === "interactive" || row.status === "running")
461
+ return false;
462
+ return true;
463
+ });
464
+ }
465
+ function isParkedWorker(row) {
466
+ return row.autoStart === false && row.status === "stopped";
467
+ }
468
+ function unhealthyWorkerRows(workers) {
469
+ return workers.filter((row) => !isParkedWorker(row) && row.status !== "running");
470
+ }
471
+ function unhealthyHealthChecks(healthChecks) {
472
+ return healthChecks.filter((row) => row.status !== "ok");
473
+ }
474
+ function overviewHealth(workers, senses, healthChecks = []) {
475
+ if (unhealthyWorkerRows(workers).length > 0)
476
+ return "warn";
477
+ if (unhealthySenseRows(senses).length > 0)
478
+ return "warn";
479
+ if (unhealthyHealthChecks(healthChecks).length > 0)
480
+ return "warn";
481
+ return "ok";
482
+ }
483
+ function formatStatusSummary(payload) {
484
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
44
485
  return "no managed agents";
45
- return snapshots
46
- .map((snapshot) => {
47
- return `${snapshot.name}\t${snapshot.channel}\t${snapshot.status}\tpid=${snapshot.pid ?? "none"}\trestarts=${snapshot.restartCount}`;
48
- })
49
- .join("\n");
486
+ }
487
+ const degraded = [
488
+ ...unhealthyWorkerRows(payload.workers)
489
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
490
+ ...unhealthySenseRows(payload.senses)
491
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
492
+ ...(payload.healthChecks ?? [])
493
+ .filter((row) => row.status !== "ok")
494
+ .map((row) => `health-check:${row.name}:${row.status}`),
495
+ ];
496
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
497
+ if (!detail) {
498
+ const rows = [
499
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
500
+ ...payload.senses
501
+ .filter((row) => row.enabled)
502
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
503
+ ];
504
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
505
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
506
+ }
507
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
50
508
  }
51
509
  function parseIncomingCommand(raw) {
52
510
  let parsed;
@@ -65,21 +523,258 @@ function parseIncomingCommand(raw) {
65
523
  }
66
524
  return parsed;
67
525
  }
526
+ function isValidSenseReviveCommand(command) {
527
+ return typeof command.agent === "string"
528
+ && typeof command.sense === "string"
529
+ && typeof command.reason === "string";
530
+ }
531
+ function isValidTaskPokeCommand(command) {
532
+ return typeof command.agent === "string"
533
+ && command.agent.trim().length > 0
534
+ && typeof command.taskId === "string"
535
+ && command.taskId.trim().length > 0;
536
+ }
537
+ function isValidHabitPokeCommand(command) {
538
+ return typeof command.agent === "string"
539
+ && command.agent.trim().length > 0
540
+ && typeof command.habitName === "string"
541
+ && command.habitName.trim().length > 0;
542
+ }
543
+ function isValidHabitProbeCommand(command) {
544
+ return typeof command.agent === "string"
545
+ && command.agent.trim().length > 0
546
+ && typeof command.habitName === "string"
547
+ && command.habitName.trim().length > 0
548
+ && (command.noSend === undefined || command.noSend === true);
549
+ }
550
+ function taskIdFromTaskPokePrivateWakeCommand(command) {
551
+ if (command.kind !== "private.wake" || command.triggerSource !== "task-poke")
552
+ return null;
553
+ const taskRef = command.originRefs?.find((ref) => ref.kind === "task" && typeof ref.id === "string");
554
+ if (!taskRef || typeof taskRef.id !== "string")
555
+ return null;
556
+ const trimmed = taskRef.id.trim();
557
+ return trimmed.length > 0 ? trimmed : null;
558
+ }
559
+ /**
560
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
561
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
562
+ * restarts the daemon process (fresh module cache).
563
+ */
564
+ async function handleAgentSenseTurn(command, runtime) {
565
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
566
+ try {
567
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
568
+ setAgentName(command.agent);
569
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
570
+ const result = await runSenseTurn({
571
+ agentName: command.agent,
572
+ channel: command.channel,
573
+ sessionKey: command.sessionKey,
574
+ friendId: command.friendId,
575
+ userMessage: command.message,
576
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
577
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
578
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
579
+ // turn for a different agent cannot inherit these servers.
580
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
581
+ });
582
+ return {
583
+ ok: true,
584
+ message: result.response,
585
+ data: { ponderDeferred: result.ponderDeferred },
586
+ };
587
+ }
588
+ catch (error) {
589
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
590
+ const errorMessage = error instanceof Error ? error.message : String(error);
591
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
592
+ }
593
+ });
594
+ }
595
+ async function handleAgentAskTurn(command, runtime) {
596
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
597
+ const question = typeof command.question === "string" ? command.question : "";
598
+ if (!question.trim())
599
+ return { ok: false, error: "Missing required parameter: question" };
600
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
601
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
602
+ ? command.sessionKey.trim()
603
+ : `agent-ask:${command.friendId}`;
604
+ /* v8 ignore stop */
605
+ return handleAgentSenseTurn({
606
+ kind: "agent.senseTurn",
607
+ agent: command.agent,
608
+ friendId: command.friendId,
609
+ channel,
610
+ sessionKey,
611
+ message: question,
612
+ }, runtime);
613
+ }
68
614
  class OuroDaemon {
69
615
  socketPath;
70
616
  processManager;
71
617
  scheduler;
72
618
  healthMonitor;
73
619
  router;
620
+ senseManager;
74
621
  bundlesRoot;
622
+ mode;
75
623
  server = null;
624
+ mailboxServer = null;
625
+ frontendSocketServer = null;
626
+ socketIdentity = null;
627
+ senseAutostartTimer = null;
628
+ externalEventReconcileTimer = null;
629
+ externalEventReconcileRunning = false;
630
+ constructedAtMs = Date.now();
631
+ mailboxServerFactory;
632
+ frontendSocketPath;
633
+ frontendSessionService;
634
+ frontendSocketServerFactory;
635
+ privateRuntimePolicyDeps;
636
+ onStopCommandComplete;
637
+ externalEventRoot;
638
+ privilegedEventSpoolRoot;
639
+ privilegedEventScanner;
640
+ externalEventScanCache = new router_1.ExternalEventScanCache();
641
+ rsvpHabitRunner;
642
+ nativeHabitRunner;
643
+ nativeHabitMatch;
644
+ nativeHabitClaims = new Set();
645
+ authenticatedSchedulerPokes = new WeakMap();
646
+ schedulerFireVerifier;
647
+ schedulerFireConsumer;
648
+ orphanStartupDrain;
649
+ externalEventSourceReadiness;
76
650
  constructor(options) {
77
651
  this.socketPath = options.socketPath;
78
652
  this.processManager = options.processManager;
79
653
  this.scheduler = options.scheduler;
80
654
  this.healthMonitor = options.healthMonitor;
81
655
  this.router = options.router;
656
+ this.senseManager = options.senseManager ?? null;
82
657
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
658
+ this.mode = options.mode ?? "production";
659
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
660
+ this.frontendSocketPath = options.frontendSocketPath ?? (0, frontend_socket_1.frontendSocketPathForDaemon)(this.socketPath);
661
+ /* v8 ignore next -- path-only default adapter; frontend service tests inject and verify the same root contract @preserve */
662
+ const frontendAgentRoot = (agent) => path.join(this.bundlesRoot, `${agent}.ouro`);
663
+ this.frontendSessionService = options.frontendSessionService ?? new frontend_session_service_1.FrontendSessionService({
664
+ journal: new frontend_journal_1.FrontendJournalStore({ agentRoot: frontendAgentRoot }),
665
+ authority: (0, frontend_approval_runtime_1.createFrontendApprovalRuntime)({
666
+ agentRoot: frontendAgentRoot,
667
+ settleApproval: frontend_approval_runtime_1.settleFrontendApproval,
668
+ }),
669
+ });
670
+ this.frontendSocketServerFactory = options.frontendSocketServerFactory ?? frontend_socket_1.startFrontendSocketServer;
671
+ this.privateRuntimePolicyDeps = options.privateRuntimePolicyDeps ?? {};
672
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
673
+ this.externalEventRoot = options.externalEventRoot ?? null;
674
+ this.privilegedEventSpoolRoot = options.privilegedEventSpoolRoot ?? "/run/ouro-events";
675
+ this.privilegedEventScanner = options.privilegedEventScanner ?? router_1.scanPrivilegedEventSpool;
676
+ this.rsvpHabitRunner = options.rsvpHabitRunner;
677
+ this.nativeHabitRunner = options.nativeHabitRunner;
678
+ this.nativeHabitMatch = options.nativeHabitMatch;
679
+ this.schedulerFireVerifier = options.schedulerFireVerifier;
680
+ this.schedulerFireConsumer = options.schedulerFireConsumer;
681
+ this.orphanStartupDrain = options.orphanStartupDrain ?? drainOrphanProcessesBeforeStartup;
682
+ this.externalEventSourceReadiness = options.externalEventSourceReadiness ?? (async (agent, source) => {
683
+ const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../../senses/sanctuary-runtime")));
684
+ await ensureSanctuarySourceRuntimeReady(agent, source);
685
+ });
686
+ }
687
+ /* v8 ignore start -- default mailbox server wiring: production-only path, tests inject mailboxServerFactory stub instead. startMailboxHttpServer itself has full coverage in mailbox-http.test.ts @preserve */
688
+ createDefaultMailboxServer() {
689
+ return (0, mailbox_http_1.startMailboxHttpServer)({
690
+ host: "127.0.0.1",
691
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
692
+ bundlesRoot: this.bundlesRoot,
693
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
694
+ readMachineView: ({ machine }) => {
695
+ const overview = this.buildStatusPayload().overview;
696
+ return (0, mailbox_view_1.buildMailboxMachineView)({
697
+ machine,
698
+ daemon: {
699
+ status: overview.daemon,
700
+ health: overview.health,
701
+ mode: overview.mode,
702
+ socketPath: overview.socketPath,
703
+ mailboxUrl: overview.mailboxUrl,
704
+ entryPath: overview.entryPath,
705
+ workerCount: overview.workerCount,
706
+ senseCount: overview.senseCount,
707
+ },
708
+ });
709
+ },
710
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
711
+ readAgentView: (agentName) => {
712
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
713
+ return (0, mailbox_view_1.buildMailboxAgentView)({
714
+ agent,
715
+ viewer: { kind: "human" },
716
+ });
717
+ },
718
+ });
719
+ }
720
+ /* v8 ignore stop */
721
+ buildStatusPayload() {
722
+ const snapshots = this.processManager.listAgentSnapshots();
723
+ const workers = buildWorkerRows(snapshots);
724
+ const senses = this.senseManager?.listSenseRows() ?? [];
725
+ const healthChecks = this.overlaySchedulerHealth(this.healthMonitor.getLastResults?.() ?? []);
726
+ const repoRoot = (0, identity_1.getRepoRoot)();
727
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
728
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
729
+ const providerAgents = (0, agent_discovery_1.listEnabledBundleAgents)({ bundlesRoot: this.bundlesRoot });
730
+ const providers = providerAgents.flatMap((agentName) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
731
+ agentName,
732
+ agentRoot: path.join(this.bundlesRoot, `${agentName}.ouro`),
733
+ })));
734
+ const externalEvents = (0, router_1.listExternalEventStatus)(this.externalEventRoot ?? (0, router_1.getExternalEventRoot)());
735
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
736
+ return {
737
+ overview: {
738
+ daemon: "running",
739
+ health: overviewHealth(workers, senses, healthChecks),
740
+ socketPath: this.socketPath,
741
+ mailboxUrl,
742
+ outlookUrl: mailboxUrl,
743
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
744
+ workerCount: workers.length,
745
+ senseCount: senses.length,
746
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
747
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
748
+ },
749
+ workers,
750
+ senses,
751
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
752
+ sync,
753
+ agents,
754
+ ...(providers.length > 0 ? { providers } : {}),
755
+ ...(externalEvents.length > 0 ? { externalEvents } : {}),
756
+ };
757
+ }
758
+ overlaySchedulerHealth(healthChecks) {
759
+ const degradedJobs = this.scheduler.listDegradedJobs?.() ?? [];
760
+ if (degradedJobs.length === 0)
761
+ return healthChecks;
762
+ const cronHealth = {
763
+ name: "cron-health",
764
+ status: "warn",
765
+ message: `cron jobs degraded; timer fallback active: ${degradedJobs
766
+ .map((job) => `${job.id} (${job.reason})`)
767
+ .join(", ")}`,
768
+ };
769
+ const next = healthChecks.map((check) => ({ ...check }));
770
+ const existingIndex = next.findIndex((check) => check.name === "cron-health");
771
+ if (existingIndex === -1) {
772
+ next.push(cronHealth);
773
+ }
774
+ else {
775
+ next[existingIndex] = cronHealth;
776
+ }
777
+ return next;
83
778
  }
84
779
  async start() {
85
780
  if (this.server)
@@ -90,22 +785,201 @@ class OuroDaemon {
90
785
  message: "starting daemon server",
91
786
  meta: { socketPath: this.socketPath },
92
787
  });
93
- await this.processManager.startAutoStartAgents();
788
+ try {
789
+ await this.startInner();
790
+ }
791
+ catch (err) {
792
+ // Emit a paired terminating event (`_error`) so the nerves audit's
793
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
794
+ // and `stop()` (which emits `server_end`) is never called.
795
+ (0, runtime_1.emitNervesEvent)({
796
+ level: "error",
797
+ component: "daemon",
798
+ event: "daemon.server_error",
799
+ message: "daemon start failed",
800
+ meta: {
801
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
802
+ },
803
+ });
804
+ throw err;
805
+ }
806
+ }
807
+ async startInner() {
808
+ const containerPolicy = (0, container_runtime_1.readContainerRuntimePolicy)();
809
+ // Register update hooks and apply pending updates before starting agents
810
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
811
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
812
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
813
+ if (containerPolicy?.updates !== "disabled")
814
+ await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
815
+ // Start periodic update checker (polls npm registry every 30 minutes)
816
+ // Skip in dev mode — dev builds should not auto-update from npm
817
+ if (this.mode === "dev" || containerPolicy?.updates === "disabled") {
818
+ (0, runtime_1.emitNervesEvent)({
819
+ component: "daemon",
820
+ event: "daemon.update_checker_skip",
821
+ message: "skipping update checker in dev mode",
822
+ meta: { reason: this.mode === "dev" ? "dev mode" : "container policy" },
823
+ });
824
+ }
825
+ else {
826
+ (0, update_checker_1.startUpdateChecker)({
827
+ currentVersion,
828
+ deps: {
829
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
830
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
831
+ fetchRegistryJson: async () => {
832
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
833
+ return res.json();
834
+ },
835
+ /* v8 ignore stop */
836
+ },
837
+ });
838
+ }
839
+ // MCP connections are lazily initialized per-agent during senseTurn
840
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
841
+ await this.orphanStartupDrain(this.socketPath);
842
+ await this.openCommandSocket();
843
+ await this.reconcileExternalEvents();
844
+ this.externalEventReconcileTimer = setInterval(() => {
845
+ void this.reconcileExternalEvents();
846
+ }, 1_000);
847
+ this.externalEventReconcileTimer.unref?.();
848
+ this.triggerAutoStartAgents();
849
+ this.triggerAutoStartSensesWhenAgentsSettled();
850
+ // Write all managed PIDs to disk so the next daemon can clean up
851
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
852
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
853
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
854
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
855
+ /* v8 ignore stop */
94
856
  this.scheduler.start?.();
95
857
  await this.scheduler.reconcile?.();
96
858
  await this.drainPendingBundleMessages();
859
+ await this.drainPendingSenseMessages();
860
+ // startInner is only reachable when this.server is null (guarded in
861
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
862
+ // so mailboxServer is guaranteed unset here — no need for a guard.
863
+ try {
864
+ this.mailboxServer = await this.mailboxServerFactory();
865
+ }
866
+ catch (error) {
867
+ (0, runtime_1.emitNervesEvent)({
868
+ level: "warn",
869
+ component: "daemon",
870
+ event: "daemon.mailbox_start_failed",
871
+ message: `Mailbox server failed to start: ${String(error)}`,
872
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
873
+ });
874
+ }
875
+ try {
876
+ this.frontendSocketServer = await this.frontendSocketServerFactory({
877
+ socketPath: this.frontendSocketPath,
878
+ service: this.frontendSessionService,
879
+ });
880
+ }
881
+ catch (error) {
882
+ (0, runtime_1.emitNervesEvent)({
883
+ level: "warn",
884
+ component: "daemon",
885
+ event: "daemon.frontend_socket_start_failed",
886
+ message: `Frontend socket failed to start: ${String(error)}`,
887
+ meta: { socketPath: this.frontendSocketPath },
888
+ });
889
+ }
890
+ }
891
+ triggerAutoStartAgents() {
892
+ if (this.processManager.triggerAutoStartAgents) {
893
+ this.processManager.triggerAutoStartAgents();
894
+ return;
895
+ }
896
+ void this.processManager.startAutoStartAgents().catch((error) => {
897
+ (0, runtime_1.emitNervesEvent)({
898
+ level: "error",
899
+ component: "daemon",
900
+ event: "daemon.agent_autostart_error",
901
+ message: "agent autostart failed after daemon socket opened",
902
+ meta: { error: error instanceof Error ? error.message : String(error) },
903
+ });
904
+ });
905
+ }
906
+ triggerAutoStartSenses() {
907
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
908
+ if (!this.senseManager)
909
+ return;
910
+ if (this.senseManager.triggerAutoStartSenses) {
911
+ this.senseManager.triggerAutoStartSenses();
912
+ return;
913
+ }
914
+ void this.senseManager.startAutoStartSenses().catch((error) => {
915
+ (0, runtime_1.emitNervesEvent)({
916
+ level: "error",
917
+ component: "daemon",
918
+ event: "daemon.sense_autostart_error",
919
+ message: "sense autostart failed after daemon socket opened",
920
+ meta: { error: error instanceof Error ? error.message : String(error) },
921
+ });
922
+ });
923
+ }
924
+ triggerAutoStartSensesWhenAgentsSettled() {
925
+ if (!this.senseManager)
926
+ return;
927
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
928
+ .some((snapshot) => snapshot.status === "starting");
929
+ if (!waitingOnAgents) {
930
+ this.triggerAutoStartSenses();
931
+ return;
932
+ }
933
+ this.senseAutostartTimer = setTimeout(() => {
934
+ this.senseAutostartTimer = null;
935
+ this.triggerAutoStartSensesWhenAgentsSettled();
936
+ }, 250);
937
+ }
938
+ async openCommandSocket() {
97
939
  if (fs.existsSync(this.socketPath)) {
98
940
  fs.unlinkSync(this.socketPath);
99
941
  }
100
- this.server = net.createServer((connection) => {
942
+ // allowHalfOpen: true lets the server keep its writable side open after
943
+ // the client sends FIN. Without this, when a client calls `client.end()`
944
+ // after writing a command, node closes the server's writable side
945
+ // automatically — so a long-running response (like an agent.senseTurn
946
+ // LLM turn that takes 5+ seconds) never reaches the client. The
947
+ // socket-client fix in #303/#334 also removed client.end() on the
948
+ // sending side, but this option is defense in depth: even if a future
949
+ // caller half-closes, the server still writes its response correctly.
950
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
101
951
  let raw = "";
102
952
  let responded = false;
953
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
954
+ connection.on("error", (err) => {
955
+ (0, runtime_1.emitNervesEvent)({
956
+ level: "warn",
957
+ component: "daemon",
958
+ event: "daemon.connection_error",
959
+ message: "socket connection error",
960
+ meta: { error: err.message, code: err.code ?? null },
961
+ });
962
+ });
963
+ /* v8 ignore stop */
103
964
  const flushResponse = async () => {
104
965
  if (responded)
105
966
  return;
106
967
  responded = true;
107
968
  const response = await this.handleRawPayload(raw);
108
- connection.end(response);
969
+ try {
970
+ connection.end(response);
971
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
972
+ }
973
+ catch (err) {
974
+ (0, runtime_1.emitNervesEvent)({
975
+ level: "warn",
976
+ component: "daemon",
977
+ event: "daemon.connection_end_error",
978
+ message: "failed to send response to client (EPIPE)",
979
+ meta: { error: err instanceof Error ? err.message : String(err) },
980
+ });
981
+ }
982
+ /* v8 ignore stop */
109
983
  };
110
984
  connection.on("data", (chunk) => {
111
985
  raw += chunk.toString("utf-8");
@@ -118,7 +992,23 @@ class OuroDaemon {
118
992
  const server = this.server;
119
993
  await new Promise((resolve, reject) => {
120
994
  server.once("error", reject);
121
- server.listen(this.socketPath, () => resolve());
995
+ server.listen(this.socketPath, () => {
996
+ // Replace the one-time error listener with a persistent one after successful listen
997
+ server.removeAllListeners("error");
998
+ this.socketIdentity = readSocketIdentity(this.socketPath);
999
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
1000
+ server.on("error", (err) => {
1001
+ (0, runtime_1.emitNervesEvent)({
1002
+ level: "error",
1003
+ component: "daemon",
1004
+ event: "daemon.server_error",
1005
+ message: "daemon server error after listen",
1006
+ meta: { error: err.message, code: err.code ?? null },
1007
+ });
1008
+ });
1009
+ /* v8 ignore stop */
1010
+ resolve();
1011
+ });
122
1012
  });
123
1013
  }
124
1014
  async drainPendingBundleMessages() {
@@ -169,24 +1059,204 @@ class OuroDaemon {
169
1059
  fs.writeFileSync(pendingPath, next, "utf-8");
170
1060
  }
171
1061
  }
1062
+ /** Drains per-sense pending dirs for always-on senses across all agents. */
1063
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
1064
+ async drainPendingSenseMessages() {
1065
+ if (!fs.existsSync(this.bundlesRoot))
1066
+ return;
1067
+ let bundleDirs;
1068
+ try {
1069
+ bundleDirs = fs.readdirSync(this.bundlesRoot, { withFileTypes: true });
1070
+ }
1071
+ catch {
1072
+ return;
1073
+ }
1074
+ for (const bundleDir of bundleDirs) {
1075
+ if (!bundleDir.isDirectory() || !bundleDir.name.endsWith(".ouro"))
1076
+ continue;
1077
+ const agentName = bundleDir.name.replace(/\.ouro$/, "");
1078
+ const pendingRoot = path.join(this.bundlesRoot, bundleDir.name, "state", "pending");
1079
+ if (!fs.existsSync(pendingRoot))
1080
+ continue;
1081
+ let friendDirs;
1082
+ try {
1083
+ friendDirs = fs.readdirSync(pendingRoot, { withFileTypes: true });
1084
+ }
1085
+ catch {
1086
+ continue;
1087
+ }
1088
+ for (const friendDir of friendDirs) {
1089
+ if (!friendDir.isDirectory())
1090
+ continue;
1091
+ const friendPath = path.join(pendingRoot, friendDir.name);
1092
+ let channelDirs;
1093
+ try {
1094
+ channelDirs = fs.readdirSync(friendPath, { withFileTypes: true });
1095
+ }
1096
+ catch {
1097
+ continue;
1098
+ }
1099
+ for (const channelDir of channelDirs) {
1100
+ if (!channelDir.isDirectory())
1101
+ continue;
1102
+ if (!OuroDaemon.ALWAYS_ON_SENSES.has(channelDir.name))
1103
+ continue;
1104
+ const channelPath = path.join(friendPath, channelDir.name);
1105
+ let keyDirs;
1106
+ try {
1107
+ keyDirs = fs.readdirSync(channelPath, { withFileTypes: true });
1108
+ }
1109
+ catch {
1110
+ continue;
1111
+ }
1112
+ for (const keyDir of keyDirs) {
1113
+ if (!keyDir.isDirectory())
1114
+ continue;
1115
+ const leafDir = path.join(channelPath, keyDir.name);
1116
+ const messages = (0, pending_1.drainPending)(leafDir);
1117
+ for (const msg of messages) {
1118
+ try {
1119
+ await this.router.send({
1120
+ from: msg.from,
1121
+ to: agentName,
1122
+ content: msg.content,
1123
+ priority: "normal",
1124
+ });
1125
+ }
1126
+ catch {
1127
+ // Best-effort delivery — log and continue
1128
+ }
1129
+ }
1130
+ if (messages.length > 0) {
1131
+ (0, runtime_1.emitNervesEvent)({
1132
+ component: "daemon",
1133
+ event: "daemon.startup_sense_drain",
1134
+ message: "drained pending sense messages on startup",
1135
+ meta: {
1136
+ agent: agentName,
1137
+ channel: channelDir.name,
1138
+ friendId: friendDir.name,
1139
+ key: keyDir.name,
1140
+ count: messages.length,
1141
+ },
1142
+ });
1143
+ }
1144
+ }
1145
+ }
1146
+ }
1147
+ }
1148
+ }
172
1149
  async stop() {
1150
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1151
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
1152
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
173
1153
  (0, runtime_1.emitNervesEvent)({
174
1154
  component: "daemon",
175
- event: "daemon.server_stop",
1155
+ event: "daemon.server_end",
176
1156
  message: "stopping daemon server",
177
1157
  meta: { socketPath: this.socketPath },
178
1158
  });
1159
+ this.frontendSessionService.cancelAllTurns();
1160
+ if (this.frontendSocketServer) {
1161
+ await this.frontendSocketServer.stop();
1162
+ this.frontendSocketServer = null;
1163
+ }
1164
+ this.frontendSessionService.close?.();
1165
+ (0, update_checker_1.stopUpdateChecker)();
179
1166
  this.scheduler.stop?.();
180
- await this.processManager.stopAll();
1167
+ this.healthMonitor.stopPeriodicChecks?.();
1168
+ if (this.senseAutostartTimer) {
1169
+ clearTimeout(this.senseAutostartTimer);
1170
+ this.senseAutostartTimer = null;
1171
+ }
1172
+ if (this.externalEventReconcileTimer) {
1173
+ clearInterval(this.externalEventReconcileTimer);
1174
+ this.externalEventReconcileTimer = null;
1175
+ }
1176
+ const workerStopTasks = [
1177
+ Promise.resolve().then(() => this.processManager.stopAll()),
1178
+ Promise.resolve().then(() => (0, mcp_manager_1.shutdownSharedMcpManager)()),
1179
+ ];
1180
+ if (this.senseManager) {
1181
+ workerStopTasks.push(Promise.resolve().then(() => this.senseManager.stopAll()));
1182
+ }
1183
+ const workerStopResults = await Promise.allSettled(workerStopTasks);
1184
+ const workerStopFailures = workerStopResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
181
1185
  if (this.server) {
182
- await new Promise((resolve) => {
183
- this.server?.close(() => resolve());
184
- });
1186
+ // DO NOT `await` server.close() here. server.close() resolves only
1187
+ // after every open connection has closed. When stop() is invoked
1188
+ // from the daemon.stop command handler, the calling client's
1189
+ // connection is STILL open — its flushResponse() is currently
1190
+ // awaiting THIS function. Awaiting close() creates a deadlock:
1191
+ //
1192
+ // client → flushResponse → handleRawPayload → daemon.stop case
1193
+ // → stop() → await server.close() (waits for client's connection)
1194
+ // → client's connection waits for flushResponse to call
1195
+ // connection.end() → DEADLOCK
1196
+ //
1197
+ // Both processes sit in kevent forever. Verified live on
1198
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
1199
+ // line for 5+ minutes after a client sent daemon.stop, while the
1200
+ // client (alpha.270 ouro up) hung waiting for the response.
1201
+ //
1202
+ // This regressed when #303/#334/#339 stopped half-closing the
1203
+ // client socket and switched the server to allowHalfOpen: true.
1204
+ // Previously, the client called .end() after writing its command,
1205
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
1206
+ // the server's writable side — incidentally unblocking
1207
+ // server.close() before the response was sent. The half-close
1208
+ // breakage masked this deadlock; the fix exposed it.
1209
+ //
1210
+ // Solution: fire close() and let it complete asynchronously. Once
1211
+ // stop() returns, the daemon.stop case returns its response,
1212
+ // flushResponse() calls connection.end(response), the connection
1213
+ // closes, and server.close()'s pending callback fires. The event
1214
+ // loop drains and the daemon exits cleanly.
1215
+ this.server.close();
185
1216
  this.server = null;
186
1217
  }
187
- if (fs.existsSync(this.socketPath)) {
1218
+ if (this.mailboxServer) {
1219
+ await this.mailboxServer.stop();
1220
+ this.mailboxServer = null;
1221
+ }
1222
+ const socketPathExists = fs.existsSync(this.socketPath);
1223
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1224
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
188
1225
  fs.unlinkSync(this.socketPath);
189
1226
  }
1227
+ else if (socketPathExists) {
1228
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1229
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1230
+ (0, runtime_1.emitNervesEvent)({
1231
+ level: "warn",
1232
+ component: "daemon",
1233
+ event: "daemon.socket_cleanup_skipped",
1234
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1235
+ meta: {
1236
+ socketPath: this.socketPath,
1237
+ expectedDev: expectedSocketIdentity.dev,
1238
+ expectedIno: expectedSocketIdentity.ino,
1239
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1240
+ actualDev: actualSocketIdentity.dev,
1241
+ actualIno: actualSocketIdentity.ino,
1242
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1243
+ },
1244
+ });
1245
+ }
1246
+ this.socketIdentity = null;
1247
+ if (workerStopFailures.length > 0) {
1248
+ const errorReason = `daemon shutdown could not drain ${workerStopFailures.length} managed worker group(s)`;
1249
+ (0, runtime_1.emitNervesEvent)({
1250
+ level: "error",
1251
+ component: "daemon",
1252
+ event: "daemon.worker_shutdown_error",
1253
+ message: errorReason,
1254
+ meta: {
1255
+ failures: workerStopFailures.map((error) => error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error rejection @preserve */ String(error)),
1256
+ },
1257
+ });
1258
+ throw new AggregateError(workerStopFailures, errorReason);
1259
+ }
190
1260
  }
191
1261
  async handleRawPayload(raw) {
192
1262
  try {
@@ -208,19 +1278,657 @@ class OuroDaemon {
208
1278
  message: "handling daemon command",
209
1279
  meta: { kind: command.kind },
210
1280
  });
1281
+ try {
1282
+ return await this.handleCommandInner(command);
1283
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1284
+ }
1285
+ catch (error) {
1286
+ (0, runtime_1.emitNervesEvent)({
1287
+ level: "error",
1288
+ component: "daemon",
1289
+ event: "daemon.command_error",
1290
+ message: "unexpected error handling daemon command",
1291
+ meta: {
1292
+ kind: command.kind,
1293
+ error: error instanceof Error ? error.message : String(error),
1294
+ stack: error instanceof Error ? error.stack ?? null : null,
1295
+ },
1296
+ });
1297
+ throw error;
1298
+ }
1299
+ /* v8 ignore stop */
1300
+ }
1301
+ hasManagedPrivateRuntime(agent) {
1302
+ return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1303
+ }
1304
+ buildPrivateRuntimeWakeRequest(command) {
1305
+ if (command.kind === "inner.wake") {
1306
+ return {
1307
+ agent: command.agent,
1308
+ origin: "daemon.private.wake",
1309
+ reason: "legacy inner.wake compatibility alias",
1310
+ providerLane: "inner",
1311
+ triggerSource: "legacy",
1312
+ budgetClass: "interactive",
1313
+ originRefs: [{ kind: "daemon-command", id: "inner.wake" }],
1314
+ };
1315
+ }
1316
+ const hasNoSendCapability = command.originRefs?.some((ref) => ref.kind === "capability" && ref.id === "no-send") ?? false;
1317
+ if ((command.noSend === true) !== hasNoSendCapability) {
1318
+ throw new Error("private-runtime no-send capability does not match its bound origin reference");
1319
+ }
1320
+ return {
1321
+ agent: command.agent,
1322
+ origin: "daemon.private.wake",
1323
+ reason: command.reason ?? "manual private-runtime wake",
1324
+ providerLane: "inner",
1325
+ triggerSource: command.triggerSource ?? "manual",
1326
+ budgetClass: command.budgetClass ?? "interactive",
1327
+ ...(command.idempotencyKey ? { idempotencyKey: command.idempotencyKey } : {}),
1328
+ originRefs: command.originRefs ?? [{ kind: "daemon-command", id: "private.wake" }],
1329
+ };
1330
+ }
1331
+ buildAwaitPrivateWakeCommand(command) {
1332
+ return (0, await_private_wake_1.buildAwaitPrivateWakeCommand)({
1333
+ agent: command.agent,
1334
+ awaitName: command.awaitName,
1335
+ triggerSource: "await-poke",
1336
+ });
1337
+ }
1338
+ buildTaskPokePrivateWakeCommand(command, receiptId) {
1339
+ return {
1340
+ kind: "private.wake",
1341
+ agent: command.agent,
1342
+ reason: `task poke ${command.taskId}`,
1343
+ triggerSource: "task-poke",
1344
+ budgetClass: "scheduled",
1345
+ idempotencyKey: `task-poke:${command.agent}:${command.taskId}:${receiptId}`,
1346
+ originRefs: [
1347
+ { kind: "task", id: command.taskId },
1348
+ { kind: "queue-receipt", id: receiptId },
1349
+ { kind: "daemon-command", id: "task.poke" },
1350
+ ],
1351
+ };
1352
+ }
1353
+ buildExternalEventPrivateWakeCommand(command, receiptId, generation, attemptCount) {
1354
+ return {
1355
+ kind: "private.wake",
1356
+ agent: command.agent,
1357
+ reason: `external event ${command.source}/${command.eventType}`,
1358
+ triggerSource: "external-event",
1359
+ budgetClass: "interactive",
1360
+ idempotencyKey: `external-event:${command.agent}:${command.source}:${command.eventId}:generation:${generation}:attempt:${attemptCount}`,
1361
+ originRefs: [
1362
+ { kind: "external-event", id: command.eventId, source: command.source, eventType: command.eventType },
1363
+ { kind: "queue-receipt", id: receiptId },
1364
+ { kind: "daemon-command", id: "external.event.submit" },
1365
+ ],
1366
+ };
1367
+ }
1368
+ resolveHabitDispatch(options) {
1369
+ const agentRoot = path.join(this.bundlesRoot, `${options.agent}.ouro`);
1370
+ const habitPath = path.join(agentRoot, "habits", `${options.habitName}.md`);
1371
+ const isRsvp = (0, habit_policy_1.isRsvpHabitName)(options.habitName);
1372
+ let readFailure = null;
1373
+ let habit;
1374
+ if (!fs.existsSync(habitPath)) {
1375
+ readFailure = "missing";
1376
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", "habit file not found");
1377
+ }
1378
+ else {
1379
+ try {
1380
+ habit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1381
+ }
1382
+ catch (error) {
1383
+ readFailure = "read";
1384
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", messageFromHabitPokeError(error));
1385
+ }
1386
+ }
1387
+ if (habit.status !== "active") {
1388
+ let skipReason = `habit status ${habit.status} is non-executable`;
1389
+ if (isRsvp && habit.status === "degraded") {
1390
+ if (readFailure === "missing") {
1391
+ skipReason = "RSVP habit file not found";
1392
+ }
1393
+ else {
1394
+ skipReason = `RSVP habit metadata invalid: ${habit.degradedDetail ?? habit.degradedReason}`;
1395
+ }
1396
+ }
1397
+ else if (readFailure === "missing"
1398
+ && options.source === "habit-poke"
1399
+ && options.trigger !== "manual"
1400
+ && options.trigger !== "poke") {
1401
+ skipReason = "habit file not found";
1402
+ }
1403
+ return { kind: "skipped", habit, skipReason };
1404
+ }
1405
+ if (isRsvp && !habit.rsvp) {
1406
+ return {
1407
+ kind: "skipped",
1408
+ habit,
1409
+ skipReason: "RSVP habit metadata is required before private runtime wake",
1410
+ };
1411
+ }
1412
+ if (options.trigger === "poke" || options.trigger === "manual") {
1413
+ return { kind: "ready", habit };
1414
+ }
1415
+ if (typeof options.occurrenceId === "string" && options.occurrenceId.trim().length > 0) {
1416
+ return { kind: "ready", habit, occurrenceId: options.occurrenceId.trim() };
1417
+ }
1418
+ if (habit.cadence === null) {
1419
+ return { kind: "skipped", habit, skipReason: "habit has no cadence" };
1420
+ }
1421
+ if (habit.lastRun === null) {
1422
+ return { kind: "ready", habit, occurrenceId: `${options.trigger}:first-run:${habit.cadence}` };
1423
+ }
1424
+ return {
1425
+ kind: "ready",
1426
+ habit,
1427
+ occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}`,
1428
+ };
1429
+ }
1430
+ emitHabitDispatchSkipped(options) {
1431
+ (0, runtime_1.emitNervesEvent)({
1432
+ level: "warn",
1433
+ component: "daemon",
1434
+ event: "daemon.habit_dispatch_skipped",
1435
+ message: "habit dispatch rejected by current lifecycle state",
1436
+ meta: {
1437
+ agent: options.agent,
1438
+ habitName: options.habitName,
1439
+ trigger: options.trigger,
1440
+ status: options.resolution.habit.status,
1441
+ degradedReason: options.resolution.habit.status === "degraded"
1442
+ ? options.resolution.habit.degradedReason
1443
+ : null,
1444
+ detail: options.resolution.habit.status === "degraded"
1445
+ ? options.resolution.habit.degradedDetail
1446
+ : null,
1447
+ reason: options.resolution.skipReason,
1448
+ },
1449
+ });
1450
+ }
1451
+ emitHabitDispatchReady(options) {
1452
+ (0, runtime_1.emitNervesEvent)({
1453
+ component: "daemon",
1454
+ event: "daemon.habit_dispatch_ready",
1455
+ message: "habit dispatch accepted by current lifecycle state",
1456
+ meta: {
1457
+ agent: options.agent,
1458
+ habitName: options.habitName,
1459
+ trigger: options.trigger,
1460
+ status: options.resolution.habit.status,
1461
+ occurrenceId: options.resolution.occurrenceId ?? null,
1462
+ },
1463
+ });
1464
+ }
1465
+ skippedHabitDispatchResponse(options) {
1466
+ return {
1467
+ ok: true,
1468
+ message: `skipped scheduled habit ${options.habitName} for ${options.agent}: ${options.skipReason}`,
1469
+ };
1470
+ }
1471
+ async runNativeRsvpHabit(command, trigger, occurrenceId, noSend = false) {
1472
+ const runner = this.rsvpHabitRunner ?? (async (input) => {
1473
+ const { runNativeRsvpHabit } = await Promise.resolve().then(() => __importStar(require("../../rsvp/native-habit-runner")));
1474
+ return runNativeRsvpHabit(input);
1475
+ });
1476
+ const result = await runner({
1477
+ agent: command.agent,
1478
+ bundlesRoot: this.bundlesRoot,
1479
+ habitName: command.habitName,
1480
+ trigger,
1481
+ ...(occurrenceId ? { occurrenceId } : {}),
1482
+ ...(noSend ? { noSend: true } : {}),
1483
+ });
1484
+ if (noSend) {
1485
+ const payload = result.payload;
1486
+ const status = payload?.status;
1487
+ const transportInvocationCount = payload?.transportInvocationCount;
1488
+ const contractError = "native RSVP habit probe violated the immutable no-send result contract";
1489
+ if (!result.ok) {
1490
+ return {
1491
+ ok: false,
1492
+ error: result.message,
1493
+ data: {
1494
+ ok: false,
1495
+ noSend: true,
1496
+ status: typeof status === "string" ? status : "degraded",
1497
+ transportInvocationCount: null,
1498
+ error: result.message,
1499
+ },
1500
+ };
1501
+ }
1502
+ if (payload?.noSend !== true
1503
+ || typeof status !== "string"
1504
+ || typeof transportInvocationCount !== "number"
1505
+ || transportInvocationCount !== 0) {
1506
+ return {
1507
+ ok: false,
1508
+ error: contractError,
1509
+ data: {
1510
+ ok: false,
1511
+ noSend: true,
1512
+ status: typeof status === "string" ? status : "degraded",
1513
+ transportInvocationCount: null,
1514
+ error: contractError,
1515
+ },
1516
+ };
1517
+ }
1518
+ return {
1519
+ ok: true,
1520
+ message: result.message,
1521
+ data: { noSend: true, status, transportInvocationCount: 0 },
1522
+ };
1523
+ }
1524
+ return {
1525
+ ok: result.ok,
1526
+ message: result.message,
1527
+ data: result,
1528
+ };
1529
+ }
1530
+ buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent) {
1531
+ const awaitName = (0, await_private_wake_1.awaitNameFromPrivateWakeCommand)(command);
1532
+ if (awaitName) {
1533
+ return {
1534
+ type: "await",
1535
+ awaitName,
1536
+ privateTurnDecision: decision,
1537
+ };
1538
+ }
1539
+ const taskId = taskIdFromTaskPokePrivateWakeCommand(command);
1540
+ if (taskId) {
1541
+ return {
1542
+ type: "poke",
1543
+ taskId,
1544
+ privateTurnDecision: decision,
1545
+ };
1546
+ }
1547
+ const habitMessage = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1548
+ if (habitMessage) {
1549
+ return {
1550
+ type: "habit",
1551
+ habitName: habitMessage.habitName,
1552
+ trigger: habitMessage.trigger,
1553
+ ...(habitMessage.noSend ? { noSend: true } : {}),
1554
+ privateTurnDecision: decision,
1555
+ };
1556
+ }
1557
+ return { type: "message", privateTurnDecision: decision, ...(externalEvent ? { externalEvent } : {}) };
1558
+ }
1559
+ queueOperatorCliMessageForPrivateRuntime(command) {
1560
+ if (command.kind !== "private.wake" || command.triggerSource !== "operator-cli")
1561
+ return;
1562
+ const receiptId = command.originRefs?.find((ref) => ref.kind === "daemon-receipt")?.id;
1563
+ if (!receiptId)
1564
+ return;
1565
+ const messages = this.router.peekInbox?.(command.agent) ?? [];
1566
+ const routed = messages.find((message) => message.id === receiptId);
1567
+ if (!routed)
1568
+ return;
1569
+ const pendingDir = path.join(this.bundlesRoot, `${command.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1570
+ const queuedAtMs = Date.parse(routed.queuedAt);
1571
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1572
+ from: routed.from,
1573
+ content: routed.content,
1574
+ timestamp: Number.isFinite(queuedAtMs) ? queuedAtMs : Date.now(),
1575
+ mode: "relay",
1576
+ requestId: routed.id,
1577
+ packetId: `operator-cli:${command.agent}:${routed.id}`,
1578
+ });
1579
+ }
1580
+ queueExternalEventForPrivateRuntime(record, quiet = false) {
1581
+ const pendingDir = path.join(this.bundlesRoot, `${record.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1582
+ const originKey = `${record.source}:${record.eventId}`;
1583
+ const parsedReceivedAt = Date.parse(record.receivedAt);
1584
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1585
+ from: "ouro-external-event",
1586
+ friendId: "ouro-external-event",
1587
+ channel: "external-event",
1588
+ key: originKey,
1589
+ content: (0, router_1.buildExternalEventMessage)(record),
1590
+ timestamp: Number.isFinite(parsedReceivedAt) ? parsedReceivedAt : Date.now(),
1591
+ delegatedFrom: {
1592
+ friendId: "ouro-external-event",
1593
+ channel: "external-event",
1594
+ key: originKey,
1595
+ },
1596
+ obligationStatus: "pending",
1597
+ mode: "relay",
1598
+ packetId: `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount}`,
1599
+ });
1600
+ if (!quiet) {
1601
+ (0, runtime_1.emitNervesEvent)({
1602
+ component: "daemon",
1603
+ event: "daemon.external_event_private_runtime_queued",
1604
+ message: "queued external event for private-runtime attention",
1605
+ meta: {
1606
+ agent: record.agent,
1607
+ source: record.source,
1608
+ eventType: record.eventType,
1609
+ eventId: record.eventId,
1610
+ pendingDir,
1611
+ },
1612
+ });
1613
+ }
1614
+ }
1615
+ externalEventRootPath() {
1616
+ return this.externalEventRoot ?? (0, router_1.getExternalEventRoot)();
1617
+ }
1618
+ externalEventLease(record) {
1619
+ /* v8 ignore next -- dispatcher calls this only with the record returned by claimExternalEvent @preserve */
1620
+ if (!record.claimOwner)
1621
+ throw new Error("External event dispatch requires a claimed receipt");
1622
+ return {
1623
+ schemaVersion: 1,
1624
+ recordPath: record.recordPath,
1625
+ agent: record.agent,
1626
+ source: record.source,
1627
+ eventId: record.eventId,
1628
+ generation: record.generation,
1629
+ observationRevision: record.observationRevision,
1630
+ claimOwner: record.claimOwner,
1631
+ };
1632
+ }
1633
+ async dispatchExternalEvents(records) {
1634
+ const claimed = [];
1635
+ let failureClass;
1636
+ try {
1637
+ for (const key of new Set(records.map((record) => `${record.agent}\0${record.source}`))) {
1638
+ const [agent, source] = key.split("\0");
1639
+ await this.externalEventSourceReadiness(agent, source);
1640
+ }
1641
+ for (const record of records) {
1642
+ const owner = `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount + 1}`;
1643
+ claimed.push((0, router_1.claimExternalEvent)(record.recordPath, { owner, expectedVersion: record.version, expectedGeneration: record.generation }));
1644
+ }
1645
+ const primary = claimed[0];
1646
+ const [primaryLease, ...relatedEvents] = claimed.map((record) => this.externalEventLease(record));
1647
+ const lease = { ...primaryLease, ...(relatedEvents.length > 0 ? { relatedEvents } : {}) };
1648
+ const receipt = {
1649
+ id: `external-event:${primary.agent}:${primary.source}:${primary.eventId}:generation:${primary.generation}:attempt:${primary.attemptCount}`,
1650
+ queuedAt: primary.updatedAt,
1651
+ };
1652
+ const wake = await this.handlePrivateRuntimeWake(this.buildExternalEventPrivateWakeCommand({
1653
+ kind: "external.event.submit",
1654
+ agent: primary.agent,
1655
+ source: primary.source,
1656
+ eventType: primary.eventType,
1657
+ eventId: primary.eventId,
1658
+ }, receipt.id, primary.generation, primary.attemptCount), () => {
1659
+ const batched = claimed.length > 1;
1660
+ for (const record of claimed)
1661
+ this.queueExternalEventForPrivateRuntime(record, batched);
1662
+ if (batched) {
1663
+ (0, runtime_1.emitNervesEvent)({
1664
+ component: "daemon",
1665
+ event: "daemon.external_event_private_runtime_batch_queued",
1666
+ message: "queued an external-event batch for private-runtime attention",
1667
+ meta: { agent: primary.agent, source: primary.source, eventCount: claimed.length },
1668
+ });
1669
+ }
1670
+ }, lease);
1671
+ failureClass = wake.denialCode === "managed_runtime_unavailable"
1672
+ ? "managed_runtime_unavailable"
1673
+ : wake.data?.decision?.denialCode === "provider_lane_unavailable"
1674
+ ? "provider_lane_unavailable"
1675
+ : undefined;
1676
+ const denied = !wake.ok || wake.data?.decision?.executable === false;
1677
+ if (denied)
1678
+ throw new Error(wake.error ?? wake.message ?? /* v8 ignore next -- daemon wake responses always carry an error or message @preserve */ "external-event private turn was denied");
1679
+ return { events: claimed, event: primary, receipt, wake };
1680
+ }
1681
+ catch (error) {
1682
+ for (const record of claimed) {
1683
+ (0, router_1.settleExternalEventFailureIfOwned)(record.recordPath, {
1684
+ owner: record.claimOwner, expectedGeneration: record.generation,
1685
+ error: failureClass ? `external-event private-runtime dispatch failed: ${failureClass}` : "external-event private-runtime dispatch failed",
1686
+ ...(failureClass ? { failureClass } : {}),
1687
+ });
1688
+ }
1689
+ throw error;
1690
+ }
1691
+ }
1692
+ dispatchExternalEvent(record) {
1693
+ return this.dispatchExternalEvents([record]);
1694
+ }
1695
+ async reconcileExternalEvents() {
1696
+ /* v8 ignore next -- re-entrancy guard is exercised only by overlapping real timer callbacks @preserve */
1697
+ if (this.externalEventReconcileRunning)
1698
+ return;
1699
+ this.externalEventReconcileRunning = true;
1700
+ try {
1701
+ const now = new Date().toISOString();
1702
+ if (fs.existsSync(this.privilegedEventSpoolRoot)) {
1703
+ this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath() });
1704
+ }
1705
+ const scanned = this.externalEventScanCache.scan(this.externalEventRootPath());
1706
+ const readinessKeys = new Set();
1707
+ for (const { record: candidate } of scanned) {
1708
+ if (!candidate)
1709
+ continue;
1710
+ if (candidate.dispatchEnabled === false)
1711
+ continue;
1712
+ const retryDue = candidate.executionState === "retry_wait" && candidate.nextAttemptAt !== null && Date.parse(candidate.nextAttemptAt) <= Date.parse(now);
1713
+ const leaseExpired = candidate.executionState === "running" && candidate.claimExpiresAt !== null && Date.parse(candidate.claimExpiresAt) <= Date.parse(now);
1714
+ const recoverableDeadLetter = candidate.executionState === "dead_letter"
1715
+ && (0, router_1.externalEventRecoveryFailure)(candidate) !== null
1716
+ && candidate.recoveryGrant?.generation !== candidate.generation;
1717
+ const dispatchable = candidate.executionState === "received" || candidate.executionState === "queued" || retryDue || leaseExpired || recoverableDeadLetter;
1718
+ if (dispatchable && (candidate.source === "sanctuary-health" || candidate.source === "sanctuary-usenet"))
1719
+ readinessKeys.add(`${candidate.agent}\0${candidate.source}`);
1720
+ }
1721
+ const blockedReadinessKeys = new Set();
1722
+ for (const key of readinessKeys) {
1723
+ const [agent, source] = key.split("\0");
1724
+ try {
1725
+ await this.externalEventSourceReadiness(agent, source);
1726
+ }
1727
+ catch (error) {
1728
+ blockedReadinessKeys.add(key);
1729
+ (0, runtime_1.emitNervesEvent)({
1730
+ level: "warn",
1731
+ component: "daemon",
1732
+ event: "daemon.external_event_readiness_blocked",
1733
+ message: "external-event reconciliation is waiting for source runtime readiness",
1734
+ meta: { agent, source, error: (error instanceof Error ? error.message : String(error)).slice(0, 1_000) },
1735
+ });
1736
+ }
1737
+ }
1738
+ const dueRecords = [];
1739
+ const providerEvidenceByAgent = new Map();
1740
+ const runtimeEvidenceByAgent = new Map();
1741
+ const recoveredByClass = new Map();
1742
+ for (const { record: scannedRecord } of scanned) {
1743
+ if (!scannedRecord)
1744
+ continue;
1745
+ let record = scannedRecord;
1746
+ if (record.dispatchEnabled === false)
1747
+ continue;
1748
+ if (blockedReadinessKeys.has(`${record.agent}\0${record.source}`))
1749
+ continue;
1750
+ if (record.executionState === "dead_letter") {
1751
+ const failure = (0, router_1.externalEventRecoveryFailure)(record);
1752
+ if (!failure || record.recoveryGrant?.generation === record.generation)
1753
+ continue;
1754
+ let evidence = null;
1755
+ try {
1756
+ if (failure.class === "provider_lane_unavailable") {
1757
+ if (!providerEvidenceByAgent.has(record.agent)) {
1758
+ providerEvidenceByAgent.set(record.agent, null);
1759
+ const binding = (0, provider_binding_resolver_1.resolveEffectiveProviderBinding)({
1760
+ agentName: record.agent,
1761
+ agentRoot: path.join(this.bundlesRoot, `${record.agent}.ouro`),
1762
+ lane: "inner",
1763
+ });
1764
+ providerEvidenceByAgent.set(record.agent, binding.ok && binding.binding.credential.status === "present"
1765
+ && binding.binding.readiness.status === "ready" && binding.binding.readiness.checkedAt
1766
+ ? { observedAt: binding.binding.readiness.checkedAt }
1767
+ : null);
1768
+ }
1769
+ const current = providerEvidenceByAgent.get(record.agent);
1770
+ const readinessIsCurrentBoot = current && Date.parse(current.observedAt) >= this.constructedAtMs;
1771
+ if (current && ((0, router_1.isExactLegacyProviderRecoveryFailure)(record)
1772
+ ? readinessIsCurrentBoot
1773
+ : Date.parse(current.observedAt) > Date.parse(failure.failedAt))) {
1774
+ evidence = { class: failure.class, observedAt: current.observedAt };
1775
+ }
1776
+ }
1777
+ else if (failure.class === "execution_lease_expired") {
1778
+ if (!runtimeEvidenceByAgent.has(record.agent)) {
1779
+ const snapshot = this.processManager.listAgentSnapshots().find((candidate) => candidate.name === record.agent && candidate.channel === "private-runtime"
1780
+ && candidate.status === "running" && candidate.pid !== null && candidate.startedAt !== null);
1781
+ runtimeEvidenceByAgent.set(record.agent, snapshot?.startedAt ? { observedAt: snapshot.startedAt } : null);
1782
+ }
1783
+ const current = runtimeEvidenceByAgent.get(record.agent);
1784
+ if (current && Date.parse(current.observedAt) > Date.parse(failure.failedAt)) {
1785
+ evidence = { class: failure.class, observedAt: current.observedAt };
1786
+ }
1787
+ }
1788
+ else if (this.hasManagedPrivateRuntime(record.agent) && Date.parse(now) > Date.parse(failure.failedAt)) {
1789
+ evidence = { class: failure.class, observedAt: now };
1790
+ }
1791
+ if (!evidence)
1792
+ continue;
1793
+ const revival = (0, router_1.reviveExternalEventAfterRecovery)(record.recordPath, { expectedVersion: record.version, expectedGeneration: record.generation, evidence, now: () => now, quiet: true });
1794
+ record = revival.record;
1795
+ recoveredByClass.set(failure.class, (recoveredByClass.get(failure.class) ?? 0) + 1);
1796
+ }
1797
+ catch (error) {
1798
+ (0, runtime_1.emitNervesEvent)({
1799
+ level: "warn",
1800
+ component: "daemon",
1801
+ event: "daemon.external_event_recovery_error",
1802
+ message: "external event dead-letter recovery check failed",
1803
+ meta: { agent: record.agent, source: record.source, eventId: record.eventId, generation: record.generation, error: error instanceof Error ? error.message : String(error) },
1804
+ });
1805
+ continue;
1806
+ }
1807
+ }
1808
+ if (record.executionState === "running" && record.claimExpiresAt && Date.parse(record.claimExpiresAt) <= Date.parse(now)) {
1809
+ record = (0, router_1.reconcileExternalEvent)(record.recordPath);
1810
+ }
1811
+ const due = record.executionState === "received"
1812
+ || record.executionState === "queued"
1813
+ || (record.executionState === "retry_wait" && record.nextAttemptAt !== null && Date.parse(record.nextAttemptAt) <= Date.parse(now));
1814
+ if (due)
1815
+ dueRecords.push(record);
1816
+ }
1817
+ if (recoveredByClass.size > 0) {
1818
+ (0, runtime_1.emitNervesEvent)({
1819
+ component: "daemon",
1820
+ event: "daemon.external_event_recovery_batch",
1821
+ message: "requeued external events after cached infrastructure recovery evidence",
1822
+ meta: { recovered: Object.fromEntries(recoveredByClass) },
1823
+ });
1824
+ }
1825
+ const batches = new Map();
1826
+ for (const record of dueRecords) {
1827
+ const key = `${record.agent}\0${record.source}`;
1828
+ const batch = batches.get(key) ?? [];
1829
+ batch.push(record);
1830
+ batches.set(key, batch);
1831
+ }
1832
+ for (const records of batches.values()) {
1833
+ for (let offset = 0; offset < records.length; offset += 32) {
1834
+ const batch = records.slice(offset, offset + 32);
1835
+ try {
1836
+ await this.dispatchExternalEvents(batch);
1837
+ }
1838
+ catch (error) {
1839
+ (0, runtime_1.emitNervesEvent)({
1840
+ level: "warn",
1841
+ component: "daemon",
1842
+ event: "daemon.external_event_dispatch_error",
1843
+ message: "external event dispatch failed",
1844
+ meta: { recordPath: batch[0].recordPath, batchSize: batch.length, error: error instanceof Error ? error.message : /* v8 ignore next -- dispatch failures are Error objects @preserve */ String(error) },
1845
+ });
1846
+ }
1847
+ }
1848
+ }
1849
+ }
1850
+ finally {
1851
+ this.externalEventReconcileRunning = false;
1852
+ }
1853
+ }
1854
+ async handlePrivateRuntimeWake(command, beforeDispatch, externalEvent) {
1855
+ if (!this.hasManagedPrivateRuntime(command.agent)) {
1856
+ return {
1857
+ ok: false,
1858
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1859
+ denialCode: "managed_runtime_unavailable",
1860
+ };
1861
+ }
1862
+ const decision = await (0, private_runtime_1.requestPrivateTurnDecision)(this.buildPrivateRuntimeWakeRequest(command), {
1863
+ bundlesRoot: this.bundlesRoot,
1864
+ ...this.privateRuntimePolicyDeps,
1865
+ });
1866
+ if (!decision.executable) {
1867
+ return {
1868
+ ok: true,
1869
+ message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
1870
+ ...(decision.denialCode ? { denialCode: decision.denialCode } : {}),
1871
+ data: { decision },
1872
+ };
1873
+ }
1874
+ this.queueOperatorCliMessageForPrivateRuntime(command);
1875
+ await beforeDispatch?.(decision);
1876
+ await this.processManager.startAgent(command.agent);
1877
+ const message = this.buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent);
1878
+ if (this.processManager.dispatchToAgent)
1879
+ await this.processManager.dispatchToAgent(command.agent, message);
1880
+ else
1881
+ this.processManager.sendToAgent?.(command.agent, message);
1882
+ return {
1883
+ ok: true,
1884
+ message: `woke private runtime for ${command.agent}`,
1885
+ data: { decision },
1886
+ };
1887
+ }
1888
+ async handleCommandInner(command) {
211
1889
  switch (command.kind) {
212
1890
  case "daemon.start":
213
1891
  await this.start();
214
1892
  return { ok: true, message: "daemon started" };
215
1893
  case "daemon.stop":
216
- await this.stop();
1894
+ try {
1895
+ await this.stop();
1896
+ }
1897
+ finally {
1898
+ await this.onStopCommandComplete?.();
1899
+ }
217
1900
  return { ok: true, message: "daemon stopped" };
1901
+ case "daemon.restart": {
1902
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1903
+ // policy the process is auto-restarted on exit, so daemon.restart and
1904
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1905
+ // the process simply exits — same observable behavior as daemon.stop.
1906
+ (0, runtime_1.emitNervesEvent)({
1907
+ component: "daemon",
1908
+ event: "daemon.restart_requested",
1909
+ message: "daemon restart requested",
1910
+ meta: {
1911
+ reason: command.reason ?? null,
1912
+ requestedBy: command.requestedBy ?? null,
1913
+ },
1914
+ });
1915
+ try {
1916
+ await this.stop();
1917
+ }
1918
+ finally {
1919
+ await this.onStopCommandComplete?.();
1920
+ }
1921
+ return {
1922
+ ok: true,
1923
+ message: "daemon restarting — launchctl will respawn",
1924
+ };
1925
+ }
218
1926
  case "daemon.status": {
219
- const snapshots = this.processManager.listAgentSnapshots();
1927
+ const data = this.buildStatusPayload();
220
1928
  return {
221
1929
  ok: true,
222
- summary: formatStatusSummary(snapshots),
223
- data: snapshots,
1930
+ summary: formatStatusSummary(data),
1931
+ data,
224
1932
  };
225
1933
  }
226
1934
  case "daemon.health": {
@@ -233,17 +1941,114 @@ class OuroDaemon {
233
1941
  ok: true,
234
1942
  summary: "logs: use `ouro logs` to tail daemon and agent output",
235
1943
  message: "log streaming available via ouro logs",
236
- data: { logDir: "~/.agentstate/daemon/logs" },
1944
+ data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
237
1945
  };
1946
+ case "daemon.sense_revive": {
1947
+ if (!isValidSenseReviveCommand(command)) {
1948
+ return {
1949
+ ok: false,
1950
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
1951
+ };
1952
+ }
1953
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
1954
+ if (revivedSenseRow) {
1955
+ return {
1956
+ ok: true,
1957
+ message: `revived ${command.agent}/${command.sense}`,
1958
+ data: revivedSenseRow,
1959
+ };
1960
+ }
1961
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
1962
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
1963
+ if (managedSenseSnapshots.length === 0) {
1964
+ return {
1965
+ ok: false,
1966
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
1967
+ };
1968
+ }
1969
+ const exactTargetName = `${command.agent}:${command.sense}`;
1970
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
1971
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
1972
+ if (!target) {
1973
+ return {
1974
+ ok: false,
1975
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
1976
+ };
1977
+ }
1978
+ this.processManager.resetAgentFailureState(target.name);
1979
+ await this.processManager.startAgent(target.name);
1980
+ const freshSnapshot = this.processManager.listAgentSnapshots()
1981
+ .find((snapshot) => snapshot.name === target.name) ?? target;
1982
+ return {
1983
+ ok: true,
1984
+ message: `revived ${command.agent}/${command.sense}`,
1985
+ data: freshSnapshot,
1986
+ };
1987
+ }
238
1988
  case "agent.start":
239
1989
  await this.processManager.startAgent(command.agent);
240
1990
  return { ok: true, message: `started ${command.agent}` };
241
1991
  case "agent.stop":
242
1992
  await this.processManager.stopAgent?.(command.agent);
243
1993
  return { ok: true, message: `stopped ${command.agent}` };
244
- case "agent.restart":
245
- await this.processManager.restartAgent?.(command.agent);
246
- return { ok: true, message: `restarted ${command.agent}` };
1994
+ case "agent.restart": {
1995
+ if (!this.processManager.restartAgent) {
1996
+ return { ok: false, error: "Managed agent restart is not available." };
1997
+ }
1998
+ const managedSnapshot = this.processManager.listAgentSnapshots()
1999
+ .find((snapshot) => snapshot.name === command.agent);
2000
+ if (!managedSnapshot) {
2001
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
2002
+ }
2003
+ if (managedSnapshot.autoStart === false && managedSnapshot.status === "stopped") {
2004
+ return { ok: true, message: `restart skipped for parked non-autostart agent '${command.agent}'` };
2005
+ }
2006
+ const restartWork = command.skipConfigCheck === true
2007
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
2008
+ : this.processManager.restartAgent(command.agent);
2009
+ void restartWork.catch((error) => {
2010
+ (0, runtime_1.emitNervesEvent)({
2011
+ level: "error",
2012
+ component: "daemon",
2013
+ event: "daemon.agent_restart_request_error",
2014
+ message: "managed agent restart failed after request acknowledgement",
2015
+ meta: {
2016
+ agent: command.agent,
2017
+ error: error instanceof Error ? error.message : String(error),
2018
+ },
2019
+ });
2020
+ });
2021
+ return { ok: true, message: `restart requested for ${command.agent}` };
2022
+ }
2023
+ case "agent.ask":
2024
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
2025
+ case "agent.status":
2026
+ return (0, agent_service_1.handleAgentStatus)(command);
2027
+ case "agent.catchup":
2028
+ return (0, agent_service_1.handleAgentCatchup)(command);
2029
+ case "agent.delegate":
2030
+ return (0, agent_service_1.handleAgentDelegate)(command);
2031
+ case "agent.getContext":
2032
+ return (0, agent_service_1.handleAgentGetContext)(command);
2033
+ case "agent.searchFacts":
2034
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
2035
+ case "agent.getTask":
2036
+ return (0, agent_service_1.handleAgentGetTask)(command);
2037
+ case "agent.checkScope":
2038
+ return (0, agent_service_1.handleAgentCheckScope)(command);
2039
+ case "agent.requestDecision":
2040
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
2041
+ case "agent.checkGuidance":
2042
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
2043
+ case "agent.reportProgress":
2044
+ return (0, agent_service_1.handleAgentReportProgress)(command);
2045
+ case "agent.reportBlocker":
2046
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
2047
+ case "agent.reportComplete":
2048
+ return (0, agent_service_1.handleAgentReportComplete)(command);
2049
+ case "agent.senseTurn":
2050
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
2051
+ /* v8 ignore stop */
247
2052
  case "cron.list": {
248
2053
  const jobs = this.scheduler.listJobs();
249
2054
  const summary = jobs.length === 0
@@ -252,10 +2057,28 @@ class OuroDaemon {
252
2057
  return { ok: true, summary, data: jobs };
253
2058
  }
254
2059
  case "cron.trigger": {
2060
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
2061
+ if (habitResult?.ok) {
2062
+ return { ok: true, message: habitResult.message };
2063
+ }
255
2064
  const result = await this.scheduler.triggerJob(command.jobId);
256
2065
  return { ok: result.ok, message: result.message };
257
2066
  }
258
2067
  case "message.send": {
2068
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
2069
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
2070
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
2071
+ // events to avoid waking the agent on every tool call. The hook's
2072
+ // intent was completely defeated by this handler calling
2073
+ // `sendToAgent({type: "message"})`, which woke the private runtime
2074
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
2075
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
2076
+ //
2077
+ // Callers that want immediate processing must send `private.wake`
2078
+ // explicitly after message.send. The CLI `ouro msg` does so
2079
+ // (lifecycle-boundary delivery should wake); the hook does so
2080
+ // only on session-start / stop, not per tool-use; the API does
2081
+ // not (notifications go to the queue).
259
2082
  const receipt = await this.router.send({
260
2083
  from: command.from,
261
2084
  to: command.to,
@@ -264,7 +2087,6 @@ class OuroDaemon {
264
2087
  sessionId: command.sessionId,
265
2088
  taskRef: command.taskRef,
266
2089
  });
267
- this.processManager.sendToAgent?.(command.to, { type: "message" });
268
2090
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
269
2091
  }
270
2092
  case "message.poll": {
@@ -275,6 +2097,127 @@ class OuroDaemon {
275
2097
  data: messages,
276
2098
  };
277
2099
  }
2100
+ case "external.event.submit": {
2101
+ const record = (0, router_1.recordExternalEvent)({
2102
+ agent: command.agent,
2103
+ source: command.source,
2104
+ eventType: command.eventType,
2105
+ eventId: command.eventId,
2106
+ summary: command.summary,
2107
+ evidence: command.evidence,
2108
+ payloadPath: command.payloadPath,
2109
+ priority: command.priority,
2110
+ observationRevision: command.observationRevision,
2111
+ transition: command.transition,
2112
+ }, {
2113
+ ...(this.externalEventRoot ? { root: this.externalEventRoot } : {}),
2114
+ dispatchEnabled: command.wake !== false,
2115
+ });
2116
+ if (!record.shouldWake || command.wake === false) {
2117
+ return {
2118
+ ok: true,
2119
+ message: `updated external event ${record.source}/${record.eventId} without wake`,
2120
+ data: { event: record, receipt: null, wake: null },
2121
+ };
2122
+ }
2123
+ const dispatched = await this.dispatchExternalEvent(record);
2124
+ return {
2125
+ ok: true,
2126
+ message: `queued external event ${record.source}/${record.eventId} as ${dispatched.receipt.id}; ${dispatched.wake.message ?? "wake skipped"}`,
2127
+ data: dispatched,
2128
+ };
2129
+ }
2130
+ case "external.event.repair": {
2131
+ if (this.externalEventReconcileRunning)
2132
+ return { ok: false, error: "external event reconciliation is already active; repair made no changes" };
2133
+ this.externalEventReconcileRunning = true;
2134
+ try {
2135
+ try {
2136
+ const result = (0, router_1.repairExternalEventsFromManifest)(command.manifestPath, { root: this.externalEventRootPath() });
2137
+ return { ok: result.failed.length === 0, message: `external event repair applied=${result.applied.length} alreadyApplied=${result.alreadyApplied.length} failed=${result.failed.length} pending=${result.pending.length}`, data: result };
2138
+ }
2139
+ catch (error) {
2140
+ const message = (error instanceof Error ? error.message : /* v8 ignore next -- defensive: repair parser and filesystem dependencies throw Error instances @preserve */ String(error)).slice(0, 1_000);
2141
+ const result = { applied: [], alreadyApplied: [], failed: [{ identity: "<manifest>", error: message }], pending: [] };
2142
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.external_event_repair", message: "rejected external event repair manifest", meta: { applied: 0, alreadyApplied: 0, failed: 1, pending: 0 } });
2143
+ return { ok: false, error: `external event repair rejected: ${message}`, data: result };
2144
+ }
2145
+ }
2146
+ finally {
2147
+ this.externalEventReconcileRunning = false;
2148
+ }
2149
+ }
2150
+ case "private.decisions": {
2151
+ const requestedLimit = Number.isInteger(command.limit) && command.limit && command.limit > 0 ? command.limit : 20;
2152
+ const limit = Math.min(requestedLimit, 1000);
2153
+ const ledgerPath = (0, private_runtime_1.privateTurnLedgerPath)(command.agent, { bundlesRoot: this.bundlesRoot });
2154
+ const ledgerExists = fs.existsSync(ledgerPath);
2155
+ let decisions;
2156
+ try {
2157
+ decisions = ledgerExists ? (0, private_runtime_1.readPrivateTurnLedger)(ledgerPath) : [];
2158
+ }
2159
+ catch {
2160
+ return {
2161
+ ok: false,
2162
+ error: `private-runtime decision ledger is malformed: ${ledgerPath}; repair or remove malformed JSONL rows before reading decisions`,
2163
+ };
2164
+ }
2165
+ const guidance = ledgerExists
2166
+ ? undefined
2167
+ : `No private-runtime decision ledger exists for ${command.agent}; run an explicit private-runtime trigger or check ${path.dirname(ledgerPath)}.`;
2168
+ const payload = (0, private_runtime_1.buildPrivateDecisionReadPayload)({
2169
+ agent: command.agent,
2170
+ ledgerPath,
2171
+ decisions,
2172
+ limit,
2173
+ ...(guidance ? { guidance } : {}),
2174
+ });
2175
+ return {
2176
+ ok: true,
2177
+ summary: (0, private_runtime_1.privateDecisionCountSummary)(payload.decisions.length),
2178
+ ...(guidance ? { message: guidance } : {}),
2179
+ data: payload,
2180
+ };
2181
+ }
2182
+ case "inner.wake":
2183
+ return this.handlePrivateRuntimeWake(command);
2184
+ case "private.wake": {
2185
+ const scheduledHabit = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
2186
+ if (!scheduledHabit || !this.hasManagedPrivateRuntime(command.agent)) {
2187
+ return this.handlePrivateRuntimeWake(command);
2188
+ }
2189
+ const occurrenceRef = command.originRefs?.find((ref) => ref.kind === "habit-occurrence");
2190
+ const occurrenceId = typeof occurrenceRef?.id === "string" && occurrenceRef.id.trim().length > 0
2191
+ ? occurrenceRef.id.trim()
2192
+ : undefined;
2193
+ const resolution = this.resolveHabitDispatch({
2194
+ agent: command.agent,
2195
+ habitName: scheduledHabit.habitName,
2196
+ trigger: scheduledHabit.trigger,
2197
+ source: "private-wake",
2198
+ ...(occurrenceId ? { occurrenceId } : {}),
2199
+ });
2200
+ if (resolution.kind === "skipped") {
2201
+ this.emitHabitDispatchSkipped({
2202
+ agent: command.agent,
2203
+ habitName: scheduledHabit.habitName,
2204
+ trigger: scheduledHabit.trigger,
2205
+ resolution,
2206
+ });
2207
+ return this.skippedHabitDispatchResponse({
2208
+ agent: command.agent,
2209
+ habitName: scheduledHabit.habitName,
2210
+ skipReason: resolution.skipReason,
2211
+ });
2212
+ }
2213
+ this.emitHabitDispatchReady({
2214
+ agent: command.agent,
2215
+ habitName: scheduledHabit.habitName,
2216
+ trigger: scheduledHabit.trigger,
2217
+ resolution,
2218
+ });
2219
+ return this.handlePrivateRuntimeWake(command);
2220
+ }
278
2221
  case "chat.connect":
279
2222
  await this.processManager.startAgent(command.agent);
280
2223
  return {
@@ -282,6 +2225,12 @@ class OuroDaemon {
282
2225
  message: `connected to ${command.agent}`,
283
2226
  };
284
2227
  case "task.poke": {
2228
+ if (!isValidTaskPokeCommand(command)) {
2229
+ return {
2230
+ ok: false,
2231
+ error: "Invalid task.poke payload: expected non-empty string fields 'agent' and 'taskId'.",
2232
+ };
2233
+ }
285
2234
  const receipt = await this.router.send({
286
2235
  from: "ouro-poke",
287
2236
  to: command.agent,
@@ -290,17 +2239,253 @@ class OuroDaemon {
290
2239
  taskRef: command.taskId,
291
2240
  });
292
2241
  await this.scheduler.recordTaskRun?.(command.agent, command.taskId);
293
- this.processManager.sendToAgent?.(command.agent, { type: "poke", taskId: command.taskId });
2242
+ await this.handlePrivateRuntimeWake(this.buildTaskPokePrivateWakeCommand(command, receipt.id));
294
2243
  return {
295
2244
  ok: true,
296
2245
  message: `queued poke ${receipt.id}`,
297
2246
  data: receipt,
298
2247
  };
299
2248
  }
2249
+ case "habit.scheduler-fire": {
2250
+ if (!this.schedulerFireVerifier || !this.schedulerFireConsumer)
2251
+ return { ok: false, error: "authenticated scheduler fire is unavailable" };
2252
+ let origin;
2253
+ try {
2254
+ origin = this.schedulerFireVerifier(command);
2255
+ this.schedulerFireConsumer(origin);
2256
+ }
2257
+ catch (error) {
2258
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2259
+ }
2260
+ const poke = { kind: "habit.poke", agent: command.agent, habitName: command.habitName, trigger: "cron", occurrenceId: origin.occurrenceId };
2261
+ this.authenticatedSchedulerPokes.set(poke, origin);
2262
+ try {
2263
+ return await this.handleCommand(poke);
2264
+ }
2265
+ finally {
2266
+ this.authenticatedSchedulerPokes.delete(poke);
2267
+ }
2268
+ }
2269
+ case "habit.poke": {
2270
+ if (!isValidHabitPokeCommand(command)) {
2271
+ return {
2272
+ ok: false,
2273
+ error: "Invalid habit.poke payload: expected non-empty string fields 'agent' and 'habitName'.",
2274
+ };
2275
+ }
2276
+ const trigger = command.trigger ?? "poke";
2277
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
2278
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
2279
+ }
2280
+ const schedulerOrigin = this.authenticatedSchedulerPokes.get(command);
2281
+ if (command.agent === "sanctuary" && command.habitName === "sanctuary-health" && trigger === "cron" && !schedulerOrigin) {
2282
+ return { ok: false, error: "Sanctuary cron habit requires authenticated Supercronic provenance" };
2283
+ }
2284
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2285
+ return {
2286
+ ok: false,
2287
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2288
+ };
2289
+ }
2290
+ const resolution = this.resolveHabitDispatch({
2291
+ agent: command.agent,
2292
+ habitName: command.habitName,
2293
+ trigger,
2294
+ source: "habit-poke",
2295
+ ...(command.occurrenceId ? { occurrenceId: command.occurrenceId } : {}),
2296
+ });
2297
+ if (resolution.kind === "skipped") {
2298
+ this.emitHabitDispatchSkipped({
2299
+ agent: command.agent,
2300
+ habitName: command.habitName,
2301
+ trigger,
2302
+ resolution,
2303
+ });
2304
+ return this.skippedHabitDispatchResponse({
2305
+ agent: command.agent,
2306
+ habitName: command.habitName,
2307
+ skipReason: resolution.skipReason,
2308
+ });
2309
+ }
2310
+ this.emitHabitDispatchReady({
2311
+ agent: command.agent,
2312
+ habitName: command.habitName,
2313
+ trigger,
2314
+ resolution,
2315
+ });
2316
+ if (this.nativeHabitRunner && this.nativeHabitMatch?.(command.agent, command.habitName)) {
2317
+ const occurrenceId = resolution.occurrenceId ?? `${trigger}:${command.agent}:${command.habitName}`;
2318
+ const claimKey = `${command.agent}:${command.habitName}`;
2319
+ if (this.nativeHabitClaims.has(claimKey)) {
2320
+ return { ok: true, message: `skipped overlapping native habit occurrence ${occurrenceId}` };
2321
+ }
2322
+ this.nativeHabitClaims.add(claimKey);
2323
+ const startedAt = new Date().toISOString();
2324
+ const runnerId = (0, node_crypto_1.randomUUID)();
2325
+ let nativeResult;
2326
+ try {
2327
+ nativeResult = await this.nativeHabitRunner({
2328
+ agent: command.agent,
2329
+ habitName: command.habitName,
2330
+ trigger,
2331
+ occurrenceId,
2332
+ runnerId,
2333
+ ...(schedulerOrigin ? { schedulerOrigin } : {}),
2334
+ }) ?? { ok: false, error: "native habit runner declined a matched habit" };
2335
+ }
2336
+ catch (error) {
2337
+ nativeResult = { ok: false, error: error instanceof Error ? error.message : String(error) };
2338
+ }
2339
+ const endedAt = new Date().toISOString();
2340
+ let completion;
2341
+ try {
2342
+ completion = (0, habit_session_1.completeHabitRun)({
2343
+ agentRoot: path.join(this.bundlesRoot, `${command.agent}.ouro`),
2344
+ habit: resolution.habit,
2345
+ runId: runnerId,
2346
+ trigger,
2347
+ startedAt,
2348
+ endedAt,
2349
+ operationId: occurrenceId,
2350
+ permissionEnvelope: { schemaVersion: 1, canMessageOutward: true, returnRoutes: [], deniedTools: [], warnings: [] },
2351
+ toolPolicy: { requestedTools: null, grantedTools: [], deniedTools: [], outwardMessagingAllowed: true },
2352
+ ...(nativeResult.ok ? {} : { errors: [nativeResult.error ?? nativeResult.message ?? "native habit failed"] }),
2353
+ });
2354
+ }
2355
+ finally {
2356
+ this.nativeHabitClaims.delete(claimKey);
2357
+ }
2358
+ if (!completion.receiptWritten || !completion.runtimeStateRecorded) {
2359
+ return { ok: false, error: "native habit completed but its durable receipt or cursor could not be recorded", data: nativeResult };
2360
+ }
2361
+ return nativeResult;
2362
+ }
2363
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2364
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId);
2365
+ }
2366
+ return this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2367
+ agent: command.agent,
2368
+ habitName: command.habitName,
2369
+ trigger,
2370
+ sourceRef: { kind: "daemon-command", id: "habit.poke" },
2371
+ occurrenceId: resolution.occurrenceId,
2372
+ }));
2373
+ }
2374
+ case "habit.probe": {
2375
+ if (!isValidHabitProbeCommand(command)) {
2376
+ return {
2377
+ ok: false,
2378
+ error: "Invalid habit.probe payload: expected non-empty agent/habitName and noSend=true.",
2379
+ };
2380
+ }
2381
+ const trigger = "manual";
2382
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2383
+ return {
2384
+ ok: false,
2385
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2386
+ };
2387
+ }
2388
+ const resolution = this.resolveHabitDispatch({
2389
+ agent: command.agent,
2390
+ habitName: command.habitName,
2391
+ trigger,
2392
+ source: "habit-probe",
2393
+ });
2394
+ if (resolution.kind === "skipped") {
2395
+ this.emitHabitDispatchSkipped({
2396
+ agent: command.agent,
2397
+ habitName: command.habitName,
2398
+ trigger,
2399
+ resolution,
2400
+ });
2401
+ return {
2402
+ ok: true,
2403
+ message: `habit probe rejected by lifecycle: status=${resolution.habit.status}`,
2404
+ data: {
2405
+ noSend: true,
2406
+ status: resolution.habit.status,
2407
+ transportInvocationCount: 0,
2408
+ },
2409
+ };
2410
+ }
2411
+ this.emitHabitDispatchReady({
2412
+ agent: command.agent,
2413
+ habitName: command.habitName,
2414
+ trigger,
2415
+ resolution,
2416
+ });
2417
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2418
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId, true);
2419
+ }
2420
+ const wake = await this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2421
+ agent: command.agent,
2422
+ habitName: command.habitName,
2423
+ trigger,
2424
+ sourceRef: { kind: "daemon-command", id: "habit.probe" },
2425
+ occurrenceId: resolution.occurrenceId,
2426
+ noSend: true,
2427
+ }));
2428
+ if (!wake.ok)
2429
+ return wake;
2430
+ const denied = wake.data
2431
+ ?.decision?.executable === false;
2432
+ const error = denied
2433
+ ? "non-RSVP habit probe was not executed because private-runtime policy denied execution"
2434
+ : "non-RSVP habit probe completion is asynchronous; zero-transport evidence is unverified";
2435
+ return {
2436
+ ok: false,
2437
+ error,
2438
+ data: {
2439
+ ok: false,
2440
+ noSend: true,
2441
+ status: resolution.habit.status,
2442
+ transportInvocationCount: null,
2443
+ error,
2444
+ },
2445
+ };
2446
+ }
2447
+ case "await.poke": {
2448
+ return this.handlePrivateRuntimeWake(this.buildAwaitPrivateWakeCommand(command));
2449
+ }
2450
+ case "mcp.list": {
2451
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
2452
+ const agentName = command.agent ?? "default";
2453
+ const owner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
2454
+ (0, identity_1.setAgentName)(agentName);
2455
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(owner);
2456
+ if (!mcpManager) {
2457
+ return { ok: true, data: [], message: "no MCP servers configured" };
2458
+ }
2459
+ return { ok: true, data: mcpManager.entries.map(({ server, tools, pluginId }) => ({ server, tools, pluginId })) };
2460
+ });
2461
+ }
2462
+ case "mcp.call": {
2463
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
2464
+ const agentName = command.agent ?? "default";
2465
+ const owner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
2466
+ (0, identity_1.setAgentName)(agentName);
2467
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)(owner);
2468
+ if (!mcpCallManager) {
2469
+ return { ok: false, error: "no MCP servers configured" };
2470
+ }
2471
+ try {
2472
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
2473
+ const matches = (0, mcp_tools_1.mcpToolsAsDefinitions)(mcpCallManager).filter((definition) => definition.mcpBinding?.server === command.server && definition.mcpBinding.rawName === command.tool);
2474
+ const binding = matches.length === 1 ? matches[0].mcpBinding : undefined;
2475
+ if (!binding)
2476
+ return { ok: false, error: "MCP tool is unavailable or ambiguous" };
2477
+ const result = await mcpCallManager.manager.callTool(binding, parsedArgs, owner);
2478
+ return { ok: true, data: result };
2479
+ }
2480
+ catch (error) {
2481
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2482
+ }
2483
+ });
2484
+ }
300
2485
  case "hatch.start":
301
2486
  return {
302
2487
  ok: true,
303
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
2488
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
304
2489
  };
305
2490
  default:
306
2491
  return {