@ouro.bot/cli 0.1.0-alpha.81 → 0.1.0-alpha.810

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