@ouro.bot/cli 0.1.0-alpha.30 → 0.1.0-alpha.301

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 (284) hide show
  1. package/README.md +188 -190
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1814 -0
  5. package/dist/arc/attention-types.js +8 -0
  6. package/dist/arc/cares.js +140 -0
  7. package/dist/arc/episodes.js +117 -0
  8. package/dist/arc/intentions.js +133 -0
  9. package/dist/arc/json-store.js +117 -0
  10. package/dist/arc/obligations.js +237 -0
  11. package/dist/arc/packets.js +203 -0
  12. package/dist/arc/presence.js +185 -0
  13. package/dist/heart/active-work.js +832 -0
  14. package/dist/heart/agent-entry.js +37 -2
  15. package/dist/heart/attachments/image-normalize.js +194 -0
  16. package/dist/heart/attachments/materialize.js +230 -0
  17. package/dist/heart/attachments/render.js +29 -0
  18. package/dist/heart/attachments/store.js +103 -0
  19. package/dist/heart/attachments/types.js +138 -0
  20. package/dist/heart/auth/auth-flow.js +456 -0
  21. package/dist/heart/bridges/manager.js +358 -0
  22. package/dist/heart/bridges/state-machine.js +135 -0
  23. package/dist/heart/bridges/store.js +123 -0
  24. package/dist/heart/bundle-state.js +168 -0
  25. package/dist/heart/commitments.js +111 -0
  26. package/dist/heart/config-registry.js +304 -0
  27. package/dist/heart/config.js +63 -30
  28. package/dist/heart/core.js +669 -195
  29. package/dist/heart/cross-chat-delivery.js +131 -0
  30. package/dist/heart/daemon/agent-config-check.js +149 -0
  31. package/dist/heart/daemon/agent-discovery.js +79 -3
  32. package/dist/heart/daemon/agent-service.js +360 -0
  33. package/dist/heart/daemon/cadence.js +70 -0
  34. package/dist/heart/daemon/cli-defaults.js +574 -0
  35. package/dist/heart/daemon/cli-exec.js +1945 -0
  36. package/dist/heart/daemon/cli-parse.js +808 -0
  37. package/dist/heart/daemon/cli-render.js +503 -0
  38. package/dist/heart/daemon/cli-types.js +8 -0
  39. package/dist/heart/daemon/daemon-cli.js +29 -1171
  40. package/dist/heart/daemon/daemon-entry.js +245 -3
  41. package/dist/heart/daemon/daemon-health.js +136 -0
  42. package/dist/heart/daemon/daemon-runtime-sync.js +153 -12
  43. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  44. package/dist/heart/daemon/daemon.js +706 -57
  45. package/dist/heart/daemon/health-monitor.js +38 -0
  46. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  47. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  48. package/dist/heart/daemon/inner-status.js +89 -0
  49. package/dist/heart/daemon/launchd.js +46 -9
  50. package/dist/heart/daemon/log-tailer.js +82 -12
  51. package/dist/heart/daemon/logs-prune.js +105 -0
  52. package/dist/heart/daemon/message-router.js +17 -8
  53. package/dist/heart/daemon/os-cron-deps.js +134 -0
  54. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  55. package/dist/heart/daemon/process-manager.js +201 -0
  56. package/dist/heart/daemon/pulse.js +463 -0
  57. package/dist/heart/daemon/run-hooks.js +2 -0
  58. package/dist/heart/daemon/runtime-logging.js +67 -16
  59. package/dist/heart/daemon/runtime-metadata.js +101 -0
  60. package/dist/heart/daemon/runtime-mode.js +67 -0
  61. package/dist/heart/daemon/safe-mode.js +161 -0
  62. package/dist/heart/daemon/sense-manager.js +72 -3
  63. package/dist/heart/daemon/session-id-resolver.js +131 -0
  64. package/dist/heart/daemon/skill-management-installer.js +94 -0
  65. package/dist/heart/daemon/socket-client.js +307 -0
  66. package/dist/heart/daemon/task-scheduler.js +3 -25
  67. package/dist/heart/daemon/thoughts.js +510 -0
  68. package/dist/heart/delegation.js +62 -0
  69. package/dist/heart/habits/habit-migration.js +181 -0
  70. package/dist/heart/habits/habit-parser.js +140 -0
  71. package/dist/heart/habits/habit-scheduler.js +371 -0
  72. package/dist/heart/{daemon → hatch}/hatch-flow.js +30 -120
  73. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  74. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -7
  75. package/dist/heart/{daemon → hatch}/specialist-tools.js +49 -3
  76. package/dist/heart/identity.js +163 -60
  77. package/dist/heart/kicks.js +2 -20
  78. package/dist/heart/mcp/mcp-server.js +653 -0
  79. package/dist/heart/migrate-config.js +127 -0
  80. package/dist/heart/model-capabilities.js +59 -0
  81. package/dist/heart/outlook/outlook-http.js +439 -0
  82. package/dist/heart/outlook/outlook-read.js +1618 -0
  83. package/dist/heart/outlook/outlook-render.js +1032 -0
  84. package/dist/heart/outlook/outlook-types.js +7 -0
  85. package/dist/heart/outlook/outlook-view.js +194 -0
  86. package/dist/heart/progress-story.js +42 -0
  87. package/dist/heart/provider-failover.js +88 -0
  88. package/dist/heart/provider-ping.js +162 -0
  89. package/dist/heart/providers/anthropic-token.js +163 -0
  90. package/dist/heart/providers/anthropic.js +169 -46
  91. package/dist/heart/providers/azure.js +98 -11
  92. package/dist/heart/providers/error-classification.js +63 -0
  93. package/dist/heart/providers/github-copilot.js +136 -0
  94. package/dist/heart/providers/minimax-vlm.js +189 -0
  95. package/dist/heart/providers/minimax.js +23 -5
  96. package/dist/heart/providers/openai-codex.js +33 -22
  97. package/dist/heart/session-activity.js +172 -0
  98. package/dist/heart/session-recall.js +216 -0
  99. package/dist/heart/start-of-turn-packet.js +339 -0
  100. package/dist/heart/streaming.js +36 -27
  101. package/dist/heart/sync.js +332 -0
  102. package/dist/heart/target-resolution.js +127 -0
  103. package/dist/heart/tempo.js +93 -0
  104. package/dist/heart/temporal-view.js +41 -0
  105. package/dist/heart/tool-activity-callbacks.js +36 -0
  106. package/dist/heart/tool-description.js +135 -0
  107. package/dist/heart/tool-friction.js +55 -0
  108. package/dist/heart/tool-loop.js +200 -0
  109. package/dist/heart/turn-context.js +358 -0
  110. package/dist/heart/turn-coordinator.js +28 -0
  111. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
  112. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  113. package/dist/heart/{daemon → versioning}/ouro-path-installer.js +78 -35
  114. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  115. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  116. package/dist/heart/{daemon → versioning}/update-checker.js +12 -2
  117. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  118. package/dist/mind/associative-recall.js +135 -66
  119. package/dist/mind/bundle-manifest.js +8 -1
  120. package/dist/mind/context.js +125 -14
  121. package/dist/mind/diary-integrity.js +60 -0
  122. package/dist/mind/{memory.js → diary.js} +84 -96
  123. package/dist/mind/embedding-provider.js +60 -0
  124. package/dist/mind/file-state.js +179 -0
  125. package/dist/mind/first-impressions.js +14 -1
  126. package/dist/mind/friends/channel.js +56 -0
  127. package/dist/mind/friends/group-context.js +144 -0
  128. package/dist/mind/friends/resolver.js +37 -0
  129. package/dist/mind/friends/store-file.js +58 -3
  130. package/dist/mind/friends/trust-explanation.js +74 -0
  131. package/dist/mind/friends/types.js +8 -0
  132. package/dist/mind/journal-index.js +161 -0
  133. package/dist/mind/obligation-steering.js +221 -0
  134. package/dist/mind/pending.js +76 -9
  135. package/dist/mind/prompt.js +922 -109
  136. package/dist/mind/scrutiny.js +173 -0
  137. package/dist/mind/token-estimate.js +8 -12
  138. package/dist/nerves/cli-logging.js +7 -1
  139. package/dist/nerves/coverage/audit.js +1 -1
  140. package/dist/nerves/coverage/file-completeness.js +59 -5
  141. package/dist/nerves/coverage/run-artifacts.js +1 -1
  142. package/dist/nerves/event-buffer.js +111 -0
  143. package/dist/nerves/index.js +224 -4
  144. package/dist/nerves/observation.js +20 -0
  145. package/dist/nerves/redact.js +79 -0
  146. package/dist/nerves/runtime.js +5 -1
  147. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  148. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  149. package/dist/outlook-ui/index.html +15 -0
  150. package/dist/repertoire/ado-client.js +15 -56
  151. package/dist/repertoire/ado-semantic.js +11 -10
  152. package/dist/repertoire/api-client.js +97 -0
  153. package/dist/repertoire/bitwarden-store.js +319 -0
  154. package/dist/repertoire/bundle-templates.js +72 -0
  155. package/dist/repertoire/bw-installer.js +79 -0
  156. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  157. package/dist/repertoire/coding/context-pack.js +330 -0
  158. package/dist/repertoire/coding/feedback.js +197 -30
  159. package/dist/repertoire/coding/manager.js +159 -11
  160. package/dist/repertoire/coding/spawner.js +55 -9
  161. package/dist/repertoire/coding/tools.js +170 -7
  162. package/dist/repertoire/commerce-errors.js +109 -0
  163. package/dist/repertoire/commerce-self-test.js +156 -0
  164. package/dist/repertoire/credential-access.js +527 -0
  165. package/dist/repertoire/duffel-client.js +185 -0
  166. package/dist/repertoire/github-client.js +14 -55
  167. package/dist/repertoire/graph-client.js +11 -52
  168. package/dist/repertoire/guardrails.js +375 -0
  169. package/dist/repertoire/mcp-client.js +255 -0
  170. package/dist/repertoire/mcp-manager.js +305 -0
  171. package/dist/repertoire/mcp-tools.js +63 -0
  172. package/dist/repertoire/shell-sessions.js +133 -0
  173. package/dist/repertoire/skills.js +14 -23
  174. package/dist/repertoire/stripe-client.js +131 -0
  175. package/dist/repertoire/tasks/board.js +43 -5
  176. package/dist/repertoire/tasks/fix.js +182 -0
  177. package/dist/repertoire/tasks/index.js +28 -10
  178. package/dist/repertoire/tasks/lifecycle.js +2 -2
  179. package/dist/repertoire/tasks/parser.js +3 -2
  180. package/dist/repertoire/tasks/scanner.js +194 -37
  181. package/dist/repertoire/tasks/transitions.js +11 -28
  182. package/dist/repertoire/tool-results.js +29 -0
  183. package/dist/repertoire/tools-attachments.js +316 -0
  184. package/dist/repertoire/tools-base.js +45 -771
  185. package/dist/repertoire/tools-bluebubbles.js +94 -0
  186. package/dist/repertoire/tools-bridge.js +141 -0
  187. package/dist/repertoire/tools-bundle.js +984 -0
  188. package/dist/repertoire/tools-config.js +185 -0
  189. package/dist/repertoire/tools-continuity.js +248 -0
  190. package/dist/repertoire/tools-credential.js +182 -0
  191. package/dist/repertoire/tools-files.js +342 -0
  192. package/dist/repertoire/tools-flight.js +224 -0
  193. package/dist/repertoire/tools-flow.js +105 -0
  194. package/dist/repertoire/tools-github.js +1 -7
  195. package/dist/repertoire/tools-memory.js +374 -0
  196. package/dist/repertoire/tools-session.js +739 -0
  197. package/dist/repertoire/tools-shell.js +120 -0
  198. package/dist/repertoire/tools-stripe.js +180 -0
  199. package/dist/repertoire/tools-surface.js +243 -0
  200. package/dist/repertoire/tools-teams.js +12 -62
  201. package/dist/repertoire/tools-travel.js +125 -0
  202. package/dist/repertoire/tools-user-profile.js +144 -0
  203. package/dist/repertoire/tools-vault.js +110 -0
  204. package/dist/repertoire/tools.js +148 -130
  205. package/dist/repertoire/travel-api-client.js +360 -0
  206. package/dist/repertoire/user-profile.js +118 -0
  207. package/dist/repertoire/vault-setup.js +241 -0
  208. package/dist/scripts/claude-code-hook.js +41 -0
  209. package/dist/scripts/claude-code-stop-hook.js +47 -0
  210. package/dist/senses/attention-queue.js +116 -0
  211. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  212. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  213. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +143 -9
  214. package/dist/senses/bluebubbles/entry.js +13 -0
  215. package/dist/senses/bluebubbles/inbound-log.js +113 -0
  216. package/dist/senses/bluebubbles/index.js +1427 -0
  217. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +122 -70
  218. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +43 -12
  219. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +46 -6
  220. package/dist/senses/bluebubbles/replay.js +129 -0
  221. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  222. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +12 -13
  223. package/dist/senses/cli/bracketed-paste.js +82 -0
  224. package/dist/senses/cli/image-paste.js +287 -0
  225. package/dist/senses/cli/image-ref-navigation.js +75 -0
  226. package/dist/senses/cli/ink-app.js +156 -0
  227. package/dist/senses/cli/inline-diff.js +64 -0
  228. package/dist/senses/cli/input-keys.js +174 -0
  229. package/dist/senses/cli/kill-ring.js +86 -0
  230. package/dist/senses/cli/message-list.js +51 -0
  231. package/dist/senses/cli/ouro-tui.js +595 -0
  232. package/dist/senses/cli/spinner-imperative.js +135 -0
  233. package/dist/senses/cli/spinner.js +101 -0
  234. package/dist/senses/cli/status-line.js +60 -0
  235. package/dist/senses/cli/streaming-markdown.js +526 -0
  236. package/dist/senses/cli/tool-display.js +83 -0
  237. package/dist/senses/cli/tool-render.js +85 -0
  238. package/dist/senses/cli/tui-store.js +240 -0
  239. package/dist/senses/cli/virtual-list.js +35 -0
  240. package/dist/senses/cli-entry.js +1 -1
  241. package/dist/senses/cli-layout.js +187 -0
  242. package/dist/senses/cli.js +588 -246
  243. package/dist/senses/commands.js +65 -1
  244. package/dist/senses/continuity.js +94 -0
  245. package/dist/senses/habit-turn-message.js +108 -0
  246. package/dist/senses/inner-dialog-worker.js +112 -19
  247. package/dist/senses/inner-dialog.js +633 -86
  248. package/dist/senses/pipeline.js +560 -0
  249. package/dist/senses/shared-turn.js +195 -0
  250. package/dist/senses/surface-tool.js +68 -0
  251. package/dist/senses/teams.js +664 -165
  252. package/dist/senses/trust-gate.js +112 -2
  253. package/package.json +14 -7
  254. package/skills/agent-commerce.md +106 -0
  255. package/skills/browser-navigation.md +110 -0
  256. package/skills/commerce-setup-guide.md +116 -0
  257. package/skills/commerce-setup.md +84 -0
  258. package/skills/configure-dev-tools.md +81 -0
  259. package/skills/travel-planning.md +138 -0
  260. package/dist/heart/daemon/subagent-installer.js +0 -134
  261. package/dist/senses/bluebubbles-entry.js +0 -11
  262. package/dist/senses/bluebubbles.js +0 -449
  263. package/dist/senses/debug-activity.js +0 -108
  264. package/subagents/README.md +0 -73
  265. package/subagents/work-doer.md +0 -235
  266. package/subagents/work-merger.md +0 -618
  267. package/subagents/work-planner.md +0 -382
  268. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  269. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  270. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  271. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  272. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  273. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  274. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  275. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  276. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  277. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  278. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  279. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  280. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  281. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  282. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  283. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  284. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,18 +34,243 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.parseOrphanPidsFromPs = parseOrphanPidsFromPs;
38
+ exports.filterPidfilePidsToActualOrphans = filterPidfilePidsToActualOrphans;
39
+ exports.killOrphanProcesses = killOrphanProcesses;
40
+ exports.writePidfile = writePidfile;
41
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
37
42
  const fs = __importStar(require("fs"));
38
43
  const net = __importStar(require("net"));
44
+ const os = __importStar(require("os"));
39
45
  const path = __importStar(require("path"));
40
46
  const identity_1 = require("../identity");
47
+ const agent_discovery_1 = require("./agent-discovery");
41
48
  const runtime_1 = require("../../nerves/runtime");
42
49
  const runtime_metadata_1 = require("./runtime-metadata");
43
- const update_hooks_1 = require("./update-hooks");
50
+ const runtime_mode_1 = require("./runtime-mode");
51
+ const update_hooks_1 = require("../versioning/update-hooks");
44
52
  const bundle_meta_1 = require("./hooks/bundle-meta");
53
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
45
54
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
46
- const update_checker_1 = require("./update-checker");
47
- const staged_restart_1 = require("./staged-restart");
55
+ const update_checker_1 = require("../versioning/update-checker");
56
+ const staged_restart_1 = require("../versioning/staged-restart");
57
+ const ouro_version_manager_1 = require("../versioning/ouro-version-manager");
48
58
  const child_process_1 = require("child_process");
59
+ const pending_1 = require("../../mind/pending");
60
+ const agent_service_1 = require("./agent-service");
61
+ const channel_1 = require("../../mind/friends/channel");
62
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
63
+ const outlook_http_1 = require("../outlook/outlook-http");
64
+ const outlook_types_1 = require("../outlook/outlook-types");
65
+ const outlook_read_1 = require("../outlook/outlook-read");
66
+ const outlook_view_1 = require("../outlook/outlook-view");
67
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
68
+ /**
69
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
70
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
71
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
72
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
73
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
74
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
75
+ * by a vitest test that called daemon.start()).
76
+ *
77
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
78
+ * to make the production pidfile sacred. Tests that need to verify these
79
+ * functions' behavior should use the extracted pure helpers
80
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
81
+ */
82
+ function isVitestProcess() {
83
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
84
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
85
+ return false;
86
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
87
+ }
88
+ /**
89
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
90
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
91
+ * that are safe to SIGTERM — true orphans, not children of live sibling
92
+ * daemons running from worktrees, test suites, or other users of the harness.
93
+ *
94
+ * Exported so unit tests can exercise the filter without shelling out.
95
+ */
96
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
97
+ const orphans = [];
98
+ for (const line of psOutput.split("\n")) {
99
+ // Explicitly exclude MCP server processes — they share a harness entry
100
+ // point but are not daemon children and must never be killed.
101
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
102
+ continue;
103
+ // Match only daemon-owned JS entry points.
104
+ if (!line.includes("agent-entry.js")
105
+ && !line.includes("daemon-entry.js")
106
+ && !line.includes("bluebubbles/entry.js")
107
+ && !line.includes("teams-entry.js"))
108
+ continue;
109
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
110
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
111
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
112
+ if (!match)
113
+ continue;
114
+ const pid = parseInt(match[1], 10);
115
+ const ppid = parseInt(match[2], 10);
116
+ if (pid === selfPid)
117
+ continue;
118
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
119
+ // PPID means the process belongs to another daemon instance (parallel
120
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
121
+ // Killing those will crash unrelated harnesses — we saw this in B6
122
+ // when a vitest worker's daemon killed slugger's production children.
123
+ if (ppid !== 1)
124
+ continue;
125
+ orphans.push(pid);
126
+ }
127
+ return orphans;
128
+ }
129
+ /**
130
+ * Given a list of PIDs from the pidfile, return only those that are actual
131
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
132
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
133
+ *
134
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
135
+ * Returns the empty list if ps fails — safer to skip cleanup than to
136
+ * wildcard-kill on a bad read.
137
+ *
138
+ * Exported for direct unit coverage.
139
+ */
140
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
141
+ if (candidatePids.length === 0)
142
+ return [];
143
+ const psOutput = psRunner(candidatePids);
144
+ if (psOutput === null)
145
+ return [];
146
+ const survivingOrphans = [];
147
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
148
+ // PIDs not found (already exited) are silently omitted — which is the
149
+ // correct behavior for us: we only want to kill live orphans.
150
+ for (const line of psOutput.split("\n")) {
151
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
152
+ if (!match)
153
+ continue;
154
+ const pid = parseInt(match[1], 10);
155
+ const ppid = parseInt(match[2], 10);
156
+ if (ppid !== 1)
157
+ continue;
158
+ if (!candidatePids.includes(pid))
159
+ continue;
160
+ survivingOrphans.push(pid);
161
+ }
162
+ return survivingOrphans;
163
+ }
164
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
165
+ function runPsCheck(pids) {
166
+ try {
167
+ const csv = pids.join(",");
168
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
169
+ }
170
+ catch {
171
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
172
+ // "no survivors" rather than an error.
173
+ return "";
174
+ }
175
+ }
176
+ /* v8 ignore stop */
177
+ /**
178
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
179
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
180
+ * deletes the file. The new daemon writes its own PIDs after spawning.
181
+ *
182
+ * Safety: pidfile contents are verified before being killed — each PID must
183
+ * be an actual orphan (PPID reparented to init/PID 1) via
184
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
185
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
186
+ * OS) could SIGTERM unrelated processes.
187
+ *
188
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
189
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
190
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
191
+ */
192
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
193
+ function killOrphanProcesses() {
194
+ if (isVitestProcess()) {
195
+ (0, runtime_1.emitNervesEvent)({
196
+ level: "warn",
197
+ component: "daemon",
198
+ event: "daemon.orphan_cleanup_test_blocked",
199
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
200
+ meta: { pidfilePath: PIDFILE_PATH },
201
+ });
202
+ return;
203
+ }
204
+ try {
205
+ let pidsToKill = [];
206
+ // Primary: read pidfile from previous daemon
207
+ try {
208
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
209
+ const candidates = raw.split("\n")
210
+ .map((s) => parseInt(s.trim(), 10))
211
+ .filter((n) => !isNaN(n) && n !== process.pid);
212
+ // Verify each candidate is an actual live orphan before killing. See
213
+ // docstring above for why this matters.
214
+ pidsToKill = filterPidfilePidsToActualOrphans(candidates);
215
+ fs.unlinkSync(PIDFILE_PATH);
216
+ }
217
+ catch {
218
+ // No pidfile — fall back to ps scan (scoped to orphans with PPID=1).
219
+ }
220
+ if (pidsToKill.length === 0) {
221
+ try {
222
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
223
+ pidsToKill = parseOrphanPidsFromPs(result, process.pid);
224
+ }
225
+ catch { /* ps failed — best effort */ }
226
+ }
227
+ if (pidsToKill.length > 0) {
228
+ for (const pid of pidsToKill) {
229
+ try {
230
+ process.kill(pid, "SIGTERM");
231
+ }
232
+ catch { /* already exited */ }
233
+ }
234
+ (0, runtime_1.emitNervesEvent)({
235
+ component: "daemon",
236
+ event: "daemon.orphan_cleanup",
237
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
238
+ meta: { pids: pidsToKill },
239
+ });
240
+ }
241
+ }
242
+ catch (error) {
243
+ (0, runtime_1.emitNervesEvent)({
244
+ level: "warn",
245
+ component: "daemon",
246
+ event: "daemon.orphan_cleanup_error",
247
+ message: "failed to clean up orphaned ouro processes",
248
+ meta: { error: error instanceof Error ? error.message : String(error) },
249
+ });
250
+ }
251
+ }
252
+ /**
253
+ * Write all managed PIDs (daemon + children) to the pidfile.
254
+ * Called after all agents and senses are spawned.
255
+ */
256
+ function writePidfile(extraPids = []) {
257
+ if (isVitestProcess()) {
258
+ (0, runtime_1.emitNervesEvent)({
259
+ level: "warn",
260
+ component: "daemon",
261
+ event: "daemon.write_pidfile_test_blocked",
262
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
263
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
264
+ });
265
+ return;
266
+ }
267
+ try {
268
+ const pids = [process.pid, ...extraPids].filter(Boolean);
269
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
270
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
271
+ }
272
+ catch { /* best effort */ }
273
+ }
49
274
  function buildWorkerRows(snapshots) {
50
275
  return snapshots.map((snapshot) => ({
51
276
  agent: snapshot.name,
@@ -54,6 +279,8 @@ function buildWorkerRows(snapshots) {
54
279
  pid: snapshot.pid,
55
280
  restartCount: snapshot.restartCount,
56
281
  startedAt: snapshot.startedAt,
282
+ lastExitCode: snapshot.lastExitCode ?? null,
283
+ lastSignal: snapshot.lastSignal ?? null,
57
284
  }));
58
285
  }
59
286
  function formatStatusSummary(payload) {
@@ -86,6 +313,35 @@ function parseIncomingCommand(raw) {
86
313
  }
87
314
  return parsed;
88
315
  }
316
+ /**
317
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
318
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
319
+ * restarts the daemon process (fresh module cache).
320
+ */
321
+ async function handleAgentSenseTurn(command) {
322
+ try {
323
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
324
+ setAgentName(command.agent);
325
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
326
+ const result = await runSenseTurn({
327
+ agentName: command.agent,
328
+ channel: command.channel,
329
+ sessionKey: command.sessionKey,
330
+ friendId: command.friendId,
331
+ userMessage: command.message,
332
+ });
333
+ return {
334
+ ok: true,
335
+ message: result.response,
336
+ data: { ponderDeferred: result.ponderDeferred },
337
+ };
338
+ }
339
+ catch (error) {
340
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
341
+ const errorMessage = error instanceof Error ? error.message : String(error);
342
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
343
+ }
344
+ }
89
345
  class OuroDaemon {
90
346
  socketPath;
91
347
  processManager;
@@ -94,7 +350,10 @@ class OuroDaemon {
94
350
  router;
95
351
  senseManager;
96
352
  bundlesRoot;
353
+ mode;
97
354
  server = null;
355
+ outlookServer = null;
356
+ outlookServerFactory;
98
357
  constructor(options) {
99
358
  this.socketPath = options.socketPath;
100
359
  this.processManager = options.processManager;
@@ -103,6 +362,67 @@ class OuroDaemon {
103
362
  this.router = options.router;
104
363
  this.senseManager = options.senseManager ?? null;
105
364
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
365
+ this.mode = options.mode ?? "production";
366
+ this.outlookServerFactory = options.outlookServerFactory ?? this.createDefaultOutlookServer.bind(this);
367
+ }
368
+ /* v8 ignore start -- default outlook server wiring: production-only path, tests inject outlookServerFactory stub instead. startOutlookHttpServer itself has full coverage in outlook-http.test.ts @preserve */
369
+ createDefaultOutlookServer() {
370
+ return (0, outlook_http_1.startOutlookHttpServer)({
371
+ host: "127.0.0.1",
372
+ port: outlook_types_1.OUTLOOK_DEFAULT_PORT,
373
+ bundlesRoot: this.bundlesRoot,
374
+ readMachineState: () => (0, outlook_read_1.readOutlookMachineState)({ bundlesRoot: this.bundlesRoot }),
375
+ readMachineView: ({ machine }) => {
376
+ const overview = this.buildStatusPayload().overview;
377
+ return (0, outlook_view_1.buildOutlookMachineView)({
378
+ machine,
379
+ daemon: {
380
+ status: overview.daemon,
381
+ health: overview.health,
382
+ mode: overview.mode,
383
+ socketPath: overview.socketPath,
384
+ outlookUrl: overview.outlookUrl,
385
+ entryPath: overview.entryPath,
386
+ workerCount: overview.workerCount,
387
+ senseCount: overview.senseCount,
388
+ },
389
+ });
390
+ },
391
+ readAgentState: (agentName) => (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
392
+ readAgentView: (agentName) => {
393
+ const agent = (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
394
+ return (0, outlook_view_1.buildOutlookAgentView)({
395
+ agent,
396
+ viewer: { kind: "human" },
397
+ });
398
+ },
399
+ });
400
+ }
401
+ /* v8 ignore stop */
402
+ buildStatusPayload() {
403
+ const snapshots = this.processManager.listAgentSnapshots();
404
+ const workers = buildWorkerRows(snapshots);
405
+ const senses = this.senseManager?.listSenseRows() ?? [];
406
+ const repoRoot = (0, identity_1.getRepoRoot)();
407
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
408
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
409
+ return {
410
+ overview: {
411
+ daemon: "running",
412
+ health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
413
+ socketPath: this.socketPath,
414
+ outlookUrl: this.outlookServer?.origin ?? "http://127.0.0.1:0",
415
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
416
+ workerCount: workers.length,
417
+ senseCount: senses.length,
418
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
419
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
420
+ },
421
+ workers,
422
+ senses,
423
+ sync,
424
+ agents,
425
+ };
106
426
  }
107
427
  async start() {
108
428
  if (this.server)
@@ -113,61 +433,181 @@ class OuroDaemon {
113
433
  message: "starting daemon server",
114
434
  meta: { socketPath: this.socketPath },
115
435
  });
436
+ try {
437
+ await this.startInner();
438
+ }
439
+ catch (err) {
440
+ // Emit a paired terminating event (`_error`) so the nerves audit's
441
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
442
+ // and `stop()` (which emits `server_end`) is never called.
443
+ (0, runtime_1.emitNervesEvent)({
444
+ level: "error",
445
+ component: "daemon",
446
+ event: "daemon.server_error",
447
+ message: "daemon start failed",
448
+ meta: {
449
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
450
+ },
451
+ });
452
+ throw err;
453
+ }
454
+ }
455
+ async startInner() {
116
456
  // Register update hooks and apply pending updates before starting agents
117
457
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
458
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
118
459
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
119
460
  await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
120
461
  // Start periodic update checker (polls npm registry every 30 minutes)
462
+ // Skip in dev mode — dev builds should not auto-update from npm
121
463
  const bundlesRoot = this.bundlesRoot;
122
- const daemon = this;
123
- (0, update_checker_1.startUpdateChecker)({
124
- currentVersion,
125
- deps: {
126
- distTag: "alpha",
127
- fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
128
- const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
129
- return res.json();
130
- },
131
- },
132
- onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
133
- if (!result.latestVersion)
134
- return;
135
- await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
136
- execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
137
- spawnSync: child_process_1.spawnSync,
138
- resolveNewCodePath: (_version) => {
139
- try {
140
- const resolved = (0, child_process_1.execSync)(`node -e "console.log(require.resolve('@ouro.bot/cli/package.json'))"`, { encoding: "utf-8" }).trim();
141
- return resolved ? path.dirname(resolved) : null;
142
- }
143
- catch {
144
- return null;
145
- }
464
+ const daemonSocketPath = this.socketPath;
465
+ if (this.mode === "dev") {
466
+ (0, runtime_1.emitNervesEvent)({
467
+ component: "daemon",
468
+ event: "daemon.update_checker_skip",
469
+ message: "skipping update checker in dev mode",
470
+ meta: { reason: "dev mode" },
471
+ });
472
+ }
473
+ else {
474
+ const daemon = this;
475
+ (0, update_checker_1.startUpdateChecker)({
476
+ currentVersion,
477
+ deps: {
478
+ distTag: "alpha",
479
+ fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
480
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
481
+ return res.json();
146
482
  },
147
- gracefulShutdown: () => daemon.stop(),
148
- nodePath: process.execPath,
149
- bundlesRoot,
150
- });
151
- },
152
- /* v8 ignore stop */
153
- });
483
+ },
484
+ onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
485
+ if (!result.latestVersion)
486
+ return;
487
+ // Install via the version manager (NOT `npm install -g`). The
488
+ // global install path doesn't end up on the daemon process's
489
+ // NODE_PATH, so the previous `require.resolve('@ouro.bot/cli')`
490
+ // -based path lookup always returned null and the staged restart
491
+ // never actually completed. Verified live on 2026-04-08:
492
+ // alpha.268 daemon detected alpha.270 was available, ran the
493
+ // staged restart, and bailed at `staged_restart_path_failed` —
494
+ // meaning the daemon could never auto-update itself and required
495
+ // manual `ouro up` to pick up new versions.
496
+ //
497
+ // Switch to the version-managed layout the CLI itself uses:
498
+ // installVersion(version) puts files at
499
+ // ~/.ouro-cli/versions/{version}/node_modules/@ouro.bot/cli
500
+ // which is a known path we can compute deterministically.
501
+ // Then activateVersion(version) flips the CurrentVersion symlink
502
+ // so the next `ouro up` from the user sees the same version
503
+ // the daemon is running.
504
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
505
+ await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
506
+ execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
507
+ spawnSync: child_process_1.spawnSync,
508
+ installNewVersion: (version) => {
509
+ (0, ouro_version_manager_1.installVersion)(version, {});
510
+ (0, ouro_version_manager_1.activateVersion)(version, {});
511
+ },
512
+ resolveNewCodePath: (version) => {
513
+ const versionPath = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli");
514
+ return fs.existsSync(versionPath) ? versionPath : null;
515
+ },
516
+ gracefulShutdown: () => daemon.stop(),
517
+ spawnNewDaemon: (entryPath, sock) => {
518
+ const outFd = fs.openSync(os.devNull, "w");
519
+ const errFd = fs.openSync(os.devNull, "w");
520
+ const child = (0, child_process_1.spawn)(process.execPath, [entryPath, "--socket", sock], {
521
+ detached: true,
522
+ stdio: ["ignore", outFd, errFd],
523
+ });
524
+ child.unref();
525
+ return { pid: child.pid ?? null };
526
+ },
527
+ nodePath: process.execPath,
528
+ bundlesRoot,
529
+ socketPath: daemonSocketPath,
530
+ });
531
+ },
532
+ /* v8 ignore stop */
533
+ });
534
+ }
535
+ // MCP connections are lazily initialized per-agent during senseTurn
536
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
537
+ /* v8 ignore start -- orphan cleanup + pidfile: calls process management functions @preserve */
538
+ killOrphanProcesses();
539
+ /* v8 ignore stop */
154
540
  await this.processManager.startAutoStartAgents();
155
541
  await this.senseManager?.startAutoStartSenses();
542
+ // Write all managed PIDs to disk so the next daemon can clean up
543
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
544
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
545
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
546
+ writePidfile([...agentPids, ...sensePids]);
547
+ /* v8 ignore stop */
156
548
  this.scheduler.start?.();
157
549
  await this.scheduler.reconcile?.();
158
550
  await this.drainPendingBundleMessages();
551
+ await this.drainPendingSenseMessages();
552
+ // startInner is only reachable when this.server is null (guarded in
553
+ // start()), and stop() nulls out this.outlookServer alongside this.server,
554
+ // so outlookServer is guaranteed unset here — no need for a guard.
555
+ try {
556
+ this.outlookServer = await this.outlookServerFactory();
557
+ }
558
+ catch (error) {
559
+ (0, runtime_1.emitNervesEvent)({
560
+ level: "warn",
561
+ component: "daemon",
562
+ event: "daemon.outlook_start_failed",
563
+ message: `Outlook server failed to start: ${String(error)}`,
564
+ meta: { port: outlook_types_1.OUTLOOK_DEFAULT_PORT },
565
+ });
566
+ }
159
567
  if (fs.existsSync(this.socketPath)) {
160
568
  fs.unlinkSync(this.socketPath);
161
569
  }
162
- this.server = net.createServer((connection) => {
570
+ // allowHalfOpen: true lets the server keep its writable side open after
571
+ // the client sends FIN. Without this, when a client calls `client.end()`
572
+ // after writing a command, node closes the server's writable side
573
+ // automatically — so a long-running response (like an agent.senseTurn
574
+ // LLM turn that takes 5+ seconds) never reaches the client. The
575
+ // socket-client fix in #303/#334 also removed client.end() on the
576
+ // sending side, but this option is defense in depth: even if a future
577
+ // caller half-closes, the server still writes its response correctly.
578
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
163
579
  let raw = "";
164
580
  let responded = false;
581
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
582
+ connection.on("error", (err) => {
583
+ (0, runtime_1.emitNervesEvent)({
584
+ level: "warn",
585
+ component: "daemon",
586
+ event: "daemon.connection_error",
587
+ message: "socket connection error",
588
+ meta: { error: err.message, code: err.code ?? null },
589
+ });
590
+ });
591
+ /* v8 ignore stop */
165
592
  const flushResponse = async () => {
166
593
  if (responded)
167
594
  return;
168
595
  responded = true;
169
596
  const response = await this.handleRawPayload(raw);
170
- connection.end(response);
597
+ try {
598
+ connection.end(response);
599
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
600
+ }
601
+ catch (err) {
602
+ (0, runtime_1.emitNervesEvent)({
603
+ level: "warn",
604
+ component: "daemon",
605
+ event: "daemon.connection_end_error",
606
+ message: "failed to send response to client (EPIPE)",
607
+ meta: { error: err instanceof Error ? err.message : String(err) },
608
+ });
609
+ }
610
+ /* v8 ignore stop */
171
611
  };
172
612
  connection.on("data", (chunk) => {
173
613
  raw += chunk.toString("utf-8");
@@ -180,7 +620,22 @@ class OuroDaemon {
180
620
  const server = this.server;
181
621
  await new Promise((resolve, reject) => {
182
622
  server.once("error", reject);
183
- server.listen(this.socketPath, () => resolve());
623
+ server.listen(this.socketPath, () => {
624
+ // Replace the one-time error listener with a persistent one after successful listen
625
+ server.removeAllListeners("error");
626
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
627
+ server.on("error", (err) => {
628
+ (0, runtime_1.emitNervesEvent)({
629
+ level: "error",
630
+ component: "daemon",
631
+ event: "daemon.server_error",
632
+ message: "daemon server error after listen",
633
+ meta: { error: err.message, code: err.code ?? null },
634
+ });
635
+ });
636
+ /* v8 ignore stop */
637
+ resolve();
638
+ });
184
639
  });
185
640
  }
186
641
  async drainPendingBundleMessages() {
@@ -231,23 +686,145 @@ class OuroDaemon {
231
686
  fs.writeFileSync(pendingPath, next, "utf-8");
232
687
  }
233
688
  }
689
+ /** Drains per-sense pending dirs for always-on senses across all agents. */
690
+ static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
691
+ async drainPendingSenseMessages() {
692
+ if (!fs.existsSync(this.bundlesRoot))
693
+ return;
694
+ let bundleDirs;
695
+ try {
696
+ bundleDirs = fs.readdirSync(this.bundlesRoot, { withFileTypes: true });
697
+ }
698
+ catch {
699
+ return;
700
+ }
701
+ for (const bundleDir of bundleDirs) {
702
+ if (!bundleDir.isDirectory() || !bundleDir.name.endsWith(".ouro"))
703
+ continue;
704
+ const agentName = bundleDir.name.replace(/\.ouro$/, "");
705
+ const pendingRoot = path.join(this.bundlesRoot, bundleDir.name, "state", "pending");
706
+ if (!fs.existsSync(pendingRoot))
707
+ continue;
708
+ let friendDirs;
709
+ try {
710
+ friendDirs = fs.readdirSync(pendingRoot, { withFileTypes: true });
711
+ }
712
+ catch {
713
+ continue;
714
+ }
715
+ for (const friendDir of friendDirs) {
716
+ if (!friendDir.isDirectory())
717
+ continue;
718
+ const friendPath = path.join(pendingRoot, friendDir.name);
719
+ let channelDirs;
720
+ try {
721
+ channelDirs = fs.readdirSync(friendPath, { withFileTypes: true });
722
+ }
723
+ catch {
724
+ continue;
725
+ }
726
+ for (const channelDir of channelDirs) {
727
+ if (!channelDir.isDirectory())
728
+ continue;
729
+ if (!OuroDaemon.ALWAYS_ON_SENSES.has(channelDir.name))
730
+ continue;
731
+ const channelPath = path.join(friendPath, channelDir.name);
732
+ let keyDirs;
733
+ try {
734
+ keyDirs = fs.readdirSync(channelPath, { withFileTypes: true });
735
+ }
736
+ catch {
737
+ continue;
738
+ }
739
+ for (const keyDir of keyDirs) {
740
+ if (!keyDir.isDirectory())
741
+ continue;
742
+ const leafDir = path.join(channelPath, keyDir.name);
743
+ const messages = (0, pending_1.drainPending)(leafDir);
744
+ for (const msg of messages) {
745
+ try {
746
+ await this.router.send({
747
+ from: msg.from,
748
+ to: agentName,
749
+ content: msg.content,
750
+ priority: "normal",
751
+ });
752
+ }
753
+ catch {
754
+ // Best-effort delivery — log and continue
755
+ }
756
+ }
757
+ if (messages.length > 0) {
758
+ (0, runtime_1.emitNervesEvent)({
759
+ component: "daemon",
760
+ event: "daemon.startup_sense_drain",
761
+ message: "drained pending sense messages on startup",
762
+ meta: {
763
+ agent: agentName,
764
+ channel: channelDir.name,
765
+ friendId: friendDir.name,
766
+ key: keyDir.name,
767
+ count: messages.length,
768
+ },
769
+ });
770
+ }
771
+ }
772
+ }
773
+ }
774
+ }
775
+ }
234
776
  async stop() {
777
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
778
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
779
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
235
780
  (0, runtime_1.emitNervesEvent)({
236
781
  component: "daemon",
237
- event: "daemon.server_stop",
782
+ event: "daemon.server_end",
238
783
  message: "stopping daemon server",
239
784
  meta: { socketPath: this.socketPath },
240
785
  });
241
786
  (0, update_checker_1.stopUpdateChecker)();
787
+ (0, mcp_manager_1.shutdownSharedMcpManager)();
242
788
  this.scheduler.stop?.();
243
789
  await this.processManager.stopAll();
244
790
  await this.senseManager?.stopAll();
245
791
  if (this.server) {
246
- await new Promise((resolve) => {
247
- this.server?.close(() => resolve());
248
- });
792
+ // DO NOT `await` server.close() here. server.close() resolves only
793
+ // after every open connection has closed. When stop() is invoked
794
+ // from the daemon.stop command handler, the calling client's
795
+ // connection is STILL open — its flushResponse() is currently
796
+ // awaiting THIS function. Awaiting close() creates a deadlock:
797
+ //
798
+ // client → flushResponse → handleRawPayload → daemon.stop case
799
+ // → stop() → await server.close() (waits for client's connection)
800
+ // → client's connection waits for flushResponse to call
801
+ // connection.end() → DEADLOCK
802
+ //
803
+ // Both processes sit in kevent forever. Verified live on
804
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
805
+ // line for 5+ minutes after a client sent daemon.stop, while the
806
+ // client (alpha.270 ouro up) hung waiting for the response.
807
+ //
808
+ // This regressed when #303/#334/#339 stopped half-closing the
809
+ // client socket and switched the server to allowHalfOpen: true.
810
+ // Previously, the client called .end() after writing its command,
811
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
812
+ // the server's writable side — incidentally unblocking
813
+ // server.close() before the response was sent. The half-close
814
+ // breakage masked this deadlock; the fix exposed it.
815
+ //
816
+ // Solution: fire close() and let it complete asynchronously. Once
817
+ // stop() returns, the daemon.stop case returns its response,
818
+ // flushResponse() calls connection.end(response), the connection
819
+ // closes, and server.close()'s pending callback fires. The event
820
+ // loop drains and the daemon exits cleanly.
821
+ this.server.close();
249
822
  this.server = null;
250
823
  }
824
+ if (this.outlookServer) {
825
+ await this.outlookServer.stop();
826
+ this.outlookServer = null;
827
+ }
251
828
  if (fs.existsSync(this.socketPath)) {
252
829
  fs.unlinkSync(this.socketPath);
253
830
  }
@@ -272,6 +849,27 @@ class OuroDaemon {
272
849
  message: "handling daemon command",
273
850
  meta: { kind: command.kind },
274
851
  });
852
+ try {
853
+ return await this.handleCommandInner(command);
854
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
855
+ }
856
+ catch (error) {
857
+ (0, runtime_1.emitNervesEvent)({
858
+ level: "error",
859
+ component: "daemon",
860
+ event: "daemon.command_error",
861
+ message: "unexpected error handling daemon command",
862
+ meta: {
863
+ kind: command.kind,
864
+ error: error instanceof Error ? error.message : String(error),
865
+ stack: error instanceof Error ? error.stack ?? null : null,
866
+ },
867
+ });
868
+ throw error;
869
+ }
870
+ /* v8 ignore stop */
871
+ }
872
+ async handleCommandInner(command) {
275
873
  switch (command.kind) {
276
874
  case "daemon.start":
277
875
  await this.start();
@@ -280,21 +878,7 @@ class OuroDaemon {
280
878
  await this.stop();
281
879
  return { ok: true, message: "daemon stopped" };
282
880
  case "daemon.status": {
283
- const snapshots = this.processManager.listAgentSnapshots();
284
- const workers = buildWorkerRows(snapshots);
285
- const senses = this.senseManager?.listSenseRows() ?? [];
286
- const data = {
287
- overview: {
288
- daemon: "running",
289
- health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
290
- socketPath: this.socketPath,
291
- ...(0, runtime_metadata_1.getRuntimeMetadata)(),
292
- workerCount: workers.length,
293
- senseCount: senses.length,
294
- },
295
- workers,
296
- senses,
297
- };
881
+ const data = this.buildStatusPayload();
298
882
  return {
299
883
  ok: true,
300
884
  summary: formatStatusSummary(data),
@@ -311,7 +895,7 @@ class OuroDaemon {
311
895
  ok: true,
312
896
  summary: "logs: use `ouro logs` to tail daemon and agent output",
313
897
  message: "log streaming available via ouro logs",
314
- data: { logDir: "~/.agentstate/daemon/logs" },
898
+ data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
315
899
  };
316
900
  case "agent.start":
317
901
  await this.processManager.startAgent(command.agent);
@@ -322,6 +906,35 @@ class OuroDaemon {
322
906
  case "agent.restart":
323
907
  await this.processManager.restartAgent?.(command.agent);
324
908
  return { ok: true, message: `restarted ${command.agent}` };
909
+ case "agent.ask":
910
+ return (0, agent_service_1.handleAgentAsk)(command);
911
+ case "agent.status":
912
+ return (0, agent_service_1.handleAgentStatus)(command);
913
+ case "agent.catchup":
914
+ return (0, agent_service_1.handleAgentCatchup)(command);
915
+ case "agent.delegate":
916
+ return (0, agent_service_1.handleAgentDelegate)(command);
917
+ case "agent.getContext":
918
+ return (0, agent_service_1.handleAgentGetContext)(command);
919
+ case "agent.searchMemory":
920
+ return (0, agent_service_1.handleAgentSearchMemory)(command);
921
+ case "agent.getTask":
922
+ return (0, agent_service_1.handleAgentGetTask)(command);
923
+ case "agent.checkScope":
924
+ return (0, agent_service_1.handleAgentCheckScope)(command);
925
+ case "agent.requestDecision":
926
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
927
+ case "agent.checkGuidance":
928
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
929
+ case "agent.reportProgress":
930
+ return (0, agent_service_1.handleAgentReportProgress)(command);
931
+ case "agent.reportBlocker":
932
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
933
+ case "agent.reportComplete":
934
+ return (0, agent_service_1.handleAgentReportComplete)(command);
935
+ case "agent.senseTurn":
936
+ return handleAgentSenseTurn(command);
937
+ /* v8 ignore stop */
325
938
  case "cron.list": {
326
939
  const jobs = this.scheduler.listJobs();
327
940
  const summary = jobs.length === 0
@@ -353,6 +966,13 @@ class OuroDaemon {
353
966
  data: messages,
354
967
  };
355
968
  }
969
+ case "inner.wake":
970
+ await this.processManager.startAgent(command.agent);
971
+ this.processManager.sendToAgent?.(command.agent, { type: "message" });
972
+ return {
973
+ ok: true,
974
+ message: `woke inner dialog for ${command.agent}`,
975
+ };
356
976
  case "chat.connect":
357
977
  await this.processManager.startAgent(command.agent);
358
978
  return {
@@ -375,6 +995,35 @@ class OuroDaemon {
375
995
  data: receipt,
376
996
  };
377
997
  }
998
+ case "habit.poke": {
999
+ this.processManager.sendToAgent?.(command.agent, { type: "habit", habitName: command.habitName });
1000
+ return {
1001
+ ok: true,
1002
+ message: `poked habit ${command.habitName} for ${command.agent}`,
1003
+ };
1004
+ }
1005
+ case "mcp.list": {
1006
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
1007
+ if (!mcpManager) {
1008
+ return { ok: true, data: [], message: "no MCP servers configured" };
1009
+ }
1010
+ return { ok: true, data: mcpManager.listAllTools() };
1011
+ }
1012
+ case "mcp.call": {
1013
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
1014
+ if (!mcpCallManager) {
1015
+ return { ok: false, error: "no MCP servers configured" };
1016
+ }
1017
+ try {
1018
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
1019
+ const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
1020
+ return { ok: true, data: result };
1021
+ }
1022
+ catch (error) {
1023
+ /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
1024
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
1025
+ }
1026
+ }
378
1027
  case "hatch.start":
379
1028
  return {
380
1029
  ok: true,