@ouro.bot/cli 0.1.0-alpha.73 → 0.1.0-alpha.730

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 (527) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -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 +4633 -14
  15. package/dist/a2a/card.js +57 -0
  16. package/dist/a2a/client.js +180 -0
  17. package/dist/a2a/config.js +50 -0
  18. package/dist/a2a/delegation-stores.js +56 -0
  19. package/dist/a2a/did-resolution.js +93 -0
  20. package/dist/a2a/identity.js +170 -0
  21. package/dist/a2a/inbound-share.js +107 -0
  22. package/dist/a2a/mission-result-wire.js +196 -0
  23. package/dist/a2a/onboarding.js +115 -0
  24. package/dist/a2a/pin-store.js +132 -0
  25. package/dist/a2a/seen-ledger.js +120 -0
  26. package/dist/a2a/server.js +604 -0
  27. package/dist/a2a/task-store.js +69 -0
  28. package/dist/a2a/transport.js +45 -0
  29. package/dist/a2a/types.js +3 -0
  30. package/dist/arc/attention-types.js +8 -0
  31. package/dist/arc/cares.js +144 -0
  32. package/dist/arc/episodes.js +118 -0
  33. package/dist/arc/evolution.js +490 -0
  34. package/dist/arc/flight-recorder.js +1034 -0
  35. package/dist/arc/intentions.js +134 -0
  36. package/dist/arc/json-store.js +117 -0
  37. package/dist/arc/obligations.js +348 -0
  38. package/dist/arc/packets.js +336 -0
  39. package/dist/arc/presence.js +185 -0
  40. package/dist/arc/task-lifecycle.js +57 -0
  41. package/dist/commerce/store.js +755 -0
  42. package/dist/commerce/types.js +3 -0
  43. package/dist/heart/active-work.js +874 -43
  44. package/dist/heart/agent-entry.js +190 -3
  45. package/dist/heart/approval-store.js +791 -0
  46. package/dist/heart/attachments/image-normalize.js +194 -0
  47. package/dist/heart/attachments/materialize.js +97 -0
  48. package/dist/heart/attachments/originals.js +88 -0
  49. package/dist/heart/attachments/render.js +29 -0
  50. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  51. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  52. package/dist/heart/attachments/sources/index.js +16 -0
  53. package/dist/heart/attachments/store.js +103 -0
  54. package/dist/heart/attachments/types.js +93 -0
  55. package/dist/heart/auth/auth-flow.js +479 -0
  56. package/dist/heart/autonomy-budget.js +434 -0
  57. package/dist/heart/awaiting/await-alert.js +146 -0
  58. package/dist/heart/awaiting/await-expiry.js +108 -0
  59. package/dist/heart/awaiting/await-loader.js +91 -0
  60. package/dist/heart/awaiting/await-parser.js +141 -0
  61. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  62. package/dist/heart/awaiting/await-scheduler.js +378 -0
  63. package/dist/heart/background-operations.js +281 -0
  64. package/dist/heart/bridges/manager.js +137 -17
  65. package/dist/heart/bridges/store.js +14 -2
  66. package/dist/heart/bundle-state.js +168 -0
  67. package/dist/heart/commitments.js +135 -0
  68. package/dist/heart/config-registry.js +331 -0
  69. package/dist/heart/config.js +120 -129
  70. package/dist/heart/context-loss-gauntlet.js +354 -0
  71. package/dist/heart/context-loss-sentinel.js +1155 -0
  72. package/dist/heart/core.js +1763 -320
  73. package/dist/heart/cross-chat-delivery.js +8 -22
  74. package/dist/heart/daemon/agent-config-check.js +451 -0
  75. package/dist/heart/daemon/agent-discovery.js +185 -3
  76. package/dist/heart/daemon/agent-service.js +542 -0
  77. package/dist/heart/daemon/agentic-repair.js +547 -0
  78. package/dist/heart/daemon/await-private-wake.js +59 -0
  79. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  80. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  81. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  82. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  83. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  84. package/dist/heart/daemon/cadence.js +180 -0
  85. package/dist/heart/daemon/cli-defaults.js +832 -0
  86. package/dist/heart/daemon/cli-desk.js +322 -0
  87. package/dist/heart/daemon/cli-exec.js +8586 -0
  88. package/dist/heart/daemon/cli-help.js +700 -0
  89. package/dist/heart/daemon/cli-parse.js +2688 -0
  90. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  91. package/dist/heart/daemon/cli-render.js +777 -0
  92. package/dist/heart/daemon/cli-types.js +8 -0
  93. package/dist/heart/daemon/connect-bay.js +323 -0
  94. package/dist/heart/daemon/daemon-cli.js +29 -2093
  95. package/dist/heart/daemon/daemon-entry.js +842 -10
  96. package/dist/heart/daemon/daemon-health.js +176 -0
  97. package/dist/heart/daemon/daemon-rollup.js +57 -0
  98. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  99. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  100. package/dist/heart/daemon/daemon.js +1610 -87
  101. package/dist/heart/daemon/dns-workflow.js +394 -0
  102. package/dist/heart/daemon/doctor-types.js +8 -0
  103. package/dist/heart/daemon/doctor.js +1440 -0
  104. package/dist/heart/daemon/freshness.js +343 -0
  105. package/dist/heart/daemon/habit-private-wake.js +61 -0
  106. package/dist/heart/daemon/health-monitor.js +142 -11
  107. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  108. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  109. package/dist/heart/daemon/http-health-probe.js +80 -0
  110. package/dist/heart/daemon/human-command-screens.js +234 -0
  111. package/dist/heart/daemon/human-readiness.js +114 -0
  112. package/dist/heart/daemon/inner-status.js +78 -0
  113. package/dist/heart/daemon/interactive-repair.js +394 -0
  114. package/dist/heart/daemon/launchd.js +37 -8
  115. package/dist/heart/daemon/log-tailer.js +79 -10
  116. package/dist/heart/daemon/logs-prune.js +110 -0
  117. package/dist/heart/daemon/mcp-canary.js +524 -0
  118. package/dist/heart/daemon/message-router.js +45 -5
  119. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  120. package/dist/heart/daemon/os-cron-deps.js +135 -0
  121. package/dist/heart/daemon/os-cron.js +22 -14
  122. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  123. package/dist/heart/daemon/ouro-entry.js +3 -1
  124. package/dist/heart/daemon/plugin-cli.js +432 -0
  125. package/dist/heart/daemon/process-manager.js +624 -61
  126. package/dist/heart/daemon/provider-discovery.js +137 -0
  127. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  128. package/dist/heart/daemon/pulse.js +511 -0
  129. package/dist/heart/daemon/readiness-repair.js +365 -0
  130. package/dist/heart/daemon/run-hooks.js +2 -0
  131. package/dist/heart/daemon/runtime-logging.js +41 -14
  132. package/dist/heart/daemon/runtime-metadata.js +2 -30
  133. package/dist/heart/daemon/safe-mode.js +161 -0
  134. package/dist/heart/daemon/sense-manager.js +670 -48
  135. package/dist/heart/daemon/session-id-resolver.js +131 -0
  136. package/dist/heart/daemon/skill-management-installer.js +1 -1
  137. package/dist/heart/daemon/socket-client.js +180 -12
  138. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  139. package/dist/heart/daemon/startup-tui.js +338 -0
  140. package/dist/heart/daemon/task-scheduler.js +117 -39
  141. package/dist/heart/daemon/terminal-ui.js +499 -0
  142. package/dist/heart/daemon/thoughts.js +255 -43
  143. package/dist/heart/daemon/up-progress.js +366 -0
  144. package/dist/heart/daemon/vault-items.js +56 -0
  145. package/dist/heart/delegation.js +1 -4
  146. package/dist/heart/external-events/router.js +121 -0
  147. package/dist/heart/habits/habit-cancel.js +810 -0
  148. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  149. package/dist/heart/habits/habit-migration.js +194 -0
  150. package/dist/heart/habits/habit-parser.js +278 -0
  151. package/dist/heart/habits/habit-runtime-state.js +93 -0
  152. package/dist/heart/habits/habit-scheduler.js +649 -0
  153. package/dist/heart/habits/habit-session-summary.js +318 -0
  154. package/dist/heart/habits/habit-session.js +636 -0
  155. package/dist/heart/{daemon → hatch}/hatch-flow.js +55 -62
  156. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  157. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  158. package/dist/heart/{daemon → hatch}/specialist-tools.js +53 -18
  159. package/dist/heart/identity.js +174 -59
  160. package/dist/heart/kept-notes.js +289 -0
  161. package/dist/heart/kicks.js +1 -1
  162. package/dist/heart/machine-identity.js +161 -0
  163. package/dist/heart/mail-import-discovery.js +353 -0
  164. package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
  165. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  166. package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
  167. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  168. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  169. package/dist/heart/mailbox/mailbox-http.js +99 -0
  170. package/dist/heart/mailbox/mailbox-read.js +39 -0
  171. package/dist/heart/mailbox/mailbox-types.js +27 -0
  172. package/dist/heart/mailbox/mailbox-view.js +197 -0
  173. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  174. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  175. package/dist/heart/mailbox/readers/mail.js +375 -0
  176. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  177. package/dist/heart/mailbox/readers/sessions.js +232 -0
  178. package/dist/heart/mailbox/readers/shared.js +111 -0
  179. package/dist/heart/mcp/mcp-server.js +696 -0
  180. package/dist/heart/migrate-config.js +100 -0
  181. package/dist/heart/model-capabilities.js +11 -0
  182. package/dist/heart/orientation-frame.js +345 -0
  183. package/dist/heart/platform.js +81 -0
  184. package/dist/heart/primitives.js +1 -1
  185. package/dist/heart/private-runtime/decision-renderer.js +156 -0
  186. package/dist/heart/private-runtime/index.js +18 -0
  187. package/dist/heart/private-runtime/ledger.js +218 -0
  188. package/dist/heart/private-runtime/policy.js +214 -0
  189. package/dist/heart/private-runtime/types.js +2 -0
  190. package/dist/heart/progress-story.js +1 -1
  191. package/dist/heart/provider-attempt.js +137 -0
  192. package/dist/heart/provider-binding-resolver.js +273 -0
  193. package/dist/heart/provider-credentials.js +441 -0
  194. package/dist/heart/provider-failover.js +311 -0
  195. package/dist/heart/provider-models.js +81 -0
  196. package/dist/heart/provider-ping.js +262 -0
  197. package/dist/heart/provider-readiness-cache.js +119 -0
  198. package/dist/heart/provider-visibility.js +188 -0
  199. package/dist/heart/providers/anthropic-token.js +131 -0
  200. package/dist/heart/providers/anthropic.js +173 -60
  201. package/dist/heart/providers/azure.js +23 -11
  202. package/dist/heart/providers/error-classification.js +127 -0
  203. package/dist/heart/providers/github-copilot.js +34 -38
  204. package/dist/heart/providers/minimax-vlm.js +189 -0
  205. package/dist/heart/providers/minimax.js +26 -8
  206. package/dist/heart/providers/openai-codex-token.js +349 -0
  207. package/dist/heart/providers/openai-codex.js +55 -40
  208. package/dist/heart/run-ledger.js +247 -0
  209. package/dist/heart/runtime-capability-check.js +170 -0
  210. package/dist/heart/runtime-credentials.js +398 -0
  211. package/dist/heart/runtime-cwd.js +87 -0
  212. package/dist/heart/sense-truth.js +20 -4
  213. package/dist/heart/session-activity.js +90 -24
  214. package/dist/heart/session-events.js +1300 -0
  215. package/dist/heart/session-playback-cli-main.js +5 -0
  216. package/dist/heart/session-playback-cli.js +36 -0
  217. package/dist/heart/session-playback.js +231 -0
  218. package/dist/heart/session-stats-cli-main.js +5 -0
  219. package/dist/heart/session-stats.js +182 -0
  220. package/dist/heart/session-transcript.js +133 -0
  221. package/dist/heart/start-of-turn-packet.js +368 -0
  222. package/dist/heart/streaming.js +604 -207
  223. package/dist/heart/structured-output.js +196 -0
  224. package/dist/heart/sync-classification.js +176 -0
  225. package/dist/heart/sync.js +449 -0
  226. package/dist/heart/target-resolution.js +11 -7
  227. package/dist/heart/tempo.js +93 -0
  228. package/dist/heart/temporal-view.js +41 -0
  229. package/dist/heart/timeouts.js +101 -0
  230. package/dist/heart/tool-activity-callbacks.js +59 -0
  231. package/dist/heart/tool-approval.js +339 -0
  232. package/dist/heart/tool-description.js +155 -0
  233. package/dist/heart/tool-friction.js +55 -0
  234. package/dist/heart/tool-loop.js +200 -0
  235. package/dist/heart/turn-context.js +472 -0
  236. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  237. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  238. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  239. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  240. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  241. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  242. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  243. package/dist/heart/versioning/update-hooks.js +154 -0
  244. package/dist/heart/versioning/version-intent.js +114 -0
  245. package/dist/heart/work-card.js +380 -0
  246. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  247. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  248. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  249. package/dist/mailbox-ui/index.html +16 -0
  250. package/dist/mailroom/attention.js +167 -0
  251. package/dist/mailroom/autonomy.js +209 -0
  252. package/dist/mailroom/blob-store.js +715 -0
  253. package/dist/mailroom/body-cache.js +61 -0
  254. package/dist/mailroom/core.js +788 -0
  255. package/dist/mailroom/entry.js +160 -0
  256. package/dist/mailroom/file-store.js +568 -0
  257. package/dist/mailroom/mbox-import.js +393 -0
  258. package/dist/mailroom/migration.js +164 -0
  259. package/dist/mailroom/outbound.js +380 -0
  260. package/dist/mailroom/policy.js +263 -0
  261. package/dist/mailroom/reader.js +233 -0
  262. package/dist/mailroom/search-cache.js +334 -0
  263. package/dist/mailroom/search-relevance.js +319 -0
  264. package/dist/mailroom/smtp-ingress.js +176 -0
  265. package/dist/mailroom/source-state.js +176 -0
  266. package/dist/mailroom/thread.js +109 -0
  267. package/dist/mailroom/travel-extract.js +89 -0
  268. package/dist/mind/bundle-manifest.js +24 -2
  269. package/dist/mind/context.js +273 -111
  270. package/dist/mind/desk-section.js +362 -0
  271. package/dist/mind/diary-integrity.js +60 -0
  272. package/dist/mind/{memory.js → diary.js} +68 -77
  273. package/dist/mind/embedding-provider.js +60 -0
  274. package/dist/mind/file-state.js +179 -0
  275. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  276. package/dist/mind/obligation-steering.js +227 -0
  277. package/dist/mind/pending.js +13 -8
  278. package/dist/mind/prompt-budget.js +479 -0
  279. package/dist/mind/prompt-refresh.js +3 -2
  280. package/dist/mind/prompt.js +1058 -172
  281. package/dist/mind/provenance-trust.js +26 -0
  282. package/dist/mind/record-paths.js +312 -0
  283. package/dist/mind/scrutiny.js +173 -0
  284. package/dist/mind/session-transaction.js +379 -0
  285. package/dist/nerves/cli-logging.js +7 -1
  286. package/dist/nerves/coverage/audit-rules.js +15 -6
  287. package/dist/nerves/coverage/audit.js +28 -2
  288. package/dist/nerves/coverage/cli.js +1 -1
  289. package/dist/nerves/coverage/contract.js +5 -5
  290. package/dist/nerves/coverage/file-completeness.js +139 -5
  291. package/dist/nerves/coverage/run-artifacts.js +55 -35
  292. package/dist/nerves/event-buffer.js +111 -0
  293. package/dist/nerves/index.js +234 -4
  294. package/dist/nerves/observation.js +20 -0
  295. package/dist/nerves/redact.js +79 -0
  296. package/dist/nerves/review/cli-main.js +5 -0
  297. package/dist/nerves/review/cli.js +156 -0
  298. package/dist/nerves/review/core.js +159 -0
  299. package/dist/nerves/runtime.js +5 -1
  300. package/dist/repertoire/ado-client.js +15 -56
  301. package/dist/repertoire/ado-semantic.js +16 -10
  302. package/dist/repertoire/api-client.js +97 -0
  303. package/dist/repertoire/bitwarden-store.js +1045 -0
  304. package/dist/repertoire/bundle-templates.js +71 -0
  305. package/dist/repertoire/bw-installer.js +180 -0
  306. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  307. package/dist/repertoire/coding/context-pack.js +331 -0
  308. package/dist/repertoire/coding/feedback.js +218 -30
  309. package/dist/repertoire/coding/index.js +15 -3
  310. package/dist/repertoire/coding/manager.js +166 -10
  311. package/dist/repertoire/coding/spawner.js +58 -11
  312. package/dist/repertoire/coding/tools.js +242 -14
  313. package/dist/repertoire/coding/workbench-client.js +272 -0
  314. package/dist/repertoire/coding/workbench-manager.js +346 -0
  315. package/dist/repertoire/commerce-errors.js +109 -0
  316. package/dist/repertoire/commerce-self-test.js +156 -0
  317. package/dist/repertoire/credential-access.js +178 -0
  318. package/dist/repertoire/desk/classifier.js +362 -0
  319. package/dist/repertoire/duffel-client.js +185 -0
  320. package/dist/repertoire/github-client.js +14 -55
  321. package/dist/repertoire/graph-client.js +11 -52
  322. package/dist/repertoire/guardrails.js +138 -18
  323. package/dist/repertoire/mcp-client.js +44 -3
  324. package/dist/repertoire/mcp-manager.js +259 -20
  325. package/dist/repertoire/mcp-tools.js +83 -0
  326. package/dist/repertoire/plugin-mcp.js +175 -0
  327. package/dist/repertoire/plugins.js +253 -0
  328. package/dist/repertoire/shell-sessions.js +133 -0
  329. package/dist/repertoire/skills.js +48 -4
  330. package/dist/repertoire/stripe-client.js +131 -0
  331. package/dist/repertoire/tool-arguments.js +104 -0
  332. package/dist/repertoire/tool-results.js +29 -0
  333. package/dist/repertoire/tools-a2a.js +699 -0
  334. package/dist/repertoire/tools-attachments.js +317 -0
  335. package/dist/repertoire/tools-awaiting.js +372 -0
  336. package/dist/repertoire/tools-base.js +67 -1095
  337. package/dist/repertoire/tools-bluebubbles.js +2 -0
  338. package/dist/repertoire/tools-bridge.js +144 -0
  339. package/dist/repertoire/tools-bundle.js +993 -0
  340. package/dist/repertoire/tools-commerce.js +253 -0
  341. package/dist/repertoire/tools-config.js +186 -0
  342. package/dist/repertoire/tools-continuity.js +252 -0
  343. package/dist/repertoire/tools-credential.js +383 -0
  344. package/dist/repertoire/tools-evolution.js +527 -0
  345. package/dist/repertoire/tools-files.js +344 -0
  346. package/dist/repertoire/tools-flight.js +290 -0
  347. package/dist/repertoire/tools-flow.js +119 -0
  348. package/dist/repertoire/tools-github.js +3 -8
  349. package/dist/repertoire/tools-habits.js +103 -0
  350. package/dist/repertoire/tools-mail.js +1975 -0
  351. package/dist/repertoire/tools-notes.js +459 -0
  352. package/dist/repertoire/tools-obligations.js +182 -0
  353. package/dist/repertoire/tools-orientation.js +31 -0
  354. package/dist/repertoire/tools-record.js +482 -0
  355. package/dist/repertoire/tools-rsvp.js +139 -0
  356. package/dist/repertoire/tools-runtime.js +150 -0
  357. package/dist/repertoire/tools-session.js +881 -0
  358. package/dist/repertoire/tools-shell.js +133 -0
  359. package/dist/repertoire/tools-stripe.js +224 -0
  360. package/dist/repertoire/tools-surface.js +355 -0
  361. package/dist/repertoire/tools-teams.js +12 -39
  362. package/dist/repertoire/tools-travel.js +125 -0
  363. package/dist/repertoire/tools-trip.js +982 -0
  364. package/dist/repertoire/tools-user-profile.js +146 -0
  365. package/dist/repertoire/tools-vault.js +40 -0
  366. package/dist/repertoire/tools-voice.js +145 -0
  367. package/dist/repertoire/tools.js +258 -79
  368. package/dist/repertoire/travel-api-client.js +360 -0
  369. package/dist/repertoire/user-profile.js +131 -0
  370. package/dist/repertoire/vault-setup.js +246 -0
  371. package/dist/repertoire/vault-unlock.js +594 -0
  372. package/dist/rsvp/aisleplanner-client.js +354 -0
  373. package/dist/rsvp/cli.js +926 -0
  374. package/dist/rsvp/config.js +327 -0
  375. package/dist/rsvp/cutover.js +433 -0
  376. package/dist/rsvp/diagnostics.js +232 -0
  377. package/dist/rsvp/diff-renderer.js +176 -0
  378. package/dist/rsvp/habit-policy.js +110 -0
  379. package/dist/rsvp/habit-stage.js +123 -0
  380. package/dist/rsvp/incident-bundle.js +97 -0
  381. package/dist/rsvp/migration.js +204 -0
  382. package/dist/rsvp/native-habit-runner.js +630 -0
  383. package/dist/rsvp/outbound-state.js +628 -0
  384. package/dist/rsvp/query.js +118 -0
  385. package/dist/rsvp/replay.js +233 -0
  386. package/dist/rsvp/snapshot.js +232 -0
  387. package/dist/rsvp/spend-ledger.js +175 -0
  388. package/dist/scripts/claude-code-hook.js +41 -0
  389. package/dist/scripts/claude-code-stop-hook.js +47 -0
  390. package/dist/senses/a2a-entry.js +115 -0
  391. package/dist/senses/attention-queue.js +186 -0
  392. package/dist/senses/await-turn-message.js +58 -0
  393. package/dist/senses/bluebubbles/active-turns.js +216 -0
  394. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  395. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  396. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +355 -40
  397. package/dist/senses/bluebubbles/context-packet.js +207 -0
  398. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  399. package/dist/senses/bluebubbles/entry.js +90 -0
  400. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  401. package/dist/senses/bluebubbles/index.js +3839 -0
  402. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  403. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  404. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +159 -28
  405. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  406. package/dist/senses/bluebubbles/outbound-state.js +308 -0
  407. package/dist/senses/bluebubbles/processed-log.js +133 -0
  408. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  409. package/dist/senses/bluebubbles/replay.js +284 -0
  410. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  411. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  412. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  413. package/dist/senses/bluebubbles/webhook-registration.js +228 -0
  414. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  415. package/dist/senses/cli/bracketed-paste.js +82 -0
  416. package/dist/senses/cli/image-paste.js +287 -0
  417. package/dist/senses/cli/image-ref-navigation.js +75 -0
  418. package/dist/senses/cli/ink-app.js +156 -0
  419. package/dist/senses/cli/inline-diff.js +64 -0
  420. package/dist/senses/cli/input-keys.js +174 -0
  421. package/dist/senses/cli/kill-ring.js +86 -0
  422. package/dist/senses/cli/message-list.js +51 -0
  423. package/dist/senses/cli/ouro-tui.js +607 -0
  424. package/dist/senses/cli/spinner-imperative.js +135 -0
  425. package/dist/senses/cli/spinner.js +101 -0
  426. package/dist/senses/cli/status-line.js +60 -0
  427. package/dist/senses/cli/streaming-markdown.js +526 -0
  428. package/dist/senses/cli/tool-display.js +85 -0
  429. package/dist/senses/cli/tool-render.js +85 -0
  430. package/dist/senses/cli/tui-store.js +241 -0
  431. package/dist/senses/cli/virtual-list.js +35 -0
  432. package/dist/senses/cli-entry.js +60 -8
  433. package/dist/senses/cli-layout.js +100 -0
  434. package/dist/senses/cli.js +640 -312
  435. package/dist/senses/commands.js +66 -3
  436. package/dist/senses/context-packet-ledger.js +371 -0
  437. package/dist/senses/context-packets.js +154 -0
  438. package/dist/senses/habit-lifecycle-guard.js +24 -0
  439. package/dist/senses/habit-turn-message.js +160 -0
  440. package/dist/senses/ingress-evidence.js +2 -0
  441. package/dist/senses/mail-entry.js +66 -0
  442. package/dist/senses/mail.js +524 -0
  443. package/dist/senses/pipeline.js +1075 -176
  444. package/dist/senses/private-runtime-worker.js +740 -0
  445. package/dist/senses/private-runtime.js +1212 -0
  446. package/dist/senses/proactive-content-guard.js +51 -0
  447. package/dist/senses/shared-turn.js +424 -0
  448. package/dist/senses/surface-tool.js +109 -0
  449. package/dist/senses/teams-entry.js +60 -8
  450. package/dist/senses/teams.js +515 -217
  451. package/dist/senses/trust-gate.js +104 -9
  452. package/dist/senses/voice/audio-playback.js +237 -0
  453. package/dist/senses/voice/audio-routing.js +119 -0
  454. package/dist/senses/voice/elevenlabs.js +202 -0
  455. package/dist/senses/voice/floor-control.js +431 -0
  456. package/dist/senses/voice/floor-controller.js +115 -0
  457. package/dist/senses/voice/golden-path.js +116 -0
  458. package/dist/senses/voice/index.js +29 -0
  459. package/dist/senses/voice/meeting.js +113 -0
  460. package/dist/senses/voice/outbound.js +190 -0
  461. package/dist/senses/voice/phone.js +33 -0
  462. package/dist/senses/voice/playback.js +139 -0
  463. package/dist/senses/voice/realtime-eval.js +496 -0
  464. package/dist/senses/voice/realtime-trace.js +531 -0
  465. package/dist/senses/voice/transcript.js +70 -0
  466. package/dist/senses/voice/turn.js +191 -0
  467. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  468. package/dist/senses/voice/twilio-phone.js +5081 -0
  469. package/dist/senses/voice/types.js +2 -0
  470. package/dist/senses/voice/whisper.js +161 -0
  471. package/dist/senses/voice-entry.js +81 -0
  472. package/dist/senses/voice-realtime-eval-command.js +99 -0
  473. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  474. package/dist/senses/voice-twilio-entry.js +87 -0
  475. package/dist/trips/core.js +138 -0
  476. package/dist/trips/store.js +265 -0
  477. package/dist/util/frontmatter.js +69 -0
  478. package/package.json +65 -12
  479. package/skills/agent-commerce.md +113 -0
  480. package/skills/browser-navigation.md +117 -0
  481. package/skills/commerce-setup-guide.md +116 -0
  482. package/skills/commerce-setup.md +84 -0
  483. package/skills/configure-dev-tools.md +99 -0
  484. package/skills/travel-planning.md +138 -0
  485. package/dist/heart/daemon/auth-flow.js +0 -430
  486. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  487. package/dist/heart/daemon/update-hooks.js +0 -138
  488. package/dist/heart/safe-workspace.js +0 -228
  489. package/dist/heart/session-recall.js +0 -116
  490. package/dist/mind/friends/channel.js +0 -84
  491. package/dist/mind/friends/group-context.js +0 -144
  492. package/dist/mind/friends/resolver.js +0 -84
  493. package/dist/mind/friends/store-file.js +0 -190
  494. package/dist/mind/friends/store.js +0 -4
  495. package/dist/mind/friends/tokens.js +0 -26
  496. package/dist/mind/friends/trust-explanation.js +0 -74
  497. package/dist/mind/friends/types.js +0 -29
  498. package/dist/repertoire/tasks/board.js +0 -134
  499. package/dist/repertoire/tasks/index.js +0 -224
  500. package/dist/repertoire/tasks/lifecycle.js +0 -80
  501. package/dist/repertoire/tasks/middleware.js +0 -65
  502. package/dist/repertoire/tasks/parser.js +0 -173
  503. package/dist/repertoire/tasks/scanner.js +0 -132
  504. package/dist/repertoire/tasks/transitions.js +0 -144
  505. package/dist/senses/bluebubbles-entry.js +0 -13
  506. package/dist/senses/bluebubbles.js +0 -1180
  507. package/dist/senses/debug-activity.js +0 -148
  508. package/dist/senses/inner-dialog-worker.js +0 -90
  509. package/dist/senses/inner-dialog.js +0 -480
  510. package/subagents/README.md +0 -7
  511. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  512. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  513. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  514. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  515. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  516. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  517. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  518. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  519. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  520. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  521. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  522. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  523. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  524. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  525. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  526. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  527. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,43 +34,465 @@ 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"));
40
52
  const identity_1 = require("../identity");
53
+ const agent_discovery_1 = require("./agent-discovery");
41
54
  const runtime_1 = require("../../nerves/runtime");
42
55
  const runtime_metadata_1 = require("./runtime-metadata");
43
56
  const runtime_mode_1 = require("./runtime-mode");
44
- const update_hooks_1 = require("./update-hooks");
57
+ const update_hooks_1 = require("../versioning/update-hooks");
45
58
  const bundle_meta_1 = require("./hooks/bundle-meta");
59
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
46
60
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
47
- const update_checker_1 = require("./update-checker");
48
- const staged_restart_1 = require("./staged-restart");
61
+ const update_checker_1 = require("../versioning/update-checker");
49
62
  const child_process_1 = require("child_process");
50
63
  const pending_1 = require("../../mind/pending");
51
- const channel_1 = require("../../mind/friends/channel");
64
+ const agent_service_1 = require("./agent-service");
65
+ const friends_1 = require("@ouro.bot/friends");
52
66
  const mcp_manager_1 = require("../../repertoire/mcp-manager");
67
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
68
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
69
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
70
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
71
+ const provider_visibility_1 = require("../provider-visibility");
72
+ const private_runtime_1 = require("../private-runtime");
73
+ const socket_client_1 = require("./socket-client");
74
+ const flight_recorder_1 = require("../../arc/flight-recorder");
75
+ const await_private_wake_1 = require("./await-private-wake");
76
+ const habit_private_wake_1 = require("./habit-private-wake");
77
+ const habit_parser_1 = require("../habits/habit-parser");
78
+ const habit_runtime_state_1 = require("../habits/habit-runtime-state");
79
+ const router_1 = require("../external-events/router");
80
+ const habit_policy_1 = require("../../rsvp/habit-policy");
81
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
82
+ /**
83
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
84
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
85
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
86
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
87
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
88
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
89
+ * by a vitest test that called daemon.start()).
90
+ *
91
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
92
+ * to make the production pidfile sacred. Tests that need to verify these
93
+ * functions' behavior should use the extracted pure helpers
94
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
95
+ */
96
+ function isVitestProcess() {
97
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
98
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
99
+ return false;
100
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
101
+ }
102
+ function messageFromHabitPokeError(error) {
103
+ if (error instanceof Error)
104
+ return error.message;
105
+ /* v8 ignore next -- defensive fallback for hostile/non-Error throws from filesystem or parsers @preserve */
106
+ return String(error);
107
+ }
108
+ /**
109
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
110
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
111
+ * that are safe to SIGTERM — true orphans, not children of live sibling
112
+ * daemons running from worktrees, test suites, or other users of the harness.
113
+ *
114
+ * Exported so unit tests can exercise the filter without shelling out.
115
+ */
116
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
117
+ const orphans = [];
118
+ for (const line of psOutput.split("\n")) {
119
+ // Explicitly exclude MCP server processes — they share a harness entry
120
+ // point but are not daemon children and must never be killed.
121
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
122
+ continue;
123
+ // Match only daemon-owned JS entry points.
124
+ if (!line.includes("agent-entry.js")
125
+ && !line.includes("daemon-entry.js")
126
+ && !line.includes("bluebubbles/entry.js")
127
+ && !line.includes("mail-entry.js")
128
+ && !line.includes("teams-entry.js")
129
+ && !line.includes("a2a-entry.js")
130
+ && !line.includes("voice-entry.js"))
131
+ continue;
132
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
133
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
134
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
135
+ if (!match)
136
+ continue;
137
+ const pid = parseInt(match[1], 10);
138
+ const ppid = parseInt(match[2], 10);
139
+ if (pid === selfPid)
140
+ continue;
141
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
142
+ // PPID means the process belongs to another daemon instance (parallel
143
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
144
+ // Killing those will crash unrelated harnesses — we saw this in B6
145
+ // when a vitest worker's daemon killed a production agent's children.
146
+ if (ppid !== 1)
147
+ continue;
148
+ orphans.push(pid);
149
+ }
150
+ return orphans;
151
+ }
152
+ /**
153
+ * Given a list of PIDs from the pidfile, return only those that are actual
154
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
155
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
156
+ *
157
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
158
+ * Returns the empty list if ps fails — safer to skip cleanup than to
159
+ * wildcard-kill on a bad read.
160
+ *
161
+ * Exported for direct unit coverage.
162
+ */
163
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
164
+ if (candidatePids.length === 0)
165
+ return [];
166
+ const psOutput = psRunner(candidatePids);
167
+ if (psOutput === null)
168
+ return [];
169
+ const survivingOrphans = [];
170
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
171
+ // PIDs not found (already exited) are silently omitted — which is the
172
+ // correct behavior for us: we only want to kill live orphans.
173
+ for (const line of psOutput.split("\n")) {
174
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
175
+ if (!match)
176
+ continue;
177
+ const pid = parseInt(match[1], 10);
178
+ const ppid = parseInt(match[2], 10);
179
+ if (ppid !== 1)
180
+ continue;
181
+ if (!candidatePids.includes(pid))
182
+ continue;
183
+ survivingOrphans.push(pid);
184
+ }
185
+ return survivingOrphans;
186
+ }
187
+ function mergeUniqueOrphanPids(...sources) {
188
+ const merged = [];
189
+ const seen = new Set();
190
+ for (const source of sources) {
191
+ for (const pid of source) {
192
+ if (seen.has(pid))
193
+ continue;
194
+ seen.add(pid);
195
+ merged.push(pid);
196
+ }
197
+ }
198
+ return merged;
199
+ }
200
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
201
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
202
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
203
+ function defaultIsPidAlive(pid) {
204
+ try {
205
+ process.kill(pid, 0);
206
+ return true;
207
+ }
208
+ catch (error) {
209
+ return error.code === "EPERM";
210
+ }
211
+ }
212
+ /* v8 ignore stop */
213
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
214
+ async function defaultSettleSleep(ms) {
215
+ await new Promise((resolve) => setTimeout(resolve, ms));
216
+ }
217
+ /* v8 ignore stop */
218
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
219
+ if (pids.length === 0)
220
+ return [];
221
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
222
+ const now = deps.now ?? Date.now;
223
+ const sleep = deps.sleep ?? defaultSettleSleep;
224
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
225
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
226
+ const deadline = now() + timeoutMs;
227
+ let survivors = pids.filter(isPidAlive);
228
+ while (survivors.length > 0 && now() < deadline) {
229
+ await sleep(pollIntervalMs);
230
+ survivors = pids.filter(isPidAlive);
231
+ }
232
+ return survivors;
233
+ }
234
+ function assertOrphanCleanupComplete(survivingPids) {
235
+ if (survivingPids.length === 0)
236
+ return;
237
+ const errorReason = `refusing startup while ${survivingPids.length} orphaned Ouro processes remain: ${survivingPids.join(", ")}`;
238
+ (0, runtime_1.emitNervesEvent)({
239
+ level: "error",
240
+ component: "daemon",
241
+ event: "daemon.orphan_cleanup_incomplete",
242
+ message: errorReason,
243
+ meta: { survivingPids },
244
+ });
245
+ throw new Error(errorReason);
246
+ }
247
+ const ORPHAN_CLEANUP_MAX_SIGNAL_PASSES = 8;
248
+ async function drainOrphanProcessesBeforeStartup(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, deps = {}) {
249
+ const signalOrphans = deps.signalOrphans ?? killOrphanProcesses;
250
+ const settleOrphans = deps.settleOrphans ?? waitForOrphanProcessesToSettle;
251
+ const maxSignalPasses = deps.maxSignalPasses ?? ORPHAN_CLEANUP_MAX_SIGNAL_PASSES;
252
+ for (let pass = 0; pass < maxSignalPasses; pass += 1) {
253
+ const signaledPids = signalOrphans(socketPath);
254
+ if (signaledPids.length === 0)
255
+ return;
256
+ const survivingPids = await settleOrphans(signaledPids);
257
+ assertOrphanCleanupComplete(survivingPids);
258
+ }
259
+ const errorReason = `orphan cleanup did not reach a fixed point after ${maxSignalPasses} signaling round(s)`;
260
+ (0, runtime_1.emitNervesEvent)({
261
+ level: "error",
262
+ component: "daemon",
263
+ event: "daemon.orphan_cleanup_not_converged",
264
+ message: errorReason,
265
+ meta: { maxSignalPasses },
266
+ });
267
+ throw new Error(errorReason);
268
+ }
269
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
270
+ function runPsCheck(pids) {
271
+ try {
272
+ const csv = pids.join(",");
273
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
274
+ }
275
+ catch {
276
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
277
+ // "no survivors" rather than an error.
278
+ return "";
279
+ }
280
+ }
281
+ /* v8 ignore stop */
282
+ /**
283
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
284
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
285
+ * deletes the file. The new daemon writes its own PIDs after spawning.
286
+ *
287
+ * Safety: pidfile contents are verified before being killed — each PID must
288
+ * be an actual orphan (PPID reparented to init/PID 1) via
289
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
290
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
291
+ * OS) could SIGTERM unrelated processes.
292
+ *
293
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
294
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
295
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
296
+ */
297
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
298
+ function isProductionDaemonSocketPath(socketPath) {
299
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
300
+ }
301
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
302
+ if (!isProductionDaemonSocketPath(socketPath)) {
303
+ (0, runtime_1.emitNervesEvent)({
304
+ level: "warn",
305
+ component: "daemon",
306
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
307
+ message: "blocked orphan cleanup for non-production daemon socket",
308
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
309
+ });
310
+ return [];
311
+ }
312
+ if (isVitestProcess()) {
313
+ (0, runtime_1.emitNervesEvent)({
314
+ level: "warn",
315
+ component: "daemon",
316
+ event: "daemon.orphan_cleanup_test_blocked",
317
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
318
+ meta: { pidfilePath: PIDFILE_PATH },
319
+ });
320
+ return [];
321
+ }
322
+ try {
323
+ let pidfileOrphans = [];
324
+ let scanOrphans = [];
325
+ // Primary: read pidfile from previous daemon
326
+ try {
327
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
328
+ const candidates = raw.split("\n")
329
+ .map((s) => parseInt(s.trim(), 10))
330
+ .filter((n) => !isNaN(n) && n !== process.pid);
331
+ // Verify each candidate is an actual live orphan before killing. See
332
+ // docstring above for why this matters.
333
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
334
+ fs.unlinkSync(PIDFILE_PATH);
335
+ }
336
+ catch {
337
+ // No pidfile — the ps scan below still covers true orphans.
338
+ }
339
+ // Always supplement the pidfile with the scoped ps scan. A stale or
340
+ // partial pidfile can otherwise kill one old daemon while leaving a
341
+ // sibling PPID=1 daemon alive without a socket.
342
+ try {
343
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
344
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
345
+ }
346
+ catch (error) {
347
+ const detail = error instanceof Error ? error.message : String(error);
348
+ throw new Error(`could not discover orphaned Ouro processes: ${detail}`);
349
+ }
350
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
351
+ if (pidsToKill.length > 0) {
352
+ for (const pid of pidsToKill) {
353
+ try {
354
+ process.kill(pid, "SIGTERM");
355
+ }
356
+ catch { /* already exited */ }
357
+ }
358
+ (0, runtime_1.emitNervesEvent)({
359
+ component: "daemon",
360
+ event: "daemon.orphan_cleanup",
361
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
362
+ meta: { pids: pidsToKill },
363
+ });
364
+ }
365
+ return pidsToKill;
366
+ }
367
+ catch (error) {
368
+ (0, runtime_1.emitNervesEvent)({
369
+ level: "error",
370
+ component: "daemon",
371
+ event: "daemon.orphan_cleanup_error",
372
+ message: "failed to clean up orphaned ouro processes",
373
+ meta: { error: error instanceof Error ? error.message : String(error) },
374
+ });
375
+ throw error instanceof Error ? error : new Error(String(error));
376
+ }
377
+ }
378
+ /**
379
+ * Write all managed PIDs (daemon + children) to the pidfile.
380
+ * Called after all agents and senses are spawned.
381
+ */
382
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
383
+ if (!isProductionDaemonSocketPath(socketPath)) {
384
+ (0, runtime_1.emitNervesEvent)({
385
+ level: "warn",
386
+ component: "daemon",
387
+ event: "daemon.write_pidfile_nonproduction_blocked",
388
+ message: "blocked production pidfile write for non-production daemon socket",
389
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
390
+ });
391
+ return;
392
+ }
393
+ if (isVitestProcess()) {
394
+ (0, runtime_1.emitNervesEvent)({
395
+ level: "warn",
396
+ component: "daemon",
397
+ event: "daemon.write_pidfile_test_blocked",
398
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
399
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
400
+ });
401
+ return;
402
+ }
403
+ try {
404
+ const pids = [process.pid, ...extraPids].filter(Boolean);
405
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
406
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
407
+ }
408
+ catch { /* best effort */ }
409
+ }
410
+ function readSocketIdentity(socketPath) {
411
+ try {
412
+ const stats = fs.lstatSync(socketPath);
413
+ return {
414
+ dev: stats.dev,
415
+ ino: stats.ino,
416
+ ctimeMs: stats.ctimeMs,
417
+ };
418
+ }
419
+ catch {
420
+ return null;
421
+ }
422
+ }
423
+ function sameSocketIdentity(left, right) {
424
+ if (!left || !right)
425
+ return false;
426
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
427
+ }
53
428
  function buildWorkerRows(snapshots) {
54
429
  return snapshots.map((snapshot) => ({
55
430
  agent: snapshot.name,
56
431
  worker: snapshot.channel,
432
+ autoStart: snapshot.autoStart ?? true,
57
433
  status: snapshot.status,
58
434
  pid: snapshot.pid,
59
435
  restartCount: snapshot.restartCount,
60
436
  startedAt: snapshot.startedAt,
437
+ lastExitCode: snapshot.lastExitCode ?? null,
438
+ lastSignal: snapshot.lastSignal ?? null,
439
+ errorReason: snapshot.errorReason ?? null,
440
+ fixHint: snapshot.fixHint ?? null,
61
441
  }));
62
442
  }
443
+ function unhealthySenseRows(senses) {
444
+ return senses.filter((row) => {
445
+ if (!row.enabled)
446
+ return false;
447
+ if (row.status === "disabled" || row.status === "not_attached")
448
+ return false;
449
+ if (row.status === "interactive" || row.status === "running")
450
+ return false;
451
+ return true;
452
+ });
453
+ }
454
+ function isParkedWorker(row) {
455
+ return row.autoStart === false && row.status === "stopped";
456
+ }
457
+ function unhealthyWorkerRows(workers) {
458
+ return workers.filter((row) => !isParkedWorker(row) && row.status !== "running");
459
+ }
460
+ function unhealthyHealthChecks(healthChecks) {
461
+ return healthChecks.filter((row) => row.status !== "ok");
462
+ }
463
+ function overviewHealth(workers, senses, healthChecks = []) {
464
+ if (unhealthyWorkerRows(workers).length > 0)
465
+ return "warn";
466
+ if (unhealthySenseRows(senses).length > 0)
467
+ return "warn";
468
+ if (unhealthyHealthChecks(healthChecks).length > 0)
469
+ return "warn";
470
+ return "ok";
471
+ }
63
472
  function formatStatusSummary(payload) {
64
- if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0) {
473
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
65
474
  return "no managed agents";
66
475
  }
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}`),
476
+ const degraded = [
477
+ ...unhealthyWorkerRows(payload.workers)
478
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
479
+ ...unhealthySenseRows(payload.senses)
480
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
481
+ ...(payload.healthChecks ?? [])
482
+ .filter((row) => row.status !== "ok")
483
+ .map((row) => `health-check:${row.name}:${row.status}`),
72
484
  ];
73
- const detail = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
485
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
486
+ if (!detail) {
487
+ const rows = [
488
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
489
+ ...payload.senses
490
+ .filter((row) => row.enabled)
491
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
492
+ ];
493
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
494
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
495
+ }
74
496
  return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
75
497
  }
76
498
  function parseIncomingCommand(raw) {
@@ -90,6 +512,92 @@ function parseIncomingCommand(raw) {
90
512
  }
91
513
  return parsed;
92
514
  }
515
+ function isValidSenseReviveCommand(command) {
516
+ return typeof command.agent === "string"
517
+ && typeof command.sense === "string"
518
+ && typeof command.reason === "string";
519
+ }
520
+ function isValidTaskPokeCommand(command) {
521
+ return typeof command.agent === "string"
522
+ && command.agent.trim().length > 0
523
+ && typeof command.taskId === "string"
524
+ && command.taskId.trim().length > 0;
525
+ }
526
+ function isValidHabitPokeCommand(command) {
527
+ return typeof command.agent === "string"
528
+ && command.agent.trim().length > 0
529
+ && typeof command.habitName === "string"
530
+ && command.habitName.trim().length > 0;
531
+ }
532
+ function isValidHabitProbeCommand(command) {
533
+ return typeof command.agent === "string"
534
+ && command.agent.trim().length > 0
535
+ && typeof command.habitName === "string"
536
+ && command.habitName.trim().length > 0
537
+ && (command.noSend === undefined || command.noSend === true);
538
+ }
539
+ function taskIdFromTaskPokePrivateWakeCommand(command) {
540
+ if (command.kind !== "private.wake" || command.triggerSource !== "task-poke")
541
+ return null;
542
+ const taskRef = command.originRefs?.find((ref) => ref.kind === "task" && typeof ref.id === "string");
543
+ if (!taskRef || typeof taskRef.id !== "string")
544
+ return null;
545
+ const trimmed = taskRef.id.trim();
546
+ return trimmed.length > 0 ? trimmed : null;
547
+ }
548
+ /**
549
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
550
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
551
+ * restarts the daemon process (fresh module cache).
552
+ */
553
+ async function handleAgentSenseTurn(command, runtime) {
554
+ try {
555
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
556
+ setAgentName(command.agent);
557
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
558
+ const result = await runSenseTurn({
559
+ agentName: command.agent,
560
+ channel: command.channel,
561
+ sessionKey: command.sessionKey,
562
+ friendId: command.friendId,
563
+ userMessage: command.message,
564
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
565
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
566
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
567
+ // turn for a different agent cannot inherit these servers.
568
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
569
+ });
570
+ return {
571
+ ok: true,
572
+ message: result.response,
573
+ data: { ponderDeferred: result.ponderDeferred },
574
+ };
575
+ }
576
+ catch (error) {
577
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
578
+ const errorMessage = error instanceof Error ? error.message : String(error);
579
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
580
+ }
581
+ }
582
+ async function handleAgentAskTurn(command, runtime) {
583
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
584
+ const question = typeof command.question === "string" ? command.question : "";
585
+ if (!question.trim())
586
+ return { ok: false, error: "Missing required parameter: question" };
587
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
588
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
589
+ ? command.sessionKey.trim()
590
+ : `agent-ask:${command.friendId}`;
591
+ /* v8 ignore stop */
592
+ return handleAgentSenseTurn({
593
+ kind: "agent.senseTurn",
594
+ agent: command.agent,
595
+ friendId: command.friendId,
596
+ channel,
597
+ sessionKey,
598
+ message: question,
599
+ }, runtime);
600
+ }
93
601
  class OuroDaemon {
94
602
  socketPath;
95
603
  processManager;
@@ -98,7 +606,17 @@ class OuroDaemon {
98
606
  router;
99
607
  senseManager;
100
608
  bundlesRoot;
609
+ mode;
101
610
  server = null;
611
+ mailboxServer = null;
612
+ socketIdentity = null;
613
+ senseAutostartTimer = null;
614
+ mailboxServerFactory;
615
+ privateRuntimePolicyDeps;
616
+ onStopCommandComplete;
617
+ externalEventRoot;
618
+ rsvpHabitRunner;
619
+ orphanStartupDrain;
102
620
  constructor(options) {
103
621
  this.socketPath = options.socketPath;
104
622
  this.processManager = options.processManager;
@@ -107,6 +625,103 @@ class OuroDaemon {
107
625
  this.router = options.router;
108
626
  this.senseManager = options.senseManager ?? null;
109
627
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
628
+ this.mode = options.mode ?? "production";
629
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
630
+ this.privateRuntimePolicyDeps = options.privateRuntimePolicyDeps ?? {};
631
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
632
+ this.externalEventRoot = options.externalEventRoot ?? null;
633
+ this.rsvpHabitRunner = options.rsvpHabitRunner;
634
+ this.orphanStartupDrain = options.orphanStartupDrain ?? drainOrphanProcessesBeforeStartup;
635
+ }
636
+ /* 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 */
637
+ createDefaultMailboxServer() {
638
+ return (0, mailbox_http_1.startMailboxHttpServer)({
639
+ host: "127.0.0.1",
640
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
641
+ bundlesRoot: this.bundlesRoot,
642
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
643
+ readMachineView: ({ machine }) => {
644
+ const overview = this.buildStatusPayload().overview;
645
+ return (0, mailbox_view_1.buildMailboxMachineView)({
646
+ machine,
647
+ daemon: {
648
+ status: overview.daemon,
649
+ health: overview.health,
650
+ mode: overview.mode,
651
+ socketPath: overview.socketPath,
652
+ mailboxUrl: overview.mailboxUrl,
653
+ entryPath: overview.entryPath,
654
+ workerCount: overview.workerCount,
655
+ senseCount: overview.senseCount,
656
+ },
657
+ });
658
+ },
659
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
660
+ readAgentView: (agentName) => {
661
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
662
+ return (0, mailbox_view_1.buildMailboxAgentView)({
663
+ agent,
664
+ viewer: { kind: "human" },
665
+ });
666
+ },
667
+ });
668
+ }
669
+ /* v8 ignore stop */
670
+ buildStatusPayload() {
671
+ const snapshots = this.processManager.listAgentSnapshots();
672
+ const workers = buildWorkerRows(snapshots);
673
+ const senses = this.senseManager?.listSenseRows() ?? [];
674
+ const healthChecks = this.overlaySchedulerHealth(this.healthMonitor.getLastResults?.() ?? []);
675
+ const repoRoot = (0, identity_1.getRepoRoot)();
676
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
677
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
678
+ const providerAgents = (0, agent_discovery_1.listEnabledBundleAgents)({ bundlesRoot: this.bundlesRoot });
679
+ const providers = providerAgents.flatMap((agentName) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
680
+ agentName,
681
+ agentRoot: path.join(this.bundlesRoot, `${agentName}.ouro`),
682
+ })));
683
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
684
+ return {
685
+ overview: {
686
+ daemon: "running",
687
+ health: overviewHealth(workers, senses, healthChecks),
688
+ socketPath: this.socketPath,
689
+ mailboxUrl,
690
+ outlookUrl: mailboxUrl,
691
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
692
+ workerCount: workers.length,
693
+ senseCount: senses.length,
694
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
695
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
696
+ },
697
+ workers,
698
+ senses,
699
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
700
+ sync,
701
+ agents,
702
+ ...(providers.length > 0 ? { providers } : {}),
703
+ };
704
+ }
705
+ overlaySchedulerHealth(healthChecks) {
706
+ const degradedJobs = this.scheduler.listDegradedJobs?.() ?? [];
707
+ if (degradedJobs.length === 0)
708
+ return healthChecks;
709
+ const cronHealth = {
710
+ name: "cron-health",
711
+ status: "warn",
712
+ message: `cron jobs degraded; timer fallback active: ${degradedJobs
713
+ .map((job) => `${job.id} (${job.reason})`)
714
+ .join(", ")}`,
715
+ };
716
+ const next = healthChecks.map((check) => ({ ...check }));
717
+ const existingIndex = next.findIndex((check) => check.name === "cron-health");
718
+ if (existingIndex === -1) {
719
+ next.push(cronHealth);
720
+ }
721
+ else {
722
+ next[existingIndex] = cronHealth;
723
+ }
724
+ return next;
110
725
  }
111
726
  async start() {
112
727
  if (this.server)
@@ -117,65 +732,179 @@ class OuroDaemon {
117
732
  message: "starting daemon server",
118
733
  meta: { socketPath: this.socketPath },
119
734
  });
735
+ try {
736
+ await this.startInner();
737
+ }
738
+ catch (err) {
739
+ // Emit a paired terminating event (`_error`) so the nerves audit's
740
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
741
+ // and `stop()` (which emits `server_end`) is never called.
742
+ (0, runtime_1.emitNervesEvent)({
743
+ level: "error",
744
+ component: "daemon",
745
+ event: "daemon.server_error",
746
+ message: "daemon start failed",
747
+ meta: {
748
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
749
+ },
750
+ });
751
+ throw err;
752
+ }
753
+ }
754
+ async startInner() {
120
755
  // Register update hooks and apply pending updates before starting agents
121
756
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
757
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
122
758
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
123
759
  await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
124
760
  // 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
- }
761
+ // Skip in dev mode — dev builds should not auto-update from npm
762
+ if (this.mode === "dev") {
763
+ (0, runtime_1.emitNervesEvent)({
764
+ component: "daemon",
765
+ event: "daemon.update_checker_skip",
766
+ message: "skipping update checker in dev mode",
767
+ meta: { reason: "dev mode" },
768
+ });
769
+ }
770
+ else {
771
+ (0, update_checker_1.startUpdateChecker)({
772
+ currentVersion,
773
+ deps: {
774
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
775
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
776
+ fetchRegistryJson: async () => {
777
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
778
+ return res.json();
150
779
  },
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();
780
+ /* v8 ignore stop */
781
+ },
782
+ });
783
+ }
784
+ // MCP connections are lazily initialized per-agent during senseTurn
785
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
786
+ await this.orphanStartupDrain(this.socketPath);
787
+ await this.openCommandSocket();
788
+ this.triggerAutoStartAgents();
789
+ this.triggerAutoStartSensesWhenAgentsSettled();
790
+ // Write all managed PIDs to disk so the next daemon can clean up
791
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
792
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
793
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
794
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
795
+ /* v8 ignore stop */
163
796
  this.scheduler.start?.();
164
797
  await this.scheduler.reconcile?.();
165
798
  await this.drainPendingBundleMessages();
166
799
  await this.drainPendingSenseMessages();
800
+ // startInner is only reachable when this.server is null (guarded in
801
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
802
+ // so mailboxServer is guaranteed unset here — no need for a guard.
803
+ try {
804
+ this.mailboxServer = await this.mailboxServerFactory();
805
+ }
806
+ catch (error) {
807
+ (0, runtime_1.emitNervesEvent)({
808
+ level: "warn",
809
+ component: "daemon",
810
+ event: "daemon.mailbox_start_failed",
811
+ message: `Mailbox server failed to start: ${String(error)}`,
812
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
813
+ });
814
+ }
815
+ }
816
+ triggerAutoStartAgents() {
817
+ if (this.processManager.triggerAutoStartAgents) {
818
+ this.processManager.triggerAutoStartAgents();
819
+ return;
820
+ }
821
+ void this.processManager.startAutoStartAgents().catch((error) => {
822
+ (0, runtime_1.emitNervesEvent)({
823
+ level: "error",
824
+ component: "daemon",
825
+ event: "daemon.agent_autostart_error",
826
+ message: "agent autostart failed after daemon socket opened",
827
+ meta: { error: error instanceof Error ? error.message : String(error) },
828
+ });
829
+ });
830
+ }
831
+ triggerAutoStartSenses() {
832
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
833
+ if (!this.senseManager)
834
+ return;
835
+ if (this.senseManager.triggerAutoStartSenses) {
836
+ this.senseManager.triggerAutoStartSenses();
837
+ return;
838
+ }
839
+ void this.senseManager.startAutoStartSenses().catch((error) => {
840
+ (0, runtime_1.emitNervesEvent)({
841
+ level: "error",
842
+ component: "daemon",
843
+ event: "daemon.sense_autostart_error",
844
+ message: "sense autostart failed after daemon socket opened",
845
+ meta: { error: error instanceof Error ? error.message : String(error) },
846
+ });
847
+ });
848
+ }
849
+ triggerAutoStartSensesWhenAgentsSettled() {
850
+ if (!this.senseManager)
851
+ return;
852
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
853
+ .some((snapshot) => snapshot.status === "starting");
854
+ if (!waitingOnAgents) {
855
+ this.triggerAutoStartSenses();
856
+ return;
857
+ }
858
+ this.senseAutostartTimer = setTimeout(() => {
859
+ this.senseAutostartTimer = null;
860
+ this.triggerAutoStartSensesWhenAgentsSettled();
861
+ }, 250);
862
+ }
863
+ async openCommandSocket() {
167
864
  if (fs.existsSync(this.socketPath)) {
168
865
  fs.unlinkSync(this.socketPath);
169
866
  }
170
- this.server = net.createServer((connection) => {
867
+ // allowHalfOpen: true lets the server keep its writable side open after
868
+ // the client sends FIN. Without this, when a client calls `client.end()`
869
+ // after writing a command, node closes the server's writable side
870
+ // automatically — so a long-running response (like an agent.senseTurn
871
+ // LLM turn that takes 5+ seconds) never reaches the client. The
872
+ // socket-client fix in #303/#334 also removed client.end() on the
873
+ // sending side, but this option is defense in depth: even if a future
874
+ // caller half-closes, the server still writes its response correctly.
875
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
171
876
  let raw = "";
172
877
  let responded = false;
878
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
879
+ connection.on("error", (err) => {
880
+ (0, runtime_1.emitNervesEvent)({
881
+ level: "warn",
882
+ component: "daemon",
883
+ event: "daemon.connection_error",
884
+ message: "socket connection error",
885
+ meta: { error: err.message, code: err.code ?? null },
886
+ });
887
+ });
888
+ /* v8 ignore stop */
173
889
  const flushResponse = async () => {
174
890
  if (responded)
175
891
  return;
176
892
  responded = true;
177
893
  const response = await this.handleRawPayload(raw);
178
- connection.end(response);
894
+ try {
895
+ connection.end(response);
896
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
897
+ }
898
+ catch (err) {
899
+ (0, runtime_1.emitNervesEvent)({
900
+ level: "warn",
901
+ component: "daemon",
902
+ event: "daemon.connection_end_error",
903
+ message: "failed to send response to client (EPIPE)",
904
+ meta: { error: err instanceof Error ? err.message : String(err) },
905
+ });
906
+ }
907
+ /* v8 ignore stop */
179
908
  };
180
909
  connection.on("data", (chunk) => {
181
910
  raw += chunk.toString("utf-8");
@@ -188,7 +917,23 @@ class OuroDaemon {
188
917
  const server = this.server;
189
918
  await new Promise((resolve, reject) => {
190
919
  server.once("error", reject);
191
- server.listen(this.socketPath, () => resolve());
920
+ server.listen(this.socketPath, () => {
921
+ // Replace the one-time error listener with a persistent one after successful listen
922
+ server.removeAllListeners("error");
923
+ this.socketIdentity = readSocketIdentity(this.socketPath);
924
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
925
+ server.on("error", (err) => {
926
+ (0, runtime_1.emitNervesEvent)({
927
+ level: "error",
928
+ component: "daemon",
929
+ event: "daemon.server_error",
930
+ message: "daemon server error after listen",
931
+ meta: { error: err.message, code: err.code ?? null },
932
+ });
933
+ });
934
+ /* v8 ignore stop */
935
+ resolve();
936
+ });
192
937
  });
193
938
  }
194
939
  async drainPendingBundleMessages() {
@@ -240,7 +985,7 @@ class OuroDaemon {
240
985
  }
241
986
  }
242
987
  /** Drains per-sense pending dirs for always-on senses across all agents. */
243
- static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
988
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
244
989
  async drainPendingSenseMessages() {
245
990
  if (!fs.existsSync(this.bundlesRoot))
246
991
  return;
@@ -327,26 +1072,104 @@ class OuroDaemon {
327
1072
  }
328
1073
  }
329
1074
  async stop() {
1075
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1076
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
1077
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
330
1078
  (0, runtime_1.emitNervesEvent)({
331
1079
  component: "daemon",
332
- event: "daemon.server_stop",
1080
+ event: "daemon.server_end",
333
1081
  message: "stopping daemon server",
334
1082
  meta: { socketPath: this.socketPath },
335
1083
  });
336
1084
  (0, update_checker_1.stopUpdateChecker)();
337
1085
  (0, mcp_manager_1.shutdownSharedMcpManager)();
338
1086
  this.scheduler.stop?.();
339
- await this.processManager.stopAll();
340
- await this.senseManager?.stopAll();
1087
+ this.healthMonitor.stopPeriodicChecks?.();
1088
+ if (this.senseAutostartTimer) {
1089
+ clearTimeout(this.senseAutostartTimer);
1090
+ this.senseAutostartTimer = null;
1091
+ }
1092
+ const workerStopTasks = [Promise.resolve().then(() => this.processManager.stopAll())];
1093
+ if (this.senseManager) {
1094
+ workerStopTasks.push(Promise.resolve().then(() => this.senseManager.stopAll()));
1095
+ }
1096
+ const workerStopResults = await Promise.allSettled(workerStopTasks);
1097
+ const workerStopFailures = workerStopResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
341
1098
  if (this.server) {
342
- await new Promise((resolve) => {
343
- this.server?.close(() => resolve());
344
- });
1099
+ // DO NOT `await` server.close() here. server.close() resolves only
1100
+ // after every open connection has closed. When stop() is invoked
1101
+ // from the daemon.stop command handler, the calling client's
1102
+ // connection is STILL open — its flushResponse() is currently
1103
+ // awaiting THIS function. Awaiting close() creates a deadlock:
1104
+ //
1105
+ // client → flushResponse → handleRawPayload → daemon.stop case
1106
+ // → stop() → await server.close() (waits for client's connection)
1107
+ // → client's connection waits for flushResponse to call
1108
+ // connection.end() → DEADLOCK
1109
+ //
1110
+ // Both processes sit in kevent forever. Verified live on
1111
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
1112
+ // line for 5+ minutes after a client sent daemon.stop, while the
1113
+ // client (alpha.270 ouro up) hung waiting for the response.
1114
+ //
1115
+ // This regressed when #303/#334/#339 stopped half-closing the
1116
+ // client socket and switched the server to allowHalfOpen: true.
1117
+ // Previously, the client called .end() after writing its command,
1118
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
1119
+ // the server's writable side — incidentally unblocking
1120
+ // server.close() before the response was sent. The half-close
1121
+ // breakage masked this deadlock; the fix exposed it.
1122
+ //
1123
+ // Solution: fire close() and let it complete asynchronously. Once
1124
+ // stop() returns, the daemon.stop case returns its response,
1125
+ // flushResponse() calls connection.end(response), the connection
1126
+ // closes, and server.close()'s pending callback fires. The event
1127
+ // loop drains and the daemon exits cleanly.
1128
+ this.server.close();
345
1129
  this.server = null;
346
1130
  }
347
- if (fs.existsSync(this.socketPath)) {
1131
+ if (this.mailboxServer) {
1132
+ await this.mailboxServer.stop();
1133
+ this.mailboxServer = null;
1134
+ }
1135
+ const socketPathExists = fs.existsSync(this.socketPath);
1136
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1137
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
348
1138
  fs.unlinkSync(this.socketPath);
349
1139
  }
1140
+ else if (socketPathExists) {
1141
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1142
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1143
+ (0, runtime_1.emitNervesEvent)({
1144
+ level: "warn",
1145
+ component: "daemon",
1146
+ event: "daemon.socket_cleanup_skipped",
1147
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1148
+ meta: {
1149
+ socketPath: this.socketPath,
1150
+ expectedDev: expectedSocketIdentity.dev,
1151
+ expectedIno: expectedSocketIdentity.ino,
1152
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1153
+ actualDev: actualSocketIdentity.dev,
1154
+ actualIno: actualSocketIdentity.ino,
1155
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1156
+ },
1157
+ });
1158
+ }
1159
+ this.socketIdentity = null;
1160
+ if (workerStopFailures.length > 0) {
1161
+ const errorReason = `daemon shutdown could not drain ${workerStopFailures.length} managed worker group(s)`;
1162
+ (0, runtime_1.emitNervesEvent)({
1163
+ level: "error",
1164
+ component: "daemon",
1165
+ event: "daemon.worker_shutdown_error",
1166
+ message: errorReason,
1167
+ meta: {
1168
+ failures: workerStopFailures.map((error) => error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error rejection @preserve */ String(error)),
1169
+ },
1170
+ });
1171
+ throw new AggregateError(workerStopFailures, errorReason);
1172
+ }
350
1173
  }
351
1174
  async handleRawPayload(raw) {
352
1175
  try {
@@ -368,32 +1191,383 @@ class OuroDaemon {
368
1191
  message: "handling daemon command",
369
1192
  meta: { kind: command.kind },
370
1193
  });
1194
+ try {
1195
+ return await this.handleCommandInner(command);
1196
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1197
+ }
1198
+ catch (error) {
1199
+ (0, runtime_1.emitNervesEvent)({
1200
+ level: "error",
1201
+ component: "daemon",
1202
+ event: "daemon.command_error",
1203
+ message: "unexpected error handling daemon command",
1204
+ meta: {
1205
+ kind: command.kind,
1206
+ error: error instanceof Error ? error.message : String(error),
1207
+ stack: error instanceof Error ? error.stack ?? null : null,
1208
+ },
1209
+ });
1210
+ throw error;
1211
+ }
1212
+ /* v8 ignore stop */
1213
+ }
1214
+ hasManagedPrivateRuntime(agent) {
1215
+ return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1216
+ }
1217
+ buildPrivateRuntimeWakeRequest(command) {
1218
+ if (command.kind === "inner.wake") {
1219
+ return {
1220
+ agent: command.agent,
1221
+ origin: "daemon.private.wake",
1222
+ reason: "legacy inner.wake compatibility alias",
1223
+ providerLane: "inner",
1224
+ triggerSource: "legacy",
1225
+ budgetClass: "interactive",
1226
+ originRefs: [{ kind: "daemon-command", id: "inner.wake" }],
1227
+ };
1228
+ }
1229
+ const hasNoSendCapability = command.originRefs?.some((ref) => ref.kind === "capability" && ref.id === "no-send") ?? false;
1230
+ if ((command.noSend === true) !== hasNoSendCapability) {
1231
+ throw new Error("private-runtime no-send capability does not match its bound origin reference");
1232
+ }
1233
+ return {
1234
+ agent: command.agent,
1235
+ origin: "daemon.private.wake",
1236
+ reason: command.reason ?? "manual private-runtime wake",
1237
+ providerLane: "inner",
1238
+ triggerSource: command.triggerSource ?? "manual",
1239
+ budgetClass: command.budgetClass ?? "interactive",
1240
+ ...(command.idempotencyKey ? { idempotencyKey: command.idempotencyKey } : {}),
1241
+ originRefs: command.originRefs ?? [{ kind: "daemon-command", id: "private.wake" }],
1242
+ };
1243
+ }
1244
+ buildAwaitPrivateWakeCommand(command) {
1245
+ return (0, await_private_wake_1.buildAwaitPrivateWakeCommand)({
1246
+ agent: command.agent,
1247
+ awaitName: command.awaitName,
1248
+ triggerSource: "await-poke",
1249
+ });
1250
+ }
1251
+ buildTaskPokePrivateWakeCommand(command, receiptId) {
1252
+ return {
1253
+ kind: "private.wake",
1254
+ agent: command.agent,
1255
+ reason: `task poke ${command.taskId}`,
1256
+ triggerSource: "task-poke",
1257
+ budgetClass: "scheduled",
1258
+ idempotencyKey: `task-poke:${command.agent}:${command.taskId}:${receiptId}`,
1259
+ originRefs: [
1260
+ { kind: "task", id: command.taskId },
1261
+ { kind: "queue-receipt", id: receiptId },
1262
+ { kind: "daemon-command", id: "task.poke" },
1263
+ ],
1264
+ };
1265
+ }
1266
+ buildExternalEventPrivateWakeCommand(command, receiptId) {
1267
+ return {
1268
+ kind: "private.wake",
1269
+ agent: command.agent,
1270
+ reason: `external event ${command.source}/${command.eventType}`,
1271
+ triggerSource: "external-event",
1272
+ budgetClass: "interactive",
1273
+ idempotencyKey: `external-event:${command.agent}:${command.source}:${command.eventId}`,
1274
+ originRefs: [
1275
+ { kind: "external-event", id: command.eventId, source: command.source, eventType: command.eventType },
1276
+ { kind: "queue-receipt", id: receiptId },
1277
+ { kind: "daemon-command", id: "external.event.submit" },
1278
+ ],
1279
+ };
1280
+ }
1281
+ resolveHabitDispatch(options) {
1282
+ const agentRoot = path.join(this.bundlesRoot, `${options.agent}.ouro`);
1283
+ const habitPath = path.join(agentRoot, "habits", `${options.habitName}.md`);
1284
+ const isRsvp = (0, habit_policy_1.isRsvpHabitName)(options.habitName);
1285
+ let readFailure = null;
1286
+ let habit;
1287
+ if (!fs.existsSync(habitPath)) {
1288
+ readFailure = "missing";
1289
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", "habit file not found");
1290
+ }
1291
+ else {
1292
+ try {
1293
+ habit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1294
+ }
1295
+ catch (error) {
1296
+ readFailure = "read";
1297
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", messageFromHabitPokeError(error));
1298
+ }
1299
+ }
1300
+ if (habit.status !== "active") {
1301
+ let skipReason = `habit status ${habit.status} is non-executable`;
1302
+ if (isRsvp && habit.status === "degraded") {
1303
+ if (readFailure === "missing") {
1304
+ skipReason = "RSVP habit file not found";
1305
+ }
1306
+ else {
1307
+ skipReason = `RSVP habit metadata invalid: ${habit.degradedDetail ?? habit.degradedReason}`;
1308
+ }
1309
+ }
1310
+ else if (readFailure === "missing"
1311
+ && options.source === "habit-poke"
1312
+ && options.trigger !== "manual"
1313
+ && options.trigger !== "poke") {
1314
+ skipReason = "habit file not found";
1315
+ }
1316
+ return { kind: "skipped", habit, skipReason };
1317
+ }
1318
+ if (isRsvp && !habit.rsvp) {
1319
+ return {
1320
+ kind: "skipped",
1321
+ habit,
1322
+ skipReason: "RSVP habit metadata is required before private runtime wake",
1323
+ };
1324
+ }
1325
+ if (options.trigger === "poke" || options.trigger === "manual") {
1326
+ return { kind: "ready", habit };
1327
+ }
1328
+ if (typeof options.occurrenceId === "string" && options.occurrenceId.trim().length > 0) {
1329
+ return { kind: "ready", habit, occurrenceId: options.occurrenceId.trim() };
1330
+ }
1331
+ if (habit.cadence === null) {
1332
+ return { kind: "skipped", habit, skipReason: "habit has no cadence" };
1333
+ }
1334
+ if (habit.lastRun === null) {
1335
+ return { kind: "ready", habit, occurrenceId: `${options.trigger}:first-run:${habit.cadence}` };
1336
+ }
1337
+ return {
1338
+ kind: "ready",
1339
+ habit,
1340
+ occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}`,
1341
+ };
1342
+ }
1343
+ emitHabitDispatchSkipped(options) {
1344
+ (0, runtime_1.emitNervesEvent)({
1345
+ level: "warn",
1346
+ component: "daemon",
1347
+ event: "daemon.habit_dispatch_skipped",
1348
+ message: "habit dispatch rejected by current lifecycle state",
1349
+ meta: {
1350
+ agent: options.agent,
1351
+ habitName: options.habitName,
1352
+ trigger: options.trigger,
1353
+ status: options.resolution.habit.status,
1354
+ degradedReason: options.resolution.habit.status === "degraded"
1355
+ ? options.resolution.habit.degradedReason
1356
+ : null,
1357
+ detail: options.resolution.habit.status === "degraded"
1358
+ ? options.resolution.habit.degradedDetail
1359
+ : null,
1360
+ reason: options.resolution.skipReason,
1361
+ },
1362
+ });
1363
+ }
1364
+ emitHabitDispatchReady(options) {
1365
+ (0, runtime_1.emitNervesEvent)({
1366
+ component: "daemon",
1367
+ event: "daemon.habit_dispatch_ready",
1368
+ message: "habit dispatch accepted by current lifecycle state",
1369
+ meta: {
1370
+ agent: options.agent,
1371
+ habitName: options.habitName,
1372
+ trigger: options.trigger,
1373
+ status: options.resolution.habit.status,
1374
+ occurrenceId: options.resolution.occurrenceId ?? null,
1375
+ },
1376
+ });
1377
+ }
1378
+ skippedHabitDispatchResponse(options) {
1379
+ return {
1380
+ ok: true,
1381
+ message: `skipped scheduled habit ${options.habitName} for ${options.agent}: ${options.skipReason}`,
1382
+ };
1383
+ }
1384
+ async runNativeRsvpHabit(command, trigger, occurrenceId, noSend = false) {
1385
+ const runner = this.rsvpHabitRunner ?? (async (input) => {
1386
+ const { runNativeRsvpHabit } = await Promise.resolve().then(() => __importStar(require("../../rsvp/native-habit-runner")));
1387
+ return runNativeRsvpHabit(input);
1388
+ });
1389
+ const result = await runner({
1390
+ agent: command.agent,
1391
+ bundlesRoot: this.bundlesRoot,
1392
+ habitName: command.habitName,
1393
+ trigger,
1394
+ ...(occurrenceId ? { occurrenceId } : {}),
1395
+ ...(noSend ? { noSend: true } : {}),
1396
+ });
1397
+ if (noSend) {
1398
+ const payload = result.payload;
1399
+ const status = payload?.status;
1400
+ const transportInvocationCount = payload?.transportInvocationCount;
1401
+ const contractError = "native RSVP habit probe violated the immutable no-send result contract";
1402
+ if (!result.ok) {
1403
+ return {
1404
+ ok: false,
1405
+ error: result.message,
1406
+ data: {
1407
+ ok: false,
1408
+ noSend: true,
1409
+ status: typeof status === "string" ? status : "degraded",
1410
+ transportInvocationCount: null,
1411
+ error: result.message,
1412
+ },
1413
+ };
1414
+ }
1415
+ if (payload?.noSend !== true
1416
+ || typeof status !== "string"
1417
+ || typeof transportInvocationCount !== "number"
1418
+ || transportInvocationCount !== 0) {
1419
+ return {
1420
+ ok: false,
1421
+ error: contractError,
1422
+ data: {
1423
+ ok: false,
1424
+ noSend: true,
1425
+ status: typeof status === "string" ? status : "degraded",
1426
+ transportInvocationCount: null,
1427
+ error: contractError,
1428
+ },
1429
+ };
1430
+ }
1431
+ return {
1432
+ ok: true,
1433
+ message: result.message,
1434
+ data: { noSend: true, status, transportInvocationCount: 0 },
1435
+ };
1436
+ }
1437
+ return {
1438
+ ok: result.ok,
1439
+ message: result.message,
1440
+ data: result,
1441
+ };
1442
+ }
1443
+ buildPrivateRuntimeWorkerWakeMessage(command, decision) {
1444
+ const awaitName = (0, await_private_wake_1.awaitNameFromPrivateWakeCommand)(command);
1445
+ if (awaitName) {
1446
+ return {
1447
+ type: "await",
1448
+ awaitName,
1449
+ privateTurnDecision: decision,
1450
+ };
1451
+ }
1452
+ const taskId = taskIdFromTaskPokePrivateWakeCommand(command);
1453
+ if (taskId) {
1454
+ return {
1455
+ type: "poke",
1456
+ taskId,
1457
+ privateTurnDecision: decision,
1458
+ };
1459
+ }
1460
+ const habitMessage = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1461
+ if (habitMessage) {
1462
+ return {
1463
+ type: "habit",
1464
+ habitName: habitMessage.habitName,
1465
+ trigger: habitMessage.trigger,
1466
+ ...(habitMessage.noSend ? { noSend: true } : {}),
1467
+ privateTurnDecision: decision,
1468
+ };
1469
+ }
1470
+ return { type: "message", privateTurnDecision: decision };
1471
+ }
1472
+ queueExternalEventForPrivateRuntime(record) {
1473
+ 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);
1474
+ const originKey = `${record.source}:${record.eventId}`;
1475
+ const parsedReceivedAt = Date.parse(record.receivedAt);
1476
+ (0, pending_1.queuePendingMessage)(pendingDir, {
1477
+ from: "ouro-external-event",
1478
+ friendId: "ouro-external-event",
1479
+ channel: "external-event",
1480
+ key: originKey,
1481
+ content: (0, router_1.buildExternalEventMessage)(record),
1482
+ timestamp: Number.isFinite(parsedReceivedAt) ? parsedReceivedAt : Date.now(),
1483
+ delegatedFrom: {
1484
+ friendId: "ouro-external-event",
1485
+ channel: "external-event",
1486
+ key: originKey,
1487
+ },
1488
+ obligationStatus: "pending",
1489
+ mode: "relay",
1490
+ });
1491
+ (0, runtime_1.emitNervesEvent)({
1492
+ component: "daemon",
1493
+ event: "daemon.external_event_private_runtime_queued",
1494
+ message: "queued external event for private-runtime attention",
1495
+ meta: {
1496
+ agent: record.agent,
1497
+ source: record.source,
1498
+ eventType: record.eventType,
1499
+ eventId: record.eventId,
1500
+ pendingDir,
1501
+ },
1502
+ });
1503
+ }
1504
+ async handlePrivateRuntimeWake(command, beforeDispatch) {
1505
+ if (!this.hasManagedPrivateRuntime(command.agent)) {
1506
+ return {
1507
+ ok: false,
1508
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1509
+ };
1510
+ }
1511
+ const decision = await (0, private_runtime_1.requestPrivateTurnDecision)(this.buildPrivateRuntimeWakeRequest(command), {
1512
+ bundlesRoot: this.bundlesRoot,
1513
+ ...this.privateRuntimePolicyDeps,
1514
+ });
1515
+ if (!decision.executable) {
1516
+ return {
1517
+ ok: true,
1518
+ message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
1519
+ data: { decision },
1520
+ };
1521
+ }
1522
+ await beforeDispatch?.(decision);
1523
+ await this.processManager.startAgent(command.agent);
1524
+ this.processManager.sendToAgent?.(command.agent, this.buildPrivateRuntimeWorkerWakeMessage(command, decision));
1525
+ return {
1526
+ ok: true,
1527
+ message: `woke private runtime for ${command.agent}`,
1528
+ data: { decision },
1529
+ };
1530
+ }
1531
+ async handleCommandInner(command) {
371
1532
  switch (command.kind) {
372
1533
  case "daemon.start":
373
1534
  await this.start();
374
1535
  return { ok: true, message: "daemon started" };
375
1536
  case "daemon.stop":
376
- await this.stop();
1537
+ try {
1538
+ await this.stop();
1539
+ }
1540
+ finally {
1541
+ this.onStopCommandComplete?.();
1542
+ }
377
1543
  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),
1544
+ case "daemon.restart": {
1545
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1546
+ // policy the process is auto-restarted on exit, so daemon.restart and
1547
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1548
+ // the process simply exits — same observable behavior as daemon.stop.
1549
+ (0, runtime_1.emitNervesEvent)({
1550
+ component: "daemon",
1551
+ event: "daemon.restart_requested",
1552
+ message: "daemon restart requested",
1553
+ meta: {
1554
+ reason: command.reason ?? null,
1555
+ requestedBy: command.requestedBy ?? null,
393
1556
  },
394
- workers,
395
- senses,
1557
+ });
1558
+ try {
1559
+ await this.stop();
1560
+ }
1561
+ finally {
1562
+ this.onStopCommandComplete?.();
1563
+ }
1564
+ return {
1565
+ ok: true,
1566
+ message: "daemon restarting — launchctl will respawn",
396
1567
  };
1568
+ }
1569
+ case "daemon.status": {
1570
+ const data = this.buildStatusPayload();
397
1571
  return {
398
1572
  ok: true,
399
1573
  summary: formatStatusSummary(data),
@@ -412,15 +1586,112 @@ class OuroDaemon {
412
1586
  message: "log streaming available via ouro logs",
413
1587
  data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
414
1588
  };
1589
+ case "daemon.sense_revive": {
1590
+ if (!isValidSenseReviveCommand(command)) {
1591
+ return {
1592
+ ok: false,
1593
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
1594
+ };
1595
+ }
1596
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
1597
+ if (revivedSenseRow) {
1598
+ return {
1599
+ ok: true,
1600
+ message: `revived ${command.agent}/${command.sense}`,
1601
+ data: revivedSenseRow,
1602
+ };
1603
+ }
1604
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
1605
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
1606
+ if (managedSenseSnapshots.length === 0) {
1607
+ return {
1608
+ ok: false,
1609
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
1610
+ };
1611
+ }
1612
+ const exactTargetName = `${command.agent}:${command.sense}`;
1613
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
1614
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
1615
+ if (!target) {
1616
+ return {
1617
+ ok: false,
1618
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
1619
+ };
1620
+ }
1621
+ this.processManager.resetAgentFailureState(target.name);
1622
+ await this.processManager.startAgent(target.name);
1623
+ const freshSnapshot = this.processManager.listAgentSnapshots()
1624
+ .find((snapshot) => snapshot.name === target.name) ?? target;
1625
+ return {
1626
+ ok: true,
1627
+ message: `revived ${command.agent}/${command.sense}`,
1628
+ data: freshSnapshot,
1629
+ };
1630
+ }
415
1631
  case "agent.start":
416
1632
  await this.processManager.startAgent(command.agent);
417
1633
  return { ok: true, message: `started ${command.agent}` };
418
1634
  case "agent.stop":
419
1635
  await this.processManager.stopAgent?.(command.agent);
420
1636
  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}` };
1637
+ case "agent.restart": {
1638
+ if (!this.processManager.restartAgent) {
1639
+ return { ok: false, error: "Managed agent restart is not available." };
1640
+ }
1641
+ const managedSnapshot = this.processManager.listAgentSnapshots()
1642
+ .find((snapshot) => snapshot.name === command.agent);
1643
+ if (!managedSnapshot) {
1644
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
1645
+ }
1646
+ if (managedSnapshot.autoStart === false && managedSnapshot.status === "stopped") {
1647
+ return { ok: true, message: `restart skipped for parked non-autostart agent '${command.agent}'` };
1648
+ }
1649
+ const restartWork = command.skipConfigCheck === true
1650
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
1651
+ : this.processManager.restartAgent(command.agent);
1652
+ void restartWork.catch((error) => {
1653
+ (0, runtime_1.emitNervesEvent)({
1654
+ level: "error",
1655
+ component: "daemon",
1656
+ event: "daemon.agent_restart_request_error",
1657
+ message: "managed agent restart failed after request acknowledgement",
1658
+ meta: {
1659
+ agent: command.agent,
1660
+ error: error instanceof Error ? error.message : String(error),
1661
+ },
1662
+ });
1663
+ });
1664
+ return { ok: true, message: `restart requested for ${command.agent}` };
1665
+ }
1666
+ case "agent.ask":
1667
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
1668
+ case "agent.status":
1669
+ return (0, agent_service_1.handleAgentStatus)(command);
1670
+ case "agent.catchup":
1671
+ return (0, agent_service_1.handleAgentCatchup)(command);
1672
+ case "agent.delegate":
1673
+ return (0, agent_service_1.handleAgentDelegate)(command);
1674
+ case "agent.getContext":
1675
+ return (0, agent_service_1.handleAgentGetContext)(command);
1676
+ case "agent.searchFacts":
1677
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
1678
+ case "agent.getTask":
1679
+ return (0, agent_service_1.handleAgentGetTask)(command);
1680
+ case "agent.checkScope":
1681
+ return (0, agent_service_1.handleAgentCheckScope)(command);
1682
+ case "agent.requestDecision":
1683
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
1684
+ case "agent.checkGuidance":
1685
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
1686
+ case "agent.reportProgress":
1687
+ return (0, agent_service_1.handleAgentReportProgress)(command);
1688
+ case "agent.reportBlocker":
1689
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
1690
+ case "agent.reportComplete":
1691
+ return (0, agent_service_1.handleAgentReportComplete)(command);
1692
+ case "agent.senseTurn":
1693
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
1694
+ /* v8 ignore stop */
424
1695
  case "cron.list": {
425
1696
  const jobs = this.scheduler.listJobs();
426
1697
  const summary = jobs.length === 0
@@ -429,10 +1700,28 @@ class OuroDaemon {
429
1700
  return { ok: true, summary, data: jobs };
430
1701
  }
431
1702
  case "cron.trigger": {
1703
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
1704
+ if (habitResult?.ok) {
1705
+ return { ok: true, message: habitResult.message };
1706
+ }
432
1707
  const result = await this.scheduler.triggerJob(command.jobId);
433
1708
  return { ok: result.ok, message: result.message };
434
1709
  }
435
1710
  case "message.send": {
1711
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
1712
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
1713
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
1714
+ // events to avoid waking the agent on every tool call. The hook's
1715
+ // intent was completely defeated by this handler calling
1716
+ // `sendToAgent({type: "message"})`, which woke the private runtime
1717
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
1718
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
1719
+ //
1720
+ // Callers that want immediate processing must send `private.wake`
1721
+ // explicitly after message.send. The CLI `ouro msg` does so
1722
+ // (lifecycle-boundary delivery should wake); the hook does so
1723
+ // only on session-start / stop, not per tool-use; the API does
1724
+ // not (notifications go to the queue).
436
1725
  const receipt = await this.router.send({
437
1726
  from: command.from,
438
1727
  to: command.to,
@@ -441,7 +1730,6 @@ class OuroDaemon {
441
1730
  sessionId: command.sessionId,
442
1731
  taskRef: command.taskRef,
443
1732
  });
444
- this.processManager.sendToAgent?.(command.to, { type: "message" });
445
1733
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
446
1734
  }
447
1735
  case "message.poll": {
@@ -452,13 +1740,110 @@ class OuroDaemon {
452
1740
  data: messages,
453
1741
  };
454
1742
  }
455
- case "inner.wake":
456
- await this.processManager.startAgent(command.agent);
457
- this.processManager.sendToAgent?.(command.agent, { type: "message" });
1743
+ case "external.event.submit": {
1744
+ const record = (0, router_1.recordExternalEvent)({
1745
+ agent: command.agent,
1746
+ source: command.source,
1747
+ eventType: command.eventType,
1748
+ eventId: command.eventId,
1749
+ summary: command.summary,
1750
+ evidence: command.evidence,
1751
+ payloadPath: command.payloadPath,
1752
+ priority: command.priority,
1753
+ }, {
1754
+ ...(this.externalEventRoot ? { root: this.externalEventRoot } : {}),
1755
+ });
1756
+ const receipt = await this.router.send({
1757
+ from: "ouro-external-event",
1758
+ to: command.agent,
1759
+ content: (0, router_1.buildExternalEventMessage)(record),
1760
+ priority: record.priority,
1761
+ sessionId: command.sessionId,
1762
+ taskRef: command.taskRef ?? `${record.source}:${record.eventId}`,
1763
+ });
1764
+ let wake = null;
1765
+ if (command.wake !== false) {
1766
+ wake = await this.handlePrivateRuntimeWake(this.buildExternalEventPrivateWakeCommand(command, receipt.id), () => this.queueExternalEventForPrivateRuntime(record));
1767
+ }
458
1768
  return {
459
1769
  ok: true,
460
- message: `woke inner dialog for ${command.agent}`,
1770
+ message: command.wake === false
1771
+ ? `queued external event ${record.source}/${record.eventId} as ${receipt.id}`
1772
+ : `queued external event ${record.source}/${record.eventId} as ${receipt.id}; ${wake?.message ?? "wake skipped"}`,
1773
+ data: { event: record, receipt, wake },
461
1774
  };
1775
+ }
1776
+ case "private.decisions": {
1777
+ const requestedLimit = Number.isInteger(command.limit) && command.limit && command.limit > 0 ? command.limit : 20;
1778
+ const limit = Math.min(requestedLimit, 1000);
1779
+ const ledgerPath = (0, private_runtime_1.privateTurnLedgerPath)(command.agent, { bundlesRoot: this.bundlesRoot });
1780
+ const ledgerExists = fs.existsSync(ledgerPath);
1781
+ let decisions;
1782
+ try {
1783
+ decisions = ledgerExists ? (0, private_runtime_1.readPrivateTurnLedger)(ledgerPath) : [];
1784
+ }
1785
+ catch {
1786
+ return {
1787
+ ok: false,
1788
+ error: `private-runtime decision ledger is malformed: ${ledgerPath}; repair or remove malformed JSONL rows before reading decisions`,
1789
+ };
1790
+ }
1791
+ const guidance = ledgerExists
1792
+ ? undefined
1793
+ : `No private-runtime decision ledger exists for ${command.agent}; run an explicit private-runtime trigger or check ${path.dirname(ledgerPath)}.`;
1794
+ const payload = (0, private_runtime_1.buildPrivateDecisionReadPayload)({
1795
+ agent: command.agent,
1796
+ ledgerPath,
1797
+ decisions,
1798
+ limit,
1799
+ ...(guidance ? { guidance } : {}),
1800
+ });
1801
+ return {
1802
+ ok: true,
1803
+ summary: (0, private_runtime_1.privateDecisionCountSummary)(payload.decisions.length),
1804
+ ...(guidance ? { message: guidance } : {}),
1805
+ data: payload,
1806
+ };
1807
+ }
1808
+ case "inner.wake":
1809
+ return this.handlePrivateRuntimeWake(command);
1810
+ case "private.wake": {
1811
+ const scheduledHabit = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1812
+ if (!scheduledHabit || !this.hasManagedPrivateRuntime(command.agent)) {
1813
+ return this.handlePrivateRuntimeWake(command);
1814
+ }
1815
+ const occurrenceRef = command.originRefs?.find((ref) => ref.kind === "habit-occurrence");
1816
+ const occurrenceId = typeof occurrenceRef?.id === "string" && occurrenceRef.id.trim().length > 0
1817
+ ? occurrenceRef.id.trim()
1818
+ : undefined;
1819
+ const resolution = this.resolveHabitDispatch({
1820
+ agent: command.agent,
1821
+ habitName: scheduledHabit.habitName,
1822
+ trigger: scheduledHabit.trigger,
1823
+ source: "private-wake",
1824
+ ...(occurrenceId ? { occurrenceId } : {}),
1825
+ });
1826
+ if (resolution.kind === "skipped") {
1827
+ this.emitHabitDispatchSkipped({
1828
+ agent: command.agent,
1829
+ habitName: scheduledHabit.habitName,
1830
+ trigger: scheduledHabit.trigger,
1831
+ resolution,
1832
+ });
1833
+ return this.skippedHabitDispatchResponse({
1834
+ agent: command.agent,
1835
+ habitName: scheduledHabit.habitName,
1836
+ skipReason: resolution.skipReason,
1837
+ });
1838
+ }
1839
+ this.emitHabitDispatchReady({
1840
+ agent: command.agent,
1841
+ habitName: scheduledHabit.habitName,
1842
+ trigger: scheduledHabit.trigger,
1843
+ resolution,
1844
+ });
1845
+ return this.handlePrivateRuntimeWake(command);
1846
+ }
462
1847
  case "chat.connect":
463
1848
  await this.processManager.startAgent(command.agent);
464
1849
  return {
@@ -466,6 +1851,12 @@ class OuroDaemon {
466
1851
  message: `connected to ${command.agent}`,
467
1852
  };
468
1853
  case "task.poke": {
1854
+ if (!isValidTaskPokeCommand(command)) {
1855
+ return {
1856
+ ok: false,
1857
+ error: "Invalid task.poke payload: expected non-empty string fields 'agent' and 'taskId'.",
1858
+ };
1859
+ }
469
1860
  const receipt = await this.router.send({
470
1861
  from: "ouro-poke",
471
1862
  to: command.agent,
@@ -474,14 +1865,145 @@ class OuroDaemon {
474
1865
  taskRef: command.taskId,
475
1866
  });
476
1867
  await this.scheduler.recordTaskRun?.(command.agent, command.taskId);
477
- this.processManager.sendToAgent?.(command.agent, { type: "poke", taskId: command.taskId });
1868
+ await this.handlePrivateRuntimeWake(this.buildTaskPokePrivateWakeCommand(command, receipt.id));
478
1869
  return {
479
1870
  ok: true,
480
1871
  message: `queued poke ${receipt.id}`,
481
1872
  data: receipt,
482
1873
  };
483
1874
  }
1875
+ case "habit.poke": {
1876
+ if (!isValidHabitPokeCommand(command)) {
1877
+ return {
1878
+ ok: false,
1879
+ error: "Invalid habit.poke payload: expected non-empty string fields 'agent' and 'habitName'.",
1880
+ };
1881
+ }
1882
+ const trigger = command.trigger ?? "poke";
1883
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
1884
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
1885
+ }
1886
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
1887
+ return {
1888
+ ok: false,
1889
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1890
+ };
1891
+ }
1892
+ const resolution = this.resolveHabitDispatch({
1893
+ agent: command.agent,
1894
+ habitName: command.habitName,
1895
+ trigger,
1896
+ source: "habit-poke",
1897
+ ...(command.occurrenceId ? { occurrenceId: command.occurrenceId } : {}),
1898
+ });
1899
+ if (resolution.kind === "skipped") {
1900
+ this.emitHabitDispatchSkipped({
1901
+ agent: command.agent,
1902
+ habitName: command.habitName,
1903
+ trigger,
1904
+ resolution,
1905
+ });
1906
+ return this.skippedHabitDispatchResponse({
1907
+ agent: command.agent,
1908
+ habitName: command.habitName,
1909
+ skipReason: resolution.skipReason,
1910
+ });
1911
+ }
1912
+ this.emitHabitDispatchReady({
1913
+ agent: command.agent,
1914
+ habitName: command.habitName,
1915
+ trigger,
1916
+ resolution,
1917
+ });
1918
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
1919
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId);
1920
+ }
1921
+ return this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
1922
+ agent: command.agent,
1923
+ habitName: command.habitName,
1924
+ trigger,
1925
+ sourceRef: { kind: "daemon-command", id: "habit.poke" },
1926
+ occurrenceId: resolution.occurrenceId,
1927
+ }));
1928
+ }
1929
+ case "habit.probe": {
1930
+ if (!isValidHabitProbeCommand(command)) {
1931
+ return {
1932
+ ok: false,
1933
+ error: "Invalid habit.probe payload: expected non-empty agent/habitName and noSend=true.",
1934
+ };
1935
+ }
1936
+ const trigger = "manual";
1937
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
1938
+ return {
1939
+ ok: false,
1940
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1941
+ };
1942
+ }
1943
+ const resolution = this.resolveHabitDispatch({
1944
+ agent: command.agent,
1945
+ habitName: command.habitName,
1946
+ trigger,
1947
+ source: "habit-probe",
1948
+ });
1949
+ if (resolution.kind === "skipped") {
1950
+ this.emitHabitDispatchSkipped({
1951
+ agent: command.agent,
1952
+ habitName: command.habitName,
1953
+ trigger,
1954
+ resolution,
1955
+ });
1956
+ return {
1957
+ ok: true,
1958
+ message: `habit probe rejected by lifecycle: status=${resolution.habit.status}`,
1959
+ data: {
1960
+ noSend: true,
1961
+ status: resolution.habit.status,
1962
+ transportInvocationCount: 0,
1963
+ },
1964
+ };
1965
+ }
1966
+ this.emitHabitDispatchReady({
1967
+ agent: command.agent,
1968
+ habitName: command.habitName,
1969
+ trigger,
1970
+ resolution,
1971
+ });
1972
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
1973
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId, true);
1974
+ }
1975
+ const wake = await this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
1976
+ agent: command.agent,
1977
+ habitName: command.habitName,
1978
+ trigger,
1979
+ sourceRef: { kind: "daemon-command", id: "habit.probe" },
1980
+ occurrenceId: resolution.occurrenceId,
1981
+ noSend: true,
1982
+ }));
1983
+ if (!wake.ok)
1984
+ return wake;
1985
+ const denied = wake.data
1986
+ ?.decision?.executable === false;
1987
+ const error = denied
1988
+ ? "non-RSVP habit probe was not executed because private-runtime policy denied execution"
1989
+ : "non-RSVP habit probe completion is asynchronous; zero-transport evidence is unverified";
1990
+ return {
1991
+ ok: false,
1992
+ error,
1993
+ data: {
1994
+ ok: false,
1995
+ noSend: true,
1996
+ status: resolution.habit.status,
1997
+ transportInvocationCount: null,
1998
+ error,
1999
+ },
2000
+ };
2001
+ }
2002
+ case "await.poke": {
2003
+ return this.handlePrivateRuntimeWake(this.buildAwaitPrivateWakeCommand(command));
2004
+ }
484
2005
  case "mcp.list": {
2006
+ (0, identity_1.setAgentName)(command.agent ?? "default");
485
2007
  const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
486
2008
  if (!mcpManager) {
487
2009
  return { ok: true, data: [], message: "no MCP servers configured" };
@@ -489,6 +2011,7 @@ class OuroDaemon {
489
2011
  return { ok: true, data: mcpManager.listAllTools() };
490
2012
  }
491
2013
  case "mcp.call": {
2014
+ (0, identity_1.setAgentName)(command.agent ?? "default");
492
2015
  const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
493
2016
  if (!mcpCallManager) {
494
2017
  return { ok: false, error: "no MCP servers configured" };
@@ -506,7 +2029,7 @@ class OuroDaemon {
506
2029
  case "hatch.start":
507
2030
  return {
508
2031
  ok: true,
509
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
2032
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
510
2033
  };
511
2034
  default:
512
2035
  return {