@ouro.bot/cli 0.1.0-alpha.19 → 0.1.0-alpha.190

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 (202) hide show
  1. package/README.md +187 -191
  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 +1280 -0
  5. package/dist/heart/active-work.js +832 -0
  6. package/dist/heart/bridges/manager.js +358 -0
  7. package/dist/heart/bridges/state-machine.js +135 -0
  8. package/dist/heart/bridges/store.js +123 -0
  9. package/dist/heart/cares.js +174 -0
  10. package/dist/heart/commitments.js +111 -0
  11. package/dist/heart/config.js +40 -30
  12. package/dist/heart/core.js +620 -124
  13. package/dist/heart/cross-chat-delivery.js +146 -0
  14. package/dist/heart/daemon/agent-discovery.js +81 -0
  15. package/dist/heart/daemon/agent-service.js +360 -0
  16. package/dist/heart/daemon/auth-flow.js +477 -0
  17. package/dist/heart/daemon/cadence.js +70 -0
  18. package/dist/heart/daemon/daemon-cli.js +2470 -210
  19. package/dist/heart/daemon/daemon-entry.js +157 -4
  20. package/dist/heart/daemon/daemon-health.js +136 -0
  21. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  22. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  23. package/dist/heart/daemon/daemon.js +449 -17
  24. package/dist/heart/daemon/habit-migration.js +181 -0
  25. package/dist/heart/daemon/habit-parser.js +119 -0
  26. package/dist/heart/daemon/habit-scheduler.js +369 -0
  27. package/dist/heart/daemon/hatch-flow.js +31 -112
  28. package/dist/heart/daemon/hatch-specialist.js +3 -3
  29. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  30. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  31. package/dist/heart/daemon/inner-status.js +89 -0
  32. package/dist/heart/daemon/launchd.js +165 -0
  33. package/dist/heart/daemon/log-tailer.js +4 -3
  34. package/dist/heart/daemon/mcp-server.js +591 -0
  35. package/dist/heart/daemon/message-router.js +17 -8
  36. package/dist/heart/daemon/os-cron-deps.js +134 -0
  37. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  38. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  39. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  40. package/dist/heart/daemon/outlook-http.js +399 -0
  41. package/dist/heart/daemon/outlook-read.js +1331 -0
  42. package/dist/heart/daemon/outlook-render.js +1032 -0
  43. package/dist/heart/daemon/outlook-types.js +7 -0
  44. package/dist/heart/daemon/outlook-view.js +194 -0
  45. package/dist/heart/daemon/process-manager.js +75 -0
  46. package/dist/heart/daemon/run-hooks.js +39 -0
  47. package/dist/heart/daemon/runtime-logging.js +58 -15
  48. package/dist/heart/daemon/runtime-metadata.js +219 -0
  49. package/dist/heart/daemon/runtime-mode.js +67 -0
  50. package/dist/heart/daemon/safe-mode.js +161 -0
  51. package/dist/heart/daemon/sense-manager.js +50 -2
  52. package/dist/heart/daemon/session-id-resolver.js +131 -0
  53. package/dist/heart/daemon/skill-management-installer.js +94 -0
  54. package/dist/heart/daemon/socket-client.js +202 -0
  55. package/dist/heart/daemon/specialist-prompt.js +10 -7
  56. package/dist/heart/daemon/specialist-tools.js +49 -3
  57. package/dist/heart/daemon/staged-restart.js +114 -0
  58. package/dist/heart/daemon/task-scheduler.js +3 -25
  59. package/dist/heart/daemon/thoughts.js +507 -0
  60. package/dist/heart/daemon/update-checker.js +111 -0
  61. package/dist/heart/daemon/update-hooks.js +138 -0
  62. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  63. package/dist/heart/delegation.js +62 -0
  64. package/dist/heart/identity.js +136 -55
  65. package/dist/heart/intentions.js +168 -0
  66. package/dist/heart/kicks.js +2 -20
  67. package/dist/heart/migrate-config.js +127 -0
  68. package/dist/heart/model-capabilities.js +48 -0
  69. package/dist/heart/obligations.js +220 -0
  70. package/dist/heart/presence.js +185 -0
  71. package/dist/heart/progress-story.js +42 -0
  72. package/dist/heart/provider-failover.js +88 -0
  73. package/dist/heart/provider-ping.js +172 -0
  74. package/dist/heart/providers/anthropic-token.js +163 -0
  75. package/dist/heart/providers/anthropic.js +187 -41
  76. package/dist/heart/providers/azure.js +116 -10
  77. package/dist/heart/providers/github-copilot.js +157 -0
  78. package/dist/heart/providers/minimax.js +33 -3
  79. package/dist/heart/providers/openai-codex.js +51 -16
  80. package/dist/heart/session-activity.js +172 -0
  81. package/dist/heart/session-recall.js +216 -0
  82. package/dist/heart/streaming.js +36 -27
  83. package/dist/heart/target-resolution.js +127 -0
  84. package/dist/heart/tempo.js +93 -0
  85. package/dist/heart/temporal-view.js +41 -0
  86. package/dist/heart/tool-activity-callbacks.js +36 -0
  87. package/dist/heart/tool-description.js +135 -0
  88. package/dist/heart/tool-loop.js +200 -0
  89. package/dist/heart/turn-coordinator.js +28 -0
  90. package/dist/heart/wake-packet.js +226 -0
  91. package/dist/mind/associative-recall.js +122 -32
  92. package/dist/mind/bundle-manifest.js +14 -0
  93. package/dist/mind/context.js +125 -14
  94. package/dist/mind/{memory.js → diary.js} +70 -56
  95. package/dist/mind/episodes.js +116 -0
  96. package/dist/mind/file-state.js +179 -0
  97. package/dist/mind/first-impressions.js +16 -2
  98. package/dist/mind/friends/channel.js +56 -0
  99. package/dist/mind/friends/group-context.js +144 -0
  100. package/dist/mind/friends/store-file.js +36 -0
  101. package/dist/mind/friends/trust-explanation.js +74 -0
  102. package/dist/mind/friends/types.js +8 -0
  103. package/dist/mind/journal-index.js +161 -0
  104. package/dist/mind/obligation-steering.js +221 -0
  105. package/dist/mind/obligations.js +134 -0
  106. package/dist/mind/pending.js +76 -9
  107. package/dist/mind/phrases.js +1 -0
  108. package/dist/mind/prompt.js +779 -102
  109. package/dist/mind/scrutiny.js +173 -0
  110. package/dist/mind/token-estimate.js +8 -12
  111. package/dist/nerves/coverage/audit.js +1 -1
  112. package/dist/nerves/coverage/run-artifacts.js +1 -1
  113. package/dist/nerves/event-buffer.js +111 -0
  114. package/dist/nerves/index.js +63 -3
  115. package/dist/nerves/observation.js +20 -0
  116. package/dist/nerves/runtime.js +5 -1
  117. package/dist/outlook-ui/assets/index-DN6vVYPm.css +1 -0
  118. package/dist/outlook-ui/assets/index-M1l1tDTX.js +61 -0
  119. package/dist/outlook-ui/index.html +15 -0
  120. package/dist/repertoire/ado-semantic.js +11 -5
  121. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  122. package/dist/repertoire/coding/context-pack.js +330 -0
  123. package/dist/repertoire/coding/feedback.js +197 -30
  124. package/dist/repertoire/coding/manager.js +149 -2
  125. package/dist/repertoire/coding/spawner.js +55 -9
  126. package/dist/repertoire/coding/tools.js +170 -7
  127. package/dist/repertoire/guardrails.js +291 -0
  128. package/dist/repertoire/mcp-client.js +254 -0
  129. package/dist/repertoire/mcp-manager.js +198 -0
  130. package/dist/repertoire/shell-sessions.js +133 -0
  131. package/dist/repertoire/skills.js +14 -23
  132. package/dist/repertoire/tasks/board.js +43 -5
  133. package/dist/repertoire/tasks/fix.js +182 -0
  134. package/dist/repertoire/tasks/index.js +28 -10
  135. package/dist/repertoire/tasks/lifecycle.js +2 -2
  136. package/dist/repertoire/tasks/parser.js +3 -2
  137. package/dist/repertoire/tasks/scanner.js +194 -37
  138. package/dist/repertoire/tasks/transitions.js +11 -28
  139. package/dist/repertoire/tools-base.js +1345 -320
  140. package/dist/repertoire/tools-bluebubbles.js +94 -0
  141. package/dist/repertoire/tools-github.js +1 -6
  142. package/dist/repertoire/tools-teams.js +12 -59
  143. package/dist/repertoire/tools.js +318 -124
  144. package/dist/scripts/claude-code-hook.js +41 -0
  145. package/dist/scripts/claude-code-stop-hook.js +47 -0
  146. package/dist/senses/attention-queue.js +97 -0
  147. package/dist/senses/bluebubbles-client.js +102 -3
  148. package/dist/senses/bluebubbles-entry.js +2 -0
  149. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  150. package/dist/senses/bluebubbles-media.js +118 -23
  151. package/dist/senses/bluebubbles-model.js +12 -4
  152. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  153. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  154. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  155. package/dist/senses/bluebubbles.js +1008 -102
  156. package/dist/senses/cli/adapter.js +274 -0
  157. package/dist/senses/cli/ink-app.js +156 -0
  158. package/dist/senses/cli/inline-diff.js +64 -0
  159. package/dist/senses/cli/message-list.js +51 -0
  160. package/dist/senses/cli/ouro-tui.js +349 -0
  161. package/dist/senses/cli/spinner-imperative.js +135 -0
  162. package/dist/senses/cli/spinner.js +101 -0
  163. package/dist/senses/cli/status-line.js +60 -0
  164. package/dist/senses/cli/streaming-markdown.js +526 -0
  165. package/dist/senses/cli/tool-display.js +83 -0
  166. package/dist/senses/cli/tool-render.js +85 -0
  167. package/dist/senses/cli/tui-store.js +198 -0
  168. package/dist/senses/cli/virtual-list.js +35 -0
  169. package/dist/senses/cli-entry.js +1 -1
  170. package/dist/senses/cli-layout.js +187 -0
  171. package/dist/senses/cli.js +508 -243
  172. package/dist/senses/commands.js +65 -1
  173. package/dist/senses/continuity.js +94 -0
  174. package/dist/senses/habit-turn-message.js +108 -0
  175. package/dist/senses/inner-dialog-worker.js +112 -19
  176. package/dist/senses/inner-dialog.js +592 -84
  177. package/dist/senses/pipeline.js +633 -0
  178. package/dist/senses/shared-turn.js +196 -0
  179. package/dist/senses/surface-tool.js +95 -0
  180. package/dist/senses/teams.js +667 -120
  181. package/dist/senses/trust-gate.js +112 -2
  182. package/package.json +16 -6
  183. package/skills/configure-dev-tools.md +81 -0
  184. package/subagents/README.md +4 -70
  185. package/dist/heart/daemon/subagent-installer.js +0 -134
  186. package/dist/senses/debug-activity.js +0 -107
  187. package/subagents/work-doer.md +0 -235
  188. package/subagents/work-merger.md +0 -618
  189. package/subagents/work-planner.md +0 -382
  190. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  191. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  192. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  193. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  194. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  195. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  196. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  197. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  198. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  199. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  200. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  201. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  202. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -34,26 +34,48 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ensureDaemonRunning = ensureDaemonRunning;
37
+ exports.listGithubCopilotModels = listGithubCopilotModels;
38
+ exports.pingGithubCopilotModel = pingGithubCopilotModel;
37
39
  exports.parseOuroCommand = parseOuroCommand;
40
+ exports.readFirstBundleMetaVersion = readFirstBundleMetaVersion;
38
41
  exports.discoverExistingCredentials = discoverExistingCredentials;
39
42
  exports.createDefaultOuroCliDeps = createDefaultOuroCliDeps;
40
43
  exports.runOuroCli = runOuroCli;
41
44
  const child_process_1 = require("child_process");
45
+ const crypto_1 = require("crypto");
42
46
  const fs = __importStar(require("fs"));
43
- const net = __importStar(require("net"));
44
47
  const os = __importStar(require("os"));
45
48
  const path = __importStar(require("path"));
49
+ const semver = __importStar(require("semver"));
46
50
  const identity_1 = require("../identity");
47
51
  const runtime_1 = require("../../nerves/runtime");
48
52
  const store_file_1 = require("../../mind/friends/store-file");
49
53
  const types_1 = require("../../mind/friends/types");
50
54
  const ouro_uti_1 = require("./ouro-uti");
51
55
  const ouro_path_installer_1 = require("./ouro-path-installer");
52
- const subagent_installer_1 = require("./subagent-installer");
56
+ const ouro_version_manager_1 = require("./ouro-version-manager");
57
+ const skill_management_installer_1 = require("./skill-management-installer");
53
58
  const hatch_flow_1 = require("./hatch-flow");
54
59
  const specialist_orchestrator_1 = require("./specialist-orchestrator");
55
60
  const specialist_prompt_1 = require("./specialist-prompt");
56
61
  const specialist_tools_1 = require("./specialist-tools");
62
+ const runtime_metadata_1 = require("./runtime-metadata");
63
+ const runtime_mode_1 = require("./runtime-mode");
64
+ const daemon_runtime_sync_1 = require("./daemon-runtime-sync");
65
+ const agent_discovery_1 = require("./agent-discovery");
66
+ const update_hooks_1 = require("./update-hooks");
67
+ const bundle_meta_1 = require("./hooks/bundle-meta");
68
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
69
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
70
+ const tasks_1 = require("../../repertoire/tasks");
71
+ const thoughts_1 = require("./thoughts");
72
+ const ouro_bot_global_installer_1 = require("./ouro-bot-global-installer");
73
+ const launchd_1 = require("./launchd");
74
+ const socket_client_1 = require("./socket-client");
75
+ const daemon_tombstone_1 = require("./daemon-tombstone");
76
+ const daemon_health_1 = require("./daemon-health");
77
+ const session_activity_1 = require("../session-activity");
78
+ const auth_flow_1 = require("./auth-flow");
57
79
  function stringField(value) {
58
80
  return typeof value === "string" ? value : null;
59
81
  }
@@ -78,8 +100,15 @@ function parseStatusPayload(data) {
78
100
  daemon: stringField(overview.daemon) ?? "unknown",
79
101
  health: stringField(overview.health) ?? "unknown",
80
102
  socketPath: stringField(overview.socketPath) ?? "unknown",
103
+ outlookUrl: stringField(overview.outlookUrl) ?? "unavailable",
104
+ version: stringField(overview.version) ?? "unknown",
105
+ lastUpdated: stringField(overview.lastUpdated) ?? "unknown",
106
+ repoRoot: stringField(overview.repoRoot) ?? "unknown",
107
+ configFingerprint: stringField(overview.configFingerprint) ?? "unknown",
81
108
  workerCount: numberField(overview.workerCount) ?? 0,
82
109
  senseCount: numberField(overview.senseCount) ?? 0,
110
+ entryPath: stringField(overview.entryPath) ?? "unknown",
111
+ mode: stringField(overview.mode) ?? "unknown",
83
112
  };
84
113
  const parsedSenses = senses.map((entry) => {
85
114
  if (!entry || typeof entry !== "object" || Array.isArray(entry))
@@ -120,6 +149,8 @@ function parseStatusPayload(data) {
120
149
  status,
121
150
  pid,
122
151
  restartCount,
152
+ lastExitCode: numberField(row.lastExitCode) ?? null,
153
+ lastSignal: stringField(row.lastSignal) ?? null,
123
154
  };
124
155
  });
125
156
  if (parsedSenses.some((row) => row === null) || parsedWorkers.some((row) => row === null))
@@ -143,7 +174,9 @@ function humanizeSenseName(sense, label) {
143
174
  }
144
175
  function formatTable(headers, rows) {
145
176
  const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index].length)));
146
- const renderRow = (row) => `| ${row.map((cell, index) => cell.padEnd(widths[index])).join(" | ")} |`;
177
+ const renderRow = (row) => `| ${row.map((cell, index) => (index === row.length - 1
178
+ ? cell
179
+ : cell.padEnd(widths[index]))).join(" | ")} |`;
147
180
  const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
148
181
  return [
149
182
  renderRow(headers),
@@ -158,6 +191,11 @@ function formatDaemonStatusOutput(response, fallback) {
158
191
  const overviewRows = [
159
192
  ["Daemon", payload.overview.daemon],
160
193
  ["Socket", payload.overview.socketPath],
194
+ ["Version", payload.overview.version],
195
+ ["Last Updated", payload.overview.lastUpdated],
196
+ ["Outlook", payload.overview.outlookUrl],
197
+ ["Entry Path", payload.overview.entryPath],
198
+ ["Mode", payload.overview.mode],
161
199
  ["Workers", String(payload.overview.workerCount)],
162
200
  ["Senses", String(payload.overview.senseCount)],
163
201
  ["Health", payload.overview.health],
@@ -169,13 +207,23 @@ function formatDaemonStatusOutput(response, fallback) {
169
207
  row.status,
170
208
  row.detail,
171
209
  ]);
172
- const workerRows = payload.workers.map((row) => [
173
- row.agent,
174
- row.worker,
175
- row.status,
176
- row.pid === null ? "n/a" : String(row.pid),
177
- String(row.restartCount),
178
- ]);
210
+ const workerRows = payload.workers.map((row) => {
211
+ /* v8 ignore start — exit info branches tested via daemon-crash-context; v8 misreports conditional chains @preserve */
212
+ let exitInfo = "n/a";
213
+ if (row.lastExitCode !== null)
214
+ exitInfo = `code=${row.lastExitCode}`;
215
+ if (row.lastSignal !== null)
216
+ exitInfo = row.lastExitCode !== null ? `code=${row.lastExitCode} sig=${row.lastSignal}` : `sig=${row.lastSignal}`;
217
+ /* v8 ignore stop */
218
+ return [
219
+ row.agent,
220
+ row.worker,
221
+ row.status,
222
+ row.pid === null ? "n/a" : String(row.pid),
223
+ String(row.restartCount),
224
+ exitInfo,
225
+ ];
226
+ });
179
227
  return [
180
228
  "Overview",
181
229
  formatTable(["Item", "Value"], overviewRows),
@@ -184,16 +232,41 @@ function formatDaemonStatusOutput(response, fallback) {
184
232
  formatTable(["Agent", "Sense", "Enabled", "State", "Detail"], senseRows),
185
233
  "",
186
234
  "Workers",
187
- formatTable(["Agent", "Worker", "State", "PID", "Restarts"], workerRows),
235
+ formatTable(["Agent", "Worker", "State", "PID", "Restarts", "Last Exit"], workerRows),
188
236
  ].join("\n");
189
237
  }
190
238
  async function ensureDaemonRunning(deps) {
191
239
  const alive = await deps.checkSocketAlive(deps.socketPath);
192
240
  if (alive) {
193
- return {
194
- alreadyRunning: true,
195
- message: `daemon already running (${deps.socketPath})`,
241
+ const localRuntime = (0, runtime_metadata_1.getRuntimeMetadata)();
242
+ let runningRuntimePromise = null;
243
+ const fetchRunningRuntimeMetadata = async () => {
244
+ runningRuntimePromise ??= (async () => {
245
+ const status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
246
+ const payload = parseStatusPayload(status.data);
247
+ return {
248
+ version: payload?.overview.version ?? "unknown",
249
+ lastUpdated: payload?.overview.lastUpdated ?? "unknown",
250
+ repoRoot: payload?.overview.repoRoot ?? "unknown",
251
+ configFingerprint: payload?.overview.configFingerprint ?? "unknown",
252
+ };
253
+ })();
254
+ return runningRuntimePromise;
196
255
  };
256
+ return (0, daemon_runtime_sync_1.ensureCurrentDaemonRuntime)({
257
+ socketPath: deps.socketPath,
258
+ localVersion: localRuntime.version,
259
+ localLastUpdated: localRuntime.lastUpdated,
260
+ localRepoRoot: localRuntime.repoRoot,
261
+ localConfigFingerprint: localRuntime.configFingerprint,
262
+ fetchRunningVersion: async () => (await fetchRunningRuntimeMetadata()).version,
263
+ fetchRunningRuntimeMetadata,
264
+ stopDaemon: async () => {
265
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
266
+ },
267
+ cleanupStaleSocket: deps.cleanupStaleSocket,
268
+ startDaemonProcess: deps.startDaemonProcess,
269
+ });
197
270
  }
198
271
  deps.cleanupStaleSocket(deps.socketPath);
199
272
  const started = await deps.startDaemonProcess(deps.socketPath);
@@ -202,17 +275,137 @@ async function ensureDaemonRunning(deps) {
202
275
  message: `daemon started (pid ${started.pid ?? "unknown"})`,
203
276
  };
204
277
  }
278
+ /**
279
+ * Extract `--agent <name>` from an args array, returning the agent name and
280
+ * the remaining args with the flag pair removed.
281
+ */
282
+ function extractAgentFlag(args) {
283
+ const idx = args.indexOf("--agent");
284
+ if (idx === -1 || idx + 1 >= args.length)
285
+ return { rest: args };
286
+ const agent = args[idx + 1];
287
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
288
+ return { agent, rest };
289
+ }
205
290
  function usage() {
206
291
  return [
207
292
  "Usage:",
208
293
  " ouro [up]",
209
- " ouro stop|status|logs|hatch",
294
+ " ouro dev [--repo-path <path>] [--clone [--clone-path <path>]]",
295
+ " ouro stop|down|status|logs|hatch",
296
+ " ouro outlook [--json]",
297
+ " ouro -v|--version",
298
+ " ouro config model --agent <name> <model-name>",
299
+ " ouro config models --agent <name>",
300
+ " ouro auth --agent <name> [--provider <provider>]",
301
+ " ouro auth verify --agent <name> [--provider <provider>]",
302
+ " ouro auth switch --agent <name> --provider <provider>",
210
303
  " ouro chat <agent>",
211
304
  " ouro msg --to <agent> [--session <id>] [--task <ref>] <message>",
212
305
  " ouro poke <agent> --task <task-id>",
306
+ " ouro poke <agent> --habit <name>",
307
+ " ouro habit list [--agent <name>]",
308
+ " ouro habit create [--agent <name>] <name> [--cadence <interval>]",
213
309
  " ouro link <agent> --friend <id> --provider <provider> --external-id <external-id>",
310
+ " ouro task board [<status>] [--agent <name>]",
311
+ " ouro task create <title> [--type <type>] [--agent <name>]",
312
+ " ouro task update <id> <status> [--agent <name>]",
313
+ " ouro task show <id> [--agent <name>]",
314
+ " ouro task fix [--safe|--all] [<id> [--option <N>]] [--agent <name>]",
315
+ " ouro task actionable|deps|sessions [--agent <name>]",
316
+ " ouro reminder create <title> --body <body> [--at <iso>] [--cadence <interval>] [--category <category>] [--agent <name>]",
317
+ " ouro friend list [--agent <name>]",
318
+ " ouro friend show <id> [--agent <name>]",
319
+ " ouro friend create --name <name> [--trust <level>] [--agent <name>]",
320
+ " ouro friend update <id> --trust <level> [--agent <name>]",
321
+ " ouro thoughts [--last <n>] [--json] [--follow] [--agent <name>]",
322
+ " ouro inner [--agent <name>]",
323
+ " ouro friend link <agent> --friend <id> --provider <p> --external-id <eid>",
324
+ " ouro friend unlink <agent> --friend <id> --provider <p> --external-id <eid>",
325
+ " ouro whoami [--agent <name>]",
326
+ " ouro session list [--agent <name>]",
327
+ " ouro mcp list",
328
+ " ouro mcp call <server> <tool> [--args '{...}']",
329
+ " ouro rollback [<version>]",
330
+ " ouro versions",
214
331
  ].join("\n");
215
332
  }
333
+ function formatVersionOutput() {
334
+ const version = (0, runtime_metadata_1.getRuntimeMetadata)().version;
335
+ const mode = (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)());
336
+ /* v8 ignore start — cosmetic display toggle; dev mode always true in test env */
337
+ return mode === "dev" ? `${version} (dev)` : version;
338
+ /* v8 ignore stop */
339
+ }
340
+ function buildStoppedStatusPayload(socketPath) {
341
+ const metadata = (0, runtime_metadata_1.getRuntimeMetadata)();
342
+ const repoRoot = (0, identity_1.getRepoRoot)();
343
+ return {
344
+ overview: {
345
+ daemon: "stopped",
346
+ health: "warn",
347
+ socketPath,
348
+ outlookUrl: "unavailable",
349
+ version: metadata.version,
350
+ lastUpdated: metadata.lastUpdated,
351
+ repoRoot: metadata.repoRoot,
352
+ configFingerprint: metadata.configFingerprint,
353
+ workerCount: 0,
354
+ senseCount: 0,
355
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
356
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
357
+ },
358
+ senses: [],
359
+ workers: [],
360
+ };
361
+ }
362
+ function daemonUnavailableStatusOutput(socketPath, healthFilePath) {
363
+ /* v8 ignore start — tombstone read tested in daemon-status-tombstone.test; branch misreported @preserve */
364
+ const tombstone = (0, daemon_tombstone_1.readDaemonTombstone)();
365
+ const deathLine = tombstone
366
+ ? `Last death: ${tombstone.timestamp} -- ${tombstone.reason}: ${tombstone.message}`
367
+ : null;
368
+ /* v8 ignore stop */
369
+ const lines = [
370
+ formatDaemonStatusOutput({
371
+ ok: true,
372
+ summary: "daemon not running",
373
+ data: buildStoppedStatusPayload(socketPath),
374
+ }, "daemon not running"),
375
+ "",
376
+ ];
377
+ /* v8 ignore start — tombstone presence requires real daemon crash @preserve */
378
+ if (deathLine) {
379
+ lines.push(deathLine);
380
+ lines.push("");
381
+ /* v8 ignore stop */
382
+ }
383
+ // Read health file for last-known state (best-effort)
384
+ const resolvedHealthPath = healthFilePath ?? (0, daemon_health_1.getDefaultHealthPath)();
385
+ const health = (0, daemon_health_1.readHealth)(resolvedHealthPath);
386
+ if (health) {
387
+ lines.push(`Last known status: ${health.status} (pid ${health.pid}, uptime ${health.uptimeSeconds}s)`);
388
+ if (health.safeMode?.active) {
389
+ lines.push(`SAFE MODE: ${health.safeMode.reason}`);
390
+ }
391
+ if (health.degraded.length > 0) {
392
+ lines.push("");
393
+ lines.push("Degraded:");
394
+ for (const d of health.degraded) {
395
+ lines.push(` ${d.component}: ${d.reason} (since ${d.since})`);
396
+ }
397
+ }
398
+ lines.push("");
399
+ }
400
+ lines.push("daemon not running; run `ouro up`");
401
+ return lines.join("\n");
402
+ }
403
+ function isDaemonUnavailableError(error) {
404
+ const code = typeof error === "object" && error !== null && "code" in error
405
+ ? String(error.code ?? "")
406
+ : "";
407
+ return code === "ENOENT" || code === "ECONNREFUSED";
408
+ }
216
409
  function parseMessageCommand(args) {
217
410
  let to;
218
411
  let sessionId;
@@ -254,17 +447,56 @@ function parsePokeCommand(args) {
254
447
  if (!agent)
255
448
  throw new Error(`Usage\n${usage()}`);
256
449
  let taskId;
450
+ let habitName;
257
451
  for (let i = 1; i < args.length; i += 1) {
258
452
  if (args[i] === "--task") {
259
453
  taskId = args[i + 1];
260
454
  i += 1;
261
455
  }
456
+ if (args[i] === "--habit") {
457
+ habitName = args[i + 1];
458
+ i += 1;
459
+ }
262
460
  }
461
+ // --habit takes priority over --task
462
+ if (habitName)
463
+ return { kind: "habit.poke", agent, habitName };
263
464
  if (!taskId)
264
465
  throw new Error(`Usage\n${usage()}`);
265
466
  return { kind: "task.poke", agent, taskId };
266
467
  }
267
- function parseLinkCommand(args) {
468
+ function parseHabitCommand(args) {
469
+ const { agent, rest } = extractAgentFlag(args);
470
+ const sub = rest[0];
471
+ if (sub === "list") {
472
+ return { kind: "habit.list", ...(agent ? { agent } : {}) };
473
+ }
474
+ if (sub === "create") {
475
+ const nameArgs = rest.slice(1);
476
+ let name;
477
+ let cadence;
478
+ const positional = [];
479
+ for (let i = 0; i < nameArgs.length; i++) {
480
+ if (nameArgs[i] === "--cadence" && nameArgs[i + 1]) {
481
+ cadence = nameArgs[++i];
482
+ continue;
483
+ }
484
+ /* v8 ignore start -- defensive: --agent already extracted by extractAgentFlag; guard prevents regression if parsing flow changes @preserve */
485
+ if (nameArgs[i] === "--agent" && nameArgs[i + 1]) {
486
+ i++; // skip --agent value (already extracted)
487
+ continue;
488
+ }
489
+ /* v8 ignore stop */
490
+ positional.push(nameArgs[i]);
491
+ }
492
+ name = positional[0];
493
+ if (!name)
494
+ throw new Error(`Usage\n${usage()}`);
495
+ return { kind: "habit.create", name, ...(agent ? { agent } : {}), ...(cadence ? { cadence } : {}) };
496
+ }
497
+ throw new Error(`Usage\n${usage()}`);
498
+ }
499
+ function parseLinkCommand(args, kind = "friend.link") {
268
500
  const agent = args[0];
269
501
  if (!agent)
270
502
  throw new Error(`Usage\n${usage()}`);
@@ -296,7 +528,7 @@ function parseLinkCommand(args) {
296
528
  throw new Error(`Unknown identity provider '${providerRaw}'. Use aad|local|teams-conversation.`);
297
529
  }
298
530
  return {
299
- kind: "friend.link",
531
+ kind,
300
532
  agent,
301
533
  friendId,
302
534
  provider: providerRaw,
@@ -304,7 +536,102 @@ function parseLinkCommand(args) {
304
536
  };
305
537
  }
306
538
  function isAgentProvider(value) {
307
- return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex";
539
+ return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex" || value === "github-copilot";
540
+ }
541
+ /* v8 ignore start -- hasStoredCredentials: per-provider branches tested via auth switch tests @preserve */
542
+ function hasStoredCredentials(provider, providerSecrets) {
543
+ if (provider === "anthropic")
544
+ return !!providerSecrets.setupToken;
545
+ if (provider === "openai-codex")
546
+ return !!providerSecrets.oauthAccessToken;
547
+ if (provider === "github-copilot")
548
+ return !!providerSecrets.githubToken;
549
+ if (provider === "minimax")
550
+ return !!providerSecrets.apiKey;
551
+ // azure
552
+ return !!providerSecrets.endpoint && !!providerSecrets.apiKey;
553
+ }
554
+ /* v8 ignore stop */
555
+ /* v8 ignore start -- verifyProviderCredentials: delegates to pingProvider @preserve */
556
+ async function verifyProviderCredentials(provider, providers) {
557
+ const config = providers[provider];
558
+ if (!config)
559
+ return "not configured";
560
+ try {
561
+ const { pingProvider } = await Promise.resolve().then(() => __importStar(require("../../heart/provider-ping")));
562
+ const result = await pingProvider(provider, config);
563
+ return result.ok ? "ok" : `failed (${result.message})`;
564
+ }
565
+ catch (error) {
566
+ return `failed (${error instanceof Error ? error.message : String(error)})`;
567
+ }
568
+ }
569
+ async function listGithubCopilotModels(baseUrl, token, fetchImpl = fetch) {
570
+ const url = `${baseUrl.replace(/\/+$/, "")}/models`;
571
+ const response = await fetchImpl(url, {
572
+ headers: { Authorization: `Bearer ${token}` },
573
+ });
574
+ if (!response.ok) {
575
+ throw new Error(`model listing failed (HTTP ${response.status})`);
576
+ }
577
+ const body = await response.json();
578
+ /* v8 ignore start -- response shape handling: tested via config-models.test.ts @preserve */
579
+ const items = Array.isArray(body) ? body : (body?.data ?? []);
580
+ return items.map((item) => {
581
+ const rec = item;
582
+ const capabilities = Array.isArray(rec.capabilities)
583
+ ? rec.capabilities.filter((c) => typeof c === "string")
584
+ : undefined;
585
+ return {
586
+ id: String(rec.id ?? rec.name ?? ""),
587
+ name: String(rec.name ?? rec.id ?? ""),
588
+ ...(capabilities ? { capabilities } : {}),
589
+ };
590
+ });
591
+ /* v8 ignore stop */
592
+ }
593
+ async function pingGithubCopilotModel(baseUrl, token, model, fetchImpl = fetch) {
594
+ const base = baseUrl.replace(/\/+$/, "");
595
+ const isClaude = model.startsWith("claude");
596
+ const url = isClaude ? `${base}/chat/completions` : `${base}/responses`;
597
+ const body = isClaude
598
+ ? JSON.stringify({ model, messages: [{ role: "user", content: "ping" }], max_tokens: 1 })
599
+ : JSON.stringify({ model, input: "ping", max_output_tokens: 16 });
600
+ try {
601
+ const response = await fetchImpl(url, {
602
+ method: "POST",
603
+ headers: {
604
+ Authorization: `Bearer ${token}`,
605
+ "Content-Type": "application/json",
606
+ },
607
+ body,
608
+ });
609
+ if (response.ok)
610
+ return { ok: true };
611
+ let detail = `HTTP ${response.status}`;
612
+ try {
613
+ const json = await response.json();
614
+ /* v8 ignore start -- error format parsing: all branches tested via config-models.test.ts @preserve */
615
+ if (typeof json.error === "string")
616
+ detail = json.error;
617
+ else if (typeof json.error === "object" && json.error !== null) {
618
+ const errObj = json.error;
619
+ if (typeof errObj.message === "string")
620
+ detail = errObj.message;
621
+ }
622
+ else if (typeof json.message === "string")
623
+ detail = json.message;
624
+ /* v8 ignore stop */
625
+ }
626
+ catch {
627
+ // response body not JSON — keep HTTP status
628
+ }
629
+ return { ok: false, error: detail };
630
+ }
631
+ catch (err) {
632
+ /* v8 ignore next -- defensive: fetch errors are always Error instances @preserve */
633
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
634
+ }
308
635
  }
309
636
  function parseHatchCommand(args) {
310
637
  let agentName;
@@ -361,7 +688,7 @@ function parseHatchCommand(args) {
361
688
  }
362
689
  }
363
690
  if (providerRaw && !isAgentProvider(providerRaw)) {
364
- throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex.");
691
+ throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex|github-copilot.");
365
692
  }
366
693
  const provider = providerRaw && isAgentProvider(providerRaw) ? providerRaw : undefined;
367
694
  return {
@@ -373,20 +700,480 @@ function parseHatchCommand(args) {
373
700
  migrationPath,
374
701
  };
375
702
  }
703
+ function parseTaskCommand(args) {
704
+ const { agent, rest: cleaned } = extractAgentFlag(args);
705
+ const [sub, ...rest] = cleaned;
706
+ if (!sub)
707
+ throw new Error(`Usage\n${usage()}`);
708
+ if (sub === "board") {
709
+ const status = rest[0];
710
+ return status
711
+ ? { kind: "task.board", status, ...(agent ? { agent } : {}) }
712
+ : { kind: "task.board", ...(agent ? { agent } : {}) };
713
+ }
714
+ if (sub === "create") {
715
+ const title = rest[0];
716
+ if (!title)
717
+ throw new Error(`Usage\n${usage()}`);
718
+ let type;
719
+ for (let i = 1; i < rest.length; i++) {
720
+ if (rest[i] === "--type" && rest[i + 1]) {
721
+ type = rest[i + 1];
722
+ i += 1;
723
+ }
724
+ }
725
+ return type
726
+ ? { kind: "task.create", title, type, ...(agent ? { agent } : {}) }
727
+ : { kind: "task.create", title, ...(agent ? { agent } : {}) };
728
+ }
729
+ if (sub === "update") {
730
+ const id = rest[0];
731
+ const status = rest[1];
732
+ if (!id || !status)
733
+ throw new Error(`Usage\n${usage()}`);
734
+ return { kind: "task.update", id, status, ...(agent ? { agent } : {}) };
735
+ }
736
+ if (sub === "show") {
737
+ const id = rest[0];
738
+ if (!id)
739
+ throw new Error(`Usage\n${usage()}`);
740
+ return { kind: "task.show", id, ...(agent ? { agent } : {}) };
741
+ }
742
+ if (sub === "actionable")
743
+ return { kind: "task.actionable", ...(agent ? { agent } : {}) };
744
+ if (sub === "deps")
745
+ return { kind: "task.deps", ...(agent ? { agent } : {}) };
746
+ if (sub === "sessions")
747
+ return { kind: "task.sessions", ...(agent ? { agent } : {}) };
748
+ if (sub === "fix") {
749
+ // fix --safe | fix --all | fix <id> [--option N] | fix (dry-run)
750
+ if (rest.length === 0)
751
+ return { kind: "task.fix", mode: "dry-run", ...(agent ? { agent } : {}) };
752
+ const first = rest[0];
753
+ if (first === "--safe" || first === "--all") {
754
+ return { kind: "task.fix", mode: "safe", ...(agent ? { agent } : {}) };
755
+ }
756
+ // first arg is an issue ID (contains a colon, e.g. schema-missing-kind:one-shots/foo.md)
757
+ const issueId = first;
758
+ let option;
759
+ for (let i = 1; i < rest.length; i++) {
760
+ if (rest[i] === "--option" && rest[i + 1]) {
761
+ option = parseInt(rest[i + 1], 10);
762
+ i += 1;
763
+ }
764
+ }
765
+ return {
766
+ kind: "task.fix",
767
+ mode: "single",
768
+ issueId,
769
+ ...(option !== undefined ? { option } : {}),
770
+ ...(agent ? { agent } : {}),
771
+ };
772
+ }
773
+ throw new Error(`Usage\n${usage()}`);
774
+ }
775
+ function extractFacingFlag(args) {
776
+ const idx = args.indexOf("--facing");
777
+ if (idx === -1 || idx + 1 >= args.length)
778
+ return { rest: args };
779
+ const value = args[idx + 1];
780
+ if (value !== "human" && value !== "agent") {
781
+ throw new Error(`--facing must be 'human' or 'agent'`);
782
+ }
783
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
784
+ return { facing: value, rest };
785
+ }
786
+ function parseAuthCommand(args) {
787
+ const first = args[0];
788
+ // Support both positional (`auth switch`) and flag (`auth --switch`) forms
789
+ if (first === "verify" || first === "switch" || first === "--verify" || first === "--switch") {
790
+ const subcommand = first.replace(/^--/, "");
791
+ const { agent, rest: afterAgent } = extractAgentFlag(args.slice(1));
792
+ const { facing, rest } = extractFacingFlag(afterAgent);
793
+ let provider;
794
+ /* v8 ignore start -- provider flag parsing: branches tested via CLI parsing tests @preserve */
795
+ for (let i = 0; i < rest.length; i += 1) {
796
+ if (rest[i] === "--provider") {
797
+ const value = rest[i + 1];
798
+ if (!isAgentProvider(value))
799
+ throw new Error(`Usage\n${usage()}`);
800
+ provider = value;
801
+ i += 1;
802
+ continue;
803
+ }
804
+ }
805
+ /* v8 ignore stop */
806
+ /* v8 ignore next -- defensive: agent always provided in tests @preserve */
807
+ if (!agent)
808
+ throw new Error(`Usage\n${usage()}`);
809
+ if (subcommand === "switch") {
810
+ if (!provider)
811
+ throw new Error(`auth switch requires --provider.\n${usage()}`);
812
+ return facing ? { kind: "auth.switch", agent, provider, facing } : { kind: "auth.switch", agent, provider };
813
+ }
814
+ return provider ? { kind: "auth.verify", agent, provider } : { kind: "auth.verify", agent };
815
+ }
816
+ const { agent, rest } = extractAgentFlag(args);
817
+ let provider;
818
+ for (let i = 0; i < rest.length; i += 1) {
819
+ if (rest[i] === "--provider") {
820
+ const value = rest[i + 1];
821
+ if (!isAgentProvider(value))
822
+ throw new Error(`Usage\n${usage()}`);
823
+ provider = value;
824
+ i += 1;
825
+ continue;
826
+ }
827
+ }
828
+ if (!agent) {
829
+ throw new Error([
830
+ "Usage:",
831
+ " ouro auth --agent <name> [--provider <provider>] Set up credentials",
832
+ " ouro auth verify --agent <name> [--provider <p>] Verify credentials work",
833
+ " ouro auth switch --agent <name> --provider <p> Switch active provider",
834
+ ].join("\n"));
835
+ }
836
+ return provider ? { kind: "auth.run", agent, provider } : { kind: "auth.run", agent };
837
+ }
838
+ function parseReminderCommand(args) {
839
+ const { agent, rest: cleaned } = extractAgentFlag(args);
840
+ const [sub, ...rest] = cleaned;
841
+ if (!sub)
842
+ throw new Error(`Usage\n${usage()}`);
843
+ if (sub === "create") {
844
+ const title = rest[0];
845
+ if (!title)
846
+ throw new Error(`Usage\n${usage()}`);
847
+ let body;
848
+ let scheduledAt;
849
+ let cadence;
850
+ let category;
851
+ let requester;
852
+ for (let i = 1; i < rest.length; i++) {
853
+ if (rest[i] === "--body" && rest[i + 1]) {
854
+ body = rest[i + 1];
855
+ i += 1;
856
+ }
857
+ else if (rest[i] === "--at" && rest[i + 1]) {
858
+ scheduledAt = rest[i + 1];
859
+ i += 1;
860
+ }
861
+ else if (rest[i] === "--cadence" && rest[i + 1]) {
862
+ cadence = rest[i + 1];
863
+ i += 1;
864
+ }
865
+ else if (rest[i] === "--category" && rest[i + 1]) {
866
+ category = rest[i + 1];
867
+ i += 1;
868
+ }
869
+ else if (rest[i] === "--requester" && rest[i + 1]) {
870
+ requester = rest[i + 1];
871
+ i += 1;
872
+ }
873
+ }
874
+ if (!body)
875
+ throw new Error(`Usage\n${usage()}`);
876
+ if (!scheduledAt && !cadence)
877
+ throw new Error(`Usage\n${usage()}`);
878
+ return {
879
+ kind: "reminder.create",
880
+ title,
881
+ body,
882
+ ...(scheduledAt ? { scheduledAt } : {}),
883
+ ...(cadence ? { cadence } : {}),
884
+ ...(category ? { category } : {}),
885
+ ...(requester ? { requester } : {}),
886
+ ...(agent ? { agent } : {}),
887
+ };
888
+ }
889
+ throw new Error(`Usage\n${usage()}`);
890
+ }
891
+ function parseSessionCommand(args) {
892
+ const { agent, rest: cleaned } = extractAgentFlag(args);
893
+ const [sub] = cleaned;
894
+ if (!sub)
895
+ throw new Error(`Usage\n${usage()}`);
896
+ if (sub === "list")
897
+ return { kind: "session.list", ...(agent ? { agent } : {}) };
898
+ throw new Error(`Usage\n${usage()}`);
899
+ }
900
+ function parseAttentionCommand(args) {
901
+ const { agent, rest: cleaned } = extractAgentFlag(args);
902
+ const sub = cleaned[0];
903
+ if (sub === "show" && cleaned[1]) {
904
+ return { kind: "attention.show", id: cleaned[1], ...(agent ? { agent } : {}) };
905
+ }
906
+ if (sub === "history") {
907
+ return { kind: "attention.history", ...(agent ? { agent } : {}) };
908
+ }
909
+ return { kind: "attention.list", ...(agent ? { agent } : {}) };
910
+ }
911
+ function parseThoughtsCommand(args) {
912
+ const { agent, rest: cleaned } = extractAgentFlag(args);
913
+ let last;
914
+ let json = false;
915
+ let follow = false;
916
+ for (let i = 0; i < cleaned.length; i++) {
917
+ if (cleaned[i] === "--last" && i + 1 < cleaned.length) {
918
+ last = Number.parseInt(cleaned[i + 1], 10);
919
+ i++;
920
+ }
921
+ if (cleaned[i] === "--json")
922
+ json = true;
923
+ if (cleaned[i] === "--follow" || cleaned[i] === "-f")
924
+ follow = true;
925
+ }
926
+ return { kind: "thoughts", ...(agent ? { agent } : {}), ...(last ? { last } : {}), ...(json ? { json } : {}), ...(follow ? { follow } : {}) };
927
+ }
928
+ function parseFriendCommand(args) {
929
+ const { agent, rest: cleaned } = extractAgentFlag(args);
930
+ const [sub, ...rest] = cleaned;
931
+ if (!sub)
932
+ throw new Error(`Usage\n${usage()}`);
933
+ if (sub === "list")
934
+ return { kind: "friend.list", ...(agent ? { agent } : {}) };
935
+ if (sub === "show") {
936
+ const friendId = rest[0];
937
+ if (!friendId)
938
+ throw new Error(`Usage\n${usage()}`);
939
+ return { kind: "friend.show", friendId, ...(agent ? { agent } : {}) };
940
+ }
941
+ if (sub === "create") {
942
+ let name;
943
+ let trustLevel;
944
+ for (let i = 0; i < rest.length; i++) {
945
+ if (rest[i] === "--name" && rest[i + 1]) {
946
+ name = rest[i + 1];
947
+ i += 1;
948
+ }
949
+ else if (rest[i] === "--trust" && rest[i + 1]) {
950
+ trustLevel = rest[i + 1];
951
+ i += 1;
952
+ }
953
+ }
954
+ if (!name)
955
+ throw new Error(`Usage\n${usage()}`);
956
+ return {
957
+ kind: "friend.create",
958
+ name,
959
+ ...(trustLevel ? { trustLevel } : {}),
960
+ ...(agent ? { agent } : {}),
961
+ };
962
+ }
963
+ if (sub === "update") {
964
+ const friendId = rest[0];
965
+ if (!friendId)
966
+ throw new Error(`Usage: ouro friend update <id> --trust <level>`);
967
+ let trustLevel;
968
+ /* v8 ignore start -- flag parsing loop: tested via CLI parsing tests @preserve */
969
+ for (let i = 1; i < rest.length; i++) {
970
+ if (rest[i] === "--trust" && rest[i + 1]) {
971
+ trustLevel = rest[i + 1];
972
+ i += 1;
973
+ }
974
+ }
975
+ /* v8 ignore stop */
976
+ const VALID_TRUST_LEVELS = new Set(["stranger", "acquaintance", "friend", "family"]);
977
+ if (!trustLevel || !VALID_TRUST_LEVELS.has(trustLevel)) {
978
+ throw new Error(`Usage: ouro friend update <id> --trust <stranger|acquaintance|friend|family>`);
979
+ }
980
+ return {
981
+ kind: "friend.update",
982
+ friendId,
983
+ trustLevel: trustLevel,
984
+ ...(agent ? { agent } : {}),
985
+ };
986
+ }
987
+ if (sub === "link")
988
+ return parseLinkCommand(rest, "friend.link");
989
+ if (sub === "unlink")
990
+ return parseLinkCommand(rest, "friend.unlink");
991
+ throw new Error(`Usage\n${usage()}`);
992
+ }
993
+ function parseConfigCommand(args) {
994
+ const { agent, rest: afterAgent } = extractAgentFlag(args);
995
+ const { facing, rest: cleaned } = extractFacingFlag(afterAgent);
996
+ const [sub, ...rest] = cleaned;
997
+ if (!sub)
998
+ throw new Error(`Usage\n${usage()}`);
999
+ if (sub === "model") {
1000
+ if (!agent)
1001
+ throw new Error("--agent is required for config model");
1002
+ const modelName = rest[0];
1003
+ if (!modelName)
1004
+ throw new Error(`Usage: ouro config model --agent <name> <model-name>`);
1005
+ return facing ? { kind: "config.model", agent, modelName, facing } : { kind: "config.model", agent, modelName };
1006
+ }
1007
+ if (sub === "models") {
1008
+ if (!agent)
1009
+ throw new Error("--agent is required for config models");
1010
+ return { kind: "config.models", agent };
1011
+ }
1012
+ throw new Error(`Usage\n${usage()}`);
1013
+ }
1014
+ function parseMcpCommand(args) {
1015
+ const [sub, ...rest] = args;
1016
+ if (!sub)
1017
+ throw new Error(`Usage\n${usage()}`);
1018
+ if (sub === "list")
1019
+ return { kind: "mcp.list" };
1020
+ if (sub === "call") {
1021
+ const server = rest[0];
1022
+ const tool = rest[1];
1023
+ if (!server || !tool)
1024
+ throw new Error(`Usage\n${usage()}`);
1025
+ const argsIdx = rest.indexOf("--args");
1026
+ const mcpArgs = argsIdx !== -1 && rest[argsIdx + 1] ? rest[argsIdx + 1] : undefined;
1027
+ return { kind: "mcp.call", server, tool, ...(mcpArgs ? { args: mcpArgs } : {}) };
1028
+ }
1029
+ throw new Error(`Usage\n${usage()}`);
1030
+ }
1031
+ function parseMcpServeCommand(args) {
1032
+ let agent;
1033
+ let friendId;
1034
+ let socketOverride;
1035
+ for (let i = 0; i < args.length; i++) {
1036
+ if (args[i] === "--agent" && args[i + 1]) {
1037
+ agent = args[++i];
1038
+ continue;
1039
+ }
1040
+ if (args[i] === "--friend" && args[i + 1]) {
1041
+ friendId = args[++i];
1042
+ continue;
1043
+ }
1044
+ if (args[i] === "--socket" && args[i + 1]) {
1045
+ socketOverride = args[++i];
1046
+ continue;
1047
+ }
1048
+ }
1049
+ if (!agent)
1050
+ throw new Error("mcp-serve requires --agent <name>");
1051
+ return { kind: "mcp-serve", agent, ...(friendId ? { friendId } : {}), ...(socketOverride ? { socketOverride } : {}) };
1052
+ }
1053
+ function parseSetupCommand(args) {
1054
+ let tool;
1055
+ let agent;
1056
+ for (let i = 0; i < args.length; i++) {
1057
+ if (args[i] === "--tool" && args[i + 1]) {
1058
+ tool = args[++i];
1059
+ continue;
1060
+ }
1061
+ if (args[i] === "--agent" && args[i + 1]) {
1062
+ agent = args[++i];
1063
+ continue;
1064
+ }
1065
+ }
1066
+ if (!tool)
1067
+ throw new Error("setup requires --tool (claude-code | codex)");
1068
+ if (tool !== "claude-code" && tool !== "codex")
1069
+ throw new Error(`Unknown tool: ${tool}. Supported: claude-code, codex`);
1070
+ if (!agent)
1071
+ throw new Error("setup requires --agent <name>");
1072
+ return { kind: "setup", tool, agent };
1073
+ }
376
1074
  function parseOuroCommand(args) {
377
1075
  const [head, second] = args;
378
1076
  if (!head)
379
1077
  return { kind: "daemon.up" };
1078
+ if (head === "--agent" && second) {
1079
+ return parseOuroCommand(args.slice(2));
1080
+ }
1081
+ if (head === "hook") {
1082
+ const hookArgs = args.slice(1);
1083
+ let event;
1084
+ let hookAgent;
1085
+ for (let i = 0; i < hookArgs.length; i++) {
1086
+ if (hookArgs[i] === "--agent" && hookArgs[i + 1]) {
1087
+ hookAgent = hookArgs[++i];
1088
+ continue;
1089
+ }
1090
+ /* v8 ignore start -- false branch: extra positional args after event are ignored */
1091
+ if (!event) {
1092
+ event = hookArgs[i];
1093
+ }
1094
+ /* v8 ignore stop */
1095
+ }
1096
+ if (!event)
1097
+ throw new Error("hook requires an event name (session-start, stop, post-tool-use)");
1098
+ if (!hookAgent)
1099
+ throw new Error("hook requires --agent <name>");
1100
+ return { kind: "hook", event, agent: hookAgent };
1101
+ }
380
1102
  if (head === "up")
381
1103
  return { kind: "daemon.up" };
382
- if (head === "stop")
1104
+ if (head === "dev") {
1105
+ const devArgs = args.slice(1);
1106
+ let repoPath;
1107
+ let clone = false;
1108
+ let clonePath;
1109
+ for (let i = 0; i < devArgs.length; i++) {
1110
+ if (devArgs[i] === "--repo-path" && devArgs[i + 1]) {
1111
+ repoPath = devArgs[++i];
1112
+ continue;
1113
+ }
1114
+ if (devArgs[i] === "--clone") {
1115
+ clone = true;
1116
+ continue;
1117
+ }
1118
+ if (devArgs[i] === "--clone-path" && devArgs[i + 1]) {
1119
+ clonePath = devArgs[++i];
1120
+ continue;
1121
+ }
1122
+ }
1123
+ return { kind: "daemon.dev", repoPath, clone, clonePath };
1124
+ }
1125
+ if (head === "rollback")
1126
+ return { kind: "rollback", ...(second ? { version: second } : {}) };
1127
+ if (head === "versions")
1128
+ return { kind: "versions" };
1129
+ if (head === "stop" || head === "down")
383
1130
  return { kind: "daemon.stop" };
384
1131
  if (head === "status")
385
1132
  return { kind: "daemon.status" };
386
1133
  if (head === "logs")
387
1134
  return { kind: "daemon.logs" };
1135
+ if (head === "outlook")
1136
+ return { kind: "outlook", ...(args.includes("--json") ? { json: true } : {}) };
388
1137
  if (head === "hatch")
389
1138
  return parseHatchCommand(args.slice(1));
1139
+ if (head === "auth")
1140
+ return parseAuthCommand(args.slice(1));
1141
+ if (head === "task")
1142
+ return parseTaskCommand(args.slice(1));
1143
+ if (head === "reminder")
1144
+ return parseReminderCommand(args.slice(1));
1145
+ if (head === "habit")
1146
+ return parseHabitCommand(args.slice(1));
1147
+ if (head === "friend")
1148
+ return parseFriendCommand(args.slice(1));
1149
+ if (head === "config")
1150
+ return parseConfigCommand(args.slice(1));
1151
+ if (head === "mcp")
1152
+ return parseMcpCommand(args.slice(1));
1153
+ if (head === "whoami") {
1154
+ const { agent } = extractAgentFlag(args.slice(1));
1155
+ return { kind: "whoami", ...(agent ? { agent } : {}) };
1156
+ }
1157
+ if (head === "session")
1158
+ return parseSessionCommand(args.slice(1));
1159
+ if (head === "changelog") {
1160
+ const sliced = args.slice(1);
1161
+ const { agent, rest: remaining } = extractAgentFlag(sliced);
1162
+ let from;
1163
+ const fromIdx = remaining.indexOf("--from");
1164
+ if (fromIdx !== -1 && remaining[fromIdx + 1]) {
1165
+ from = remaining[fromIdx + 1];
1166
+ }
1167
+ return { kind: "changelog", ...(from ? { from } : {}), ...(agent ? { agent } : {}) };
1168
+ }
1169
+ if (head === "thoughts")
1170
+ return parseThoughtsCommand(args.slice(1));
1171
+ if (head === "attention")
1172
+ return parseAttentionCommand(args.slice(1));
1173
+ if (head === "inner") {
1174
+ const { agent } = extractAgentFlag(args.slice(1));
1175
+ return { kind: "inner.status", ...(agent ? { agent } : {}) };
1176
+ }
390
1177
  if (head === "chat") {
391
1178
  if (!second)
392
1179
  throw new Error(`Usage\n${usage()}`);
@@ -398,92 +1185,56 @@ function parseOuroCommand(args) {
398
1185
  return parsePokeCommand(args.slice(1));
399
1186
  if (head === "link")
400
1187
  return parseLinkCommand(args.slice(1));
1188
+ if (head === "mcp-serve")
1189
+ return parseMcpServeCommand(args.slice(1));
1190
+ if (head === "setup")
1191
+ return parseSetupCommand(args.slice(1));
401
1192
  throw new Error(`Unknown command '${args.join(" ")}'.\n${usage()}`);
402
1193
  }
403
- function defaultSendCommand(socketPath, command) {
404
- return new Promise((resolve, reject) => {
405
- const client = net.createConnection(socketPath);
406
- let raw = "";
407
- client.on("connect", () => {
408
- client.write(JSON.stringify(command));
409
- client.end();
410
- });
411
- client.on("data", (chunk) => {
412
- raw += chunk.toString("utf-8");
413
- });
414
- client.on("error", reject);
415
- client.on("end", () => {
416
- const trimmed = raw.trim();
417
- if (trimmed.length === 0 && command.kind === "daemon.stop") {
418
- resolve({ ok: true, message: "daemon stopped" });
419
- return;
420
- }
421
- if (trimmed.length === 0) {
422
- reject(new Error("Daemon returned empty response."));
423
- return;
424
- }
425
- try {
426
- const parsed = JSON.parse(trimmed);
427
- resolve(parsed);
428
- }
429
- catch (error) {
430
- reject(error);
431
- }
432
- });
433
- });
434
- }
435
1194
  function defaultStartDaemonProcess(socketPath) {
436
1195
  const entry = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
1196
+ // Redirect stdio to /dev/null via file descriptors — using 'ignore' causes EPIPE
1197
+ // when the daemon's logging system writes to stderr after the parent exits.
1198
+ const outFd = fs.openSync(os.devNull, "w");
1199
+ const errFd = fs.openSync(os.devNull, "w");
437
1200
  const child = (0, child_process_1.spawn)("node", [entry, "--socket", socketPath], {
438
1201
  detached: true,
439
- stdio: "ignore",
1202
+ stdio: ["ignore", outFd, errFd],
440
1203
  });
441
1204
  child.unref();
1205
+ // Don't close fds — the child process needs them. They'll be cleaned up when the parent exits.
442
1206
  return Promise.resolve({ pid: child.pid ?? null });
443
1207
  }
444
1208
  function defaultWriteStdout(text) {
445
1209
  // eslint-disable-next-line no-console -- terminal UX: CLI command output
446
1210
  console.log(text);
447
1211
  }
448
- function defaultCheckSocketAlive(socketPath) {
449
- return new Promise((resolve) => {
450
- const client = net.createConnection(socketPath);
451
- let raw = "";
452
- let done = false;
453
- const finalize = (alive) => {
454
- if (done)
455
- return;
456
- done = true;
457
- resolve(alive);
458
- };
459
- if ("setTimeout" in client && typeof client.setTimeout === "function") {
460
- client.setTimeout(800, () => {
461
- client.destroy();
462
- finalize(false);
463
- });
1212
+ /**
1213
+ * Read the runtimeVersion from the first .ouro bundle's bundle-meta.json.
1214
+ * Returns undefined if none found or unreadable.
1215
+ */
1216
+ function readFirstBundleMetaVersion(bundlesRoot) {
1217
+ try {
1218
+ if (!fs.existsSync(bundlesRoot))
1219
+ return undefined;
1220
+ const entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
1221
+ for (const entry of entries) {
1222
+ /* v8 ignore next -- skip non-.ouro dirs: tested via version-detect tests @preserve */
1223
+ if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
1224
+ continue;
1225
+ const metaPath = path.join(bundlesRoot, entry.name, "bundle-meta.json");
1226
+ if (!fs.existsSync(metaPath))
1227
+ continue;
1228
+ const raw = fs.readFileSync(metaPath, "utf-8");
1229
+ const meta = JSON.parse(raw);
1230
+ if (meta.runtimeVersion)
1231
+ return meta.runtimeVersion;
464
1232
  }
465
- client.on("connect", () => {
466
- client.write(JSON.stringify({ kind: "daemon.status" }));
467
- client.end();
468
- });
469
- client.on("data", (chunk) => {
470
- raw += chunk.toString("utf-8");
471
- });
472
- client.on("error", () => finalize(false));
473
- client.on("end", () => {
474
- if (raw.trim().length === 0) {
475
- finalize(false);
476
- return;
477
- }
478
- try {
479
- JSON.parse(raw);
480
- finalize(true);
481
- }
482
- catch {
483
- finalize(false);
484
- }
485
- });
486
- });
1233
+ }
1234
+ catch {
1235
+ // Best effort — return undefined on any error
1236
+ }
1237
+ return undefined;
487
1238
  }
488
1239
  function defaultCleanupStaleSocket(socketPath) {
489
1240
  if (fs.existsSync(socketPath)) {
@@ -519,9 +1270,38 @@ function defaultFallbackPendingMessage(command) {
519
1270
  });
520
1271
  return pendingPath;
521
1272
  }
522
- async function defaultInstallSubagents() {
523
- return (0, subagent_installer_1.installSubagentsForAvailableCli)({
524
- repoRoot: (0, identity_1.getRepoRoot)(),
1273
+ function defaultEnsureDaemonBootPersistence(socketPath) {
1274
+ if (process.platform !== "darwin") {
1275
+ return;
1276
+ }
1277
+ const homeDir = os.homedir();
1278
+ const launchdDeps = {
1279
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd, { stdio: "ignore" }); },
1280
+ writeFile: (filePath, content) => fs.writeFileSync(filePath, content, "utf-8"),
1281
+ removeFile: (filePath) => fs.rmSync(filePath, { force: true }),
1282
+ existsFile: (filePath) => fs.existsSync(filePath),
1283
+ mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
1284
+ homeDir,
1285
+ userUid: process.getuid?.() ?? 0,
1286
+ };
1287
+ const entryPath = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
1288
+ /* v8 ignore next -- covered via mock in daemon-cli-defaults.test.ts; v8 on CI attributes the real fs.existsSync branch to the non-mock load @preserve */
1289
+ if (!fs.existsSync(entryPath)) {
1290
+ (0, runtime_1.emitNervesEvent)({
1291
+ level: "warn",
1292
+ component: "daemon",
1293
+ event: "daemon.entry_path_missing",
1294
+ message: "entryPath does not exist on disk — plist may point to a stale location. Run 'ouro daemon install' from the correct location.",
1295
+ meta: { entryPath },
1296
+ });
1297
+ }
1298
+ const logDir = (0, identity_1.getAgentDaemonLogsDir)();
1299
+ (0, launchd_1.installLaunchAgent)(launchdDeps, {
1300
+ nodePath: process.execPath,
1301
+ entryPath,
1302
+ socketPath,
1303
+ logDir,
1304
+ envPath: process.env.PATH,
525
1305
  });
526
1306
  }
527
1307
  async function defaultPromptInput(question) {
@@ -539,62 +1319,11 @@ async function defaultPromptInput(question) {
539
1319
  }
540
1320
  }
541
1321
  function defaultListDiscoveredAgents() {
542
- const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
543
- let entries;
544
- try {
545
- entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
546
- }
547
- catch {
548
- return [];
549
- }
550
- const discovered = [];
551
- for (const entry of entries) {
552
- if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
553
- continue;
554
- const agentName = entry.name.slice(0, -5);
555
- const configPath = path.join(bundlesRoot, entry.name, "agent.json");
556
- let enabled = true;
557
- try {
558
- const raw = fs.readFileSync(configPath, "utf-8");
559
- const parsed = JSON.parse(raw);
560
- if (typeof parsed.enabled === "boolean") {
561
- enabled = parsed.enabled;
562
- }
563
- }
564
- catch {
565
- continue;
566
- }
567
- if (enabled) {
568
- discovered.push(agentName);
569
- }
570
- }
571
- return discovered.sort((left, right) => left.localeCompare(right));
572
- }
573
- async function defaultLinkFriendIdentity(command) {
574
- const fp = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`, "friends");
575
- const friendStore = new store_file_1.FileFriendStore(fp);
576
- const current = await friendStore.get(command.friendId);
577
- if (!current) {
578
- return `friend not found: ${command.friendId}`;
579
- }
580
- const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
581
- if (alreadyLinked) {
582
- return `identity already linked: ${command.provider}:${command.externalId}`;
583
- }
584
- const now = new Date().toISOString();
585
- await friendStore.put(command.friendId, {
586
- ...current,
587
- externalIds: [
588
- ...current.externalIds,
589
- {
590
- provider: command.provider,
591
- externalId: command.externalId,
592
- linkedAt: now,
593
- },
594
- ],
595
- updatedAt: now,
1322
+ return (0, agent_discovery_1.listEnabledBundleAgents)({
1323
+ bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
1324
+ readdirSync: fs.readdirSync,
1325
+ readFileSync: fs.readFileSync,
596
1326
  });
597
- return `linked ${command.provider}:${command.externalId} to ${command.friendId}`;
598
1327
  }
599
1328
  function discoverExistingCredentials(secretsRoot) {
600
1329
  const found = [];
@@ -651,7 +1380,7 @@ function discoverExistingCredentials(secretsRoot) {
651
1380
  });
652
1381
  }
653
1382
  /* v8 ignore start -- integration: interactive terminal specialist session @preserve */
654
- async function defaultRunAdoptionSpecialist() {
1383
+ async function defaultRunSerpentGuide() {
655
1384
  const { runCliSession } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
656
1385
  const { patchRuntimeConfig } = await Promise.resolve().then(() => __importStar(require("../config")));
657
1386
  const { setAgentName, setAgentConfigOverride } = await Promise.resolve().then(() => __importStar(require("../identity")));
@@ -675,10 +1404,41 @@ async function defaultRunAdoptionSpecialist() {
675
1404
  // Default models per provider (used when entering new credentials)
676
1405
  const defaultModels = {
677
1406
  anthropic: "claude-opus-4-6",
678
- minimax: "MiniMax-Text-01",
1407
+ minimax: "MiniMax-M2.7",
679
1408
  "openai-codex": "gpt-5.4",
1409
+ "github-copilot": "claude-sonnet-4.6",
680
1410
  azure: "",
681
1411
  };
1412
+ // Scan environment variables for API keys
1413
+ const envKeys = [
1414
+ { provider: "anthropic", envVar: "ANTHROPIC_API_KEY", credKey: "setupToken" },
1415
+ { provider: "openai-codex", envVar: "OPENAI_API_KEY", credKey: "oauthAccessToken" },
1416
+ { provider: "azure", envVar: "AZURE_OPENAI_API_KEY", credKey: "apiKey" },
1417
+ { provider: "azure", envVar: "AZURE_OPENAI_KEY", credKey: "apiKey" },
1418
+ { provider: "minimax", envVar: "MINIMAX_API_KEY", credKey: "apiKey" },
1419
+ { provider: "github-copilot", envVar: "GITHUB_TOKEN", credKey: "token" },
1420
+ ];
1421
+ const envDiscovered = [];
1422
+ for (const { provider, envVar, credKey } of envKeys) {
1423
+ const value = process.env[envVar];
1424
+ if (value) {
1425
+ const envCred = { [credKey]: value };
1426
+ // For Azure, also check for endpoint and deployment env vars
1427
+ if (provider === "azure") {
1428
+ const endpoint = process.env.AZURE_OPENAI_ENDPOINT;
1429
+ const deployment = process.env.AZURE_OPENAI_DEPLOYMENT;
1430
+ if (endpoint)
1431
+ envCred.endpoint = endpoint;
1432
+ if (deployment)
1433
+ envCred.deployment = deployment;
1434
+ }
1435
+ const provCfg = { model: defaultModels[provider] };
1436
+ if (provider === "azure" && envCred.deployment)
1437
+ provCfg.deployment = envCred.deployment;
1438
+ envDiscovered.push({ provider, agentName: "env", credentials: envCred, providerConfig: provCfg, envVar });
1439
+ discovered.push({ provider, agentName: "env", credentials: envCred, providerConfig: provCfg });
1440
+ }
1441
+ }
682
1442
  if (discovered.length > 0) {
683
1443
  process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
684
1444
  process.stdout.write("i found existing API credentials:\n\n");
@@ -686,7 +1446,9 @@ async function defaultRunAdoptionSpecialist() {
686
1446
  for (let i = 0; i < unique.length; i++) {
687
1447
  const model = unique[i].providerConfig.model || unique[i].providerConfig.deployment || "";
688
1448
  const modelLabel = model ? `, ${model}` : "";
689
- process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (from ${unique[i].agentName})\n`);
1449
+ const envMatch = envDiscovered.find((e) => e.provider === unique[i].provider && unique[i].agentName === "env");
1450
+ const sourceLabel = envMatch ? `from env: $${envMatch.envVar}` : `from ${unique[i].agentName}`;
1451
+ process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (${sourceLabel})\n`);
690
1452
  }
691
1453
  process.stdout.write("\n");
692
1454
  const choice = await coldPrompt("use one of these? enter number, or 'new' for a different key: ");
@@ -697,7 +1459,7 @@ async function defaultRunAdoptionSpecialist() {
697
1459
  providerConfig = unique[idx].providerConfig;
698
1460
  }
699
1461
  else {
700
- const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
1462
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
701
1463
  if (!isAgentProvider(pRaw)) {
702
1464
  process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
703
1465
  coldRl.close();
@@ -721,7 +1483,7 @@ async function defaultRunAdoptionSpecialist() {
721
1483
  else {
722
1484
  process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
723
1485
  process.stdout.write("i need an API key to power our conversation.\n\n");
724
- const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
1486
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
725
1487
  if (!isAgentProvider(pRaw)) {
726
1488
  process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
727
1489
  coldRl.close();
@@ -743,17 +1505,17 @@ async function defaultRunAdoptionSpecialist() {
743
1505
  }
744
1506
  coldRl.close();
745
1507
  process.stdout.write("\n");
746
- // Phase 2: configure runtime for adoption specialist
747
- const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "AdoptionSpecialist.ouro");
1508
+ // Phase 2: configure runtime for serpent guide
1509
+ const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "SerpentGuide.ouro");
748
1510
  const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
749
1511
  const secretsRoot2 = path.join(os.homedir(), ".agentsecrets");
750
- // Suppress non-critical log noise during adoption (no secrets.json, etc.)
1512
+ // Suppress non-critical log noise during hatch (no secrets.json, etc.)
751
1513
  const { setRuntimeLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
752
1514
  const { createLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves")));
753
1515
  setRuntimeLogger(createLogger({ level: "error" }));
754
1516
  // Configure runtime: set agent identity + config override so runAgent
755
- // doesn't try to read from ~/AgentBundles/AdoptionSpecialist.ouro/
756
- setAgentName("AdoptionSpecialist");
1517
+ // doesn't try to read from ~/AgentBundles/SerpentGuide.ouro/
1518
+ setAgentName("SerpentGuide");
757
1519
  // Build specialist system prompt
758
1520
  const soulText = (0, specialist_orchestrator_1.loadSoulText)(bundleSourceDir);
759
1521
  const identitiesDir = path.join(bundleSourceDir, "psyche", "identities");
@@ -761,10 +1523,13 @@ async function defaultRunAdoptionSpecialist() {
761
1523
  // Load identity-specific spinner phrases (falls back to DEFAULT_AGENT_PHRASES)
762
1524
  const { loadIdentityPhrases } = await Promise.resolve().then(() => __importStar(require("./specialist-orchestrator")));
763
1525
  const phrases = loadIdentityPhrases(bundleSourceDir, identity.fileName);
1526
+ const resolvedModel = providerConfig.model || providerConfig.deployment || "";
764
1527
  setAgentConfigOverride({
765
- version: 1,
1528
+ version: 2,
766
1529
  enabled: true,
767
1530
  provider: providerRaw,
1531
+ humanFacing: { provider: providerRaw, model: resolvedModel },
1532
+ agentFacing: { provider: providerRaw, model: resolvedModel },
768
1533
  phrases,
769
1534
  });
770
1535
  patchRuntimeConfig({
@@ -776,6 +1541,7 @@ async function defaultRunAdoptionSpecialist() {
776
1541
  const systemPrompt = (0, specialist_prompt_1.buildSpecialistSystemPrompt)(soulText, identity.content, existingBundles, {
777
1542
  tempDir,
778
1543
  provider: providerRaw,
1544
+ model: providerConfig.model ?? "",
779
1545
  });
780
1546
  // Build specialist tools
781
1547
  const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
@@ -787,9 +1553,9 @@ async function defaultRunAdoptionSpecialist() {
787
1553
  secretsRoot: secretsRoot2,
788
1554
  animationWriter: (text) => process.stdout.write(text),
789
1555
  });
790
- // Run the adoption specialist session via runCliSession
1556
+ // Run the serpent guide session via runCliSession
791
1557
  const result = await runCliSession({
792
- agentName: "AdoptionSpecialist",
1558
+ agentName: "SerpentGuide",
793
1559
  tools: specialistTools,
794
1560
  execTool: specialistExecTool,
795
1561
  exitOnToolCall: "complete_adoption",
@@ -811,7 +1577,7 @@ async function defaultRunAdoptionSpecialist() {
811
1577
  return null;
812
1578
  }
813
1579
  catch (err) {
814
- process.stderr.write(`\nouro adoption error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
1580
+ process.stderr.write(`\nouro hatch error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
815
1581
  coldRl.close();
816
1582
  return null;
817
1583
  }
@@ -837,30 +1603,118 @@ async function defaultRunAdoptionSpecialist() {
837
1603
  }
838
1604
  }
839
1605
  /* v8 ignore stop */
840
- function createDefaultOuroCliDeps(socketPath = "/tmp/ouroboros-daemon.sock") {
1606
+ function createDefaultOuroCliDeps(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
841
1607
  return {
842
1608
  socketPath,
843
- sendCommand: defaultSendCommand,
1609
+ sendCommand: socket_client_1.sendDaemonCommand,
844
1610
  startDaemonProcess: defaultStartDaemonProcess,
845
1611
  writeStdout: defaultWriteStdout,
846
- checkSocketAlive: defaultCheckSocketAlive,
1612
+ checkSocketAlive: socket_client_1.checkDaemonSocketAlive,
847
1613
  cleanupStaleSocket: defaultCleanupStaleSocket,
848
1614
  fallbackPendingMessage: defaultFallbackPendingMessage,
849
- installSubagents: defaultInstallSubagents,
850
- linkFriendIdentity: defaultLinkFriendIdentity,
851
1615
  listDiscoveredAgents: defaultListDiscoveredAgents,
852
1616
  runHatchFlow: hatch_flow_1.runHatchFlow,
853
1617
  promptInput: defaultPromptInput,
854
- runAdoptionSpecialist: defaultRunAdoptionSpecialist,
1618
+ runSerpentGuide: defaultRunSerpentGuide,
1619
+ runAuthFlow: auth_flow_1.runRuntimeAuthFlow,
855
1620
  registerOuroBundleType: ouro_uti_1.registerOuroBundleUti,
856
1621
  installOuroCommand: ouro_path_installer_1.installOuroCommand,
1622
+ /* v8 ignore start -- self-healing: ensures active symlink matches running runtime version @preserve */
1623
+ ensureCurrentVersionInstalled: () => {
1624
+ const linkedVersion = (0, ouro_version_manager_1.getCurrentVersion)({});
1625
+ const version = (0, bundle_manifest_1.getPackageVersion)();
1626
+ if (linkedVersion === version)
1627
+ return;
1628
+ (0, ouro_version_manager_1.ensureLayout)({});
1629
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
1630
+ const versionEntry = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
1631
+ if (!fs.existsSync(versionEntry)) {
1632
+ (0, ouro_version_manager_1.installVersion)(version, {});
1633
+ }
1634
+ (0, ouro_version_manager_1.activateVersion)(version, {});
1635
+ },
1636
+ /* v8 ignore stop */
1637
+ /* v8 ignore start -- CLI version management defaults: integration code @preserve */
1638
+ checkForCliUpdate: async () => {
1639
+ const { checkForUpdate } = await Promise.resolve().then(() => __importStar(require("./update-checker")));
1640
+ return checkForUpdate((0, bundle_manifest_1.getPackageVersion)(), {
1641
+ fetchRegistryJson: async () => {
1642
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
1643
+ return res.json();
1644
+ },
1645
+ distTag: "alpha",
1646
+ });
1647
+ },
1648
+ installCliVersion: async (version) => { (0, ouro_version_manager_1.installVersion)(version, {}); },
1649
+ activateCliVersion: (version) => { (0, ouro_version_manager_1.activateVersion)(version, {}); },
1650
+ getCurrentCliVersion: () => (0, ouro_version_manager_1.getCurrentVersion)({}),
1651
+ getPreviousCliVersion: () => (0, ouro_version_manager_1.getPreviousVersion)({}),
1652
+ listCliVersions: () => (0, ouro_version_manager_1.listInstalledVersions)({}),
1653
+ reExecFromNewVersion: (reArgs) => {
1654
+ const entry = path.join((0, ouro_version_manager_1.getOuroCliHome)(), "CurrentVersion", "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
1655
+ require("child_process").execFileSync("node", [entry, ...reArgs], { stdio: "inherit" });
1656
+ process.exit(0);
1657
+ },
1658
+ /* v8 ignore stop */
1659
+ syncGlobalOuroBotWrapper: ouro_bot_global_installer_1.syncGlobalOuroBotWrapper,
1660
+ ensureSkillManagement: skill_management_installer_1.ensureSkillManagement,
1661
+ ensureDaemonBootPersistence: defaultEnsureDaemonBootPersistence,
1662
+ /* v8 ignore start -- dev-mode defaults: tests inject mocks for mode detection and binary resolution @preserve */
1663
+ detectMode: () => (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)()),
1664
+ getInstalledBinaryPath: () => {
1665
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
1666
+ const binaryPath = path.join(cliHome, "bin", "ouro");
1667
+ return fs.existsSync(binaryPath) ? binaryPath : null;
1668
+ },
1669
+ execInstalledBinary: (binaryPath, binArgs) => {
1670
+ const { execFileSync } = require("child_process");
1671
+ execFileSync(binaryPath, binArgs, { stdio: "inherit" });
1672
+ process.exit(0);
1673
+ },
1674
+ /* v8 ignore stop */
857
1675
  /* v8 ignore next 3 -- integration: launches interactive CLI session @preserve */
858
1676
  startChat: async (agentName) => {
859
1677
  const { main } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
860
1678
  await main(agentName);
861
1679
  },
1680
+ scanSessions: async () => {
1681
+ const agentName = (0, identity_1.getAgentName)();
1682
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
1683
+ return (0, session_activity_1.listSessionActivity)({
1684
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
1685
+ friendsDir: path.join(agentRoot, "friends"),
1686
+ agentName,
1687
+ }).map((entry) => ({
1688
+ friendId: entry.friendId,
1689
+ friendName: entry.friendName,
1690
+ channel: entry.channel,
1691
+ lastActivity: entry.lastActivityAt,
1692
+ }));
1693
+ },
862
1694
  };
863
1695
  }
1696
+ function formatMcpResponse(command, response) {
1697
+ if (command.kind === "mcp.list") {
1698
+ const allTools = response.data;
1699
+ if (!allTools || allTools.length === 0) {
1700
+ return response.message ?? "no tools available from connected MCP servers";
1701
+ }
1702
+ const lines = [];
1703
+ for (const entry of allTools) {
1704
+ lines.push(`[${entry.server}]`);
1705
+ for (const tool of entry.tools) {
1706
+ lines.push(` ${tool.name}: ${tool.description}`);
1707
+ }
1708
+ }
1709
+ return lines.join("\n");
1710
+ }
1711
+ // mcp.call
1712
+ const result = response.data;
1713
+ if (!result) {
1714
+ return response.message ?? "no result";
1715
+ }
1716
+ return result.content.map((c) => c.text).join("\n");
1717
+ }
864
1718
  function toDaemonCommand(command) {
865
1719
  return command;
866
1720
  }
@@ -868,28 +1722,17 @@ async function resolveHatchInput(command, deps) {
868
1722
  const prompt = deps.promptInput;
869
1723
  const agentName = command.agentName ?? (prompt ? await prompt("Hatchling name: ") : "");
870
1724
  const humanName = command.humanName ?? (prompt ? await prompt("Your name: ") : os.userInfo().username);
871
- const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex): ") : "");
1725
+ const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex|github-copilot): ") : "");
872
1726
  if (!agentName || !humanName || !isAgentProvider(providerRaw)) {
873
1727
  throw new Error(`Usage\n${usage()}`);
874
1728
  }
875
- const credentials = { ...(command.credentials ?? {}) };
876
- if (providerRaw === "anthropic" && !credentials.setupToken && prompt) {
877
- credentials.setupToken = await prompt("Anthropic setup-token: ");
878
- }
879
- if (providerRaw === "openai-codex" && !credentials.oauthAccessToken && prompt) {
880
- credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
881
- }
882
- if (providerRaw === "minimax" && !credentials.apiKey && prompt) {
883
- credentials.apiKey = await prompt("MiniMax API key: ");
884
- }
885
- if (providerRaw === "azure") {
886
- if (!credentials.apiKey && prompt)
887
- credentials.apiKey = await prompt("Azure API key: ");
888
- if (!credentials.endpoint && prompt)
889
- credentials.endpoint = await prompt("Azure endpoint: ");
890
- if (!credentials.deployment && prompt)
891
- credentials.deployment = await prompt("Azure deployment: ");
892
- }
1729
+ const credentials = await (0, auth_flow_1.resolveHatchCredentials)({
1730
+ agentName,
1731
+ provider: providerRaw,
1732
+ credentials: command.credentials,
1733
+ promptInput: prompt,
1734
+ runAuthFlow: deps.runAuthFlow,
1735
+ });
893
1736
  return {
894
1737
  agentName,
895
1738
  humanName,
@@ -919,7 +1762,11 @@ async function performSystemSetup(deps) {
919
1762
  // Install ouro command to PATH (non-blocking)
920
1763
  if (deps.installOuroCommand) {
921
1764
  try {
922
- deps.installOuroCommand();
1765
+ const installResult = deps.installOuroCommand();
1766
+ /* v8 ignore next -- old-launcher repair hint: fires when stale ~/.local/bin/ouro is fixed @preserve */
1767
+ if (installResult.repairedOldLauncher) {
1768
+ deps.writeStdout("repaired stale ouro launcher at ~/.local/bin/ouro");
1769
+ }
923
1770
  }
924
1771
  catch (error) {
925
1772
  (0, runtime_1.emitNervesEvent)({
@@ -931,28 +1778,391 @@ async function performSystemSetup(deps) {
931
1778
  });
932
1779
  }
933
1780
  }
934
- // Install subagents (claude/codex skills)
935
- try {
936
- await deps.installSubagents();
937
- }
938
- catch (error) {
939
- (0, runtime_1.emitNervesEvent)({
940
- level: "warn",
941
- component: "daemon",
942
- event: "daemon.subagent_install_error",
943
- message: "subagent auto-install failed",
944
- meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
945
- });
1781
+ // Self-healing: ensure current version is installed in ~/.ouro-cli/ layout.
1782
+ // Handles the case where the wrapper exists but CurrentVersion is missing
1783
+ // (e.g., first run after migration from old npx wrapper).
1784
+ if (deps.ensureCurrentVersionInstalled) {
1785
+ try {
1786
+ deps.ensureCurrentVersionInstalled();
1787
+ }
1788
+ catch (error) {
1789
+ (0, runtime_1.emitNervesEvent)({
1790
+ level: "warn",
1791
+ component: "daemon",
1792
+ event: "daemon.system_setup_version_install_error",
1793
+ message: "failed to ensure current version installed",
1794
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive @preserve */ String(error) },
1795
+ });
1796
+ }
1797
+ }
1798
+ if (deps.syncGlobalOuroBotWrapper) {
1799
+ try {
1800
+ await Promise.resolve(deps.syncGlobalOuroBotWrapper());
1801
+ }
1802
+ catch (error) {
1803
+ (0, runtime_1.emitNervesEvent)({
1804
+ level: "warn",
1805
+ component: "daemon",
1806
+ event: "daemon.system_setup_ouro_bot_wrapper_error",
1807
+ message: "failed to sync global ouro.bot wrapper",
1808
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1809
+ });
1810
+ }
1811
+ }
1812
+ // Ensure skill-management skill is available
1813
+ if (deps.ensureSkillManagement) {
1814
+ try {
1815
+ await deps.ensureSkillManagement();
1816
+ /* v8 ignore start -- defensive: ensureSkillManagement handles its own errors internally @preserve */
1817
+ }
1818
+ catch (error) {
1819
+ (0, runtime_1.emitNervesEvent)({
1820
+ level: "warn",
1821
+ component: "daemon",
1822
+ event: "daemon.system_setup_skill_management_error",
1823
+ message: "failed to ensure skill-management skill",
1824
+ meta: { error: error instanceof Error ? error.message : String(error) },
1825
+ });
1826
+ }
1827
+ /* v8 ignore stop */
946
1828
  }
947
1829
  // Register .ouro bundle type (UTI on macOS)
948
1830
  await registerOuroBundleTypeNonBlocking(deps);
949
1831
  }
1832
+ function executeTaskCommand(command, taskMod) {
1833
+ if (command.kind === "task.board") {
1834
+ if (command.status) {
1835
+ const lines = taskMod.boardStatus(command.status);
1836
+ return lines.length > 0 ? lines.join("\n") : "no tasks in that status";
1837
+ }
1838
+ const board = taskMod.getBoard();
1839
+ return board.full || board.compact || "no tasks found";
1840
+ }
1841
+ if (command.kind === "task.create") {
1842
+ try {
1843
+ const created = taskMod.createTask({
1844
+ title: command.title,
1845
+ type: command.type ?? "one-shot",
1846
+ category: "general",
1847
+ body: "",
1848
+ });
1849
+ return `created: ${created}`;
1850
+ }
1851
+ catch (error) {
1852
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1853
+ }
1854
+ }
1855
+ if (command.kind === "task.update") {
1856
+ const result = taskMod.updateStatus(command.id, command.status);
1857
+ if (!result.ok) {
1858
+ return `error: ${result.reason ?? "status update failed"}`;
1859
+ }
1860
+ const archivedSuffix = result.archived && result.archived.length > 0
1861
+ ? ` | archived: ${result.archived.join(", ")}`
1862
+ : "";
1863
+ return `updated: ${command.id} -> ${result.to}${archivedSuffix}`;
1864
+ }
1865
+ if (command.kind === "task.show") {
1866
+ const task = taskMod.getTask(command.id);
1867
+ if (!task)
1868
+ return `task not found: ${command.id}`;
1869
+ return [
1870
+ `title: ${task.title}`,
1871
+ `type: ${task.type}`,
1872
+ `status: ${task.status}`,
1873
+ `category: ${task.category}`,
1874
+ `created: ${task.created}`,
1875
+ `updated: ${task.updated}`,
1876
+ `path: ${task.path}`,
1877
+ task.body ? `\n${task.body}` : "",
1878
+ ].filter(Boolean).join("\n");
1879
+ }
1880
+ if (command.kind === "task.actionable") {
1881
+ const lines = taskMod.boardAction();
1882
+ return lines.length > 0 ? lines.join("\n") : "no action required";
1883
+ }
1884
+ if (command.kind === "task.deps") {
1885
+ const lines = taskMod.boardDeps();
1886
+ return lines.length > 0 ? lines.join("\n") : "no unresolved dependencies";
1887
+ }
1888
+ if (command.kind === "task.fix") {
1889
+ try {
1890
+ const fixOptions = {
1891
+ mode: command.mode,
1892
+ ...(command.issueId ? { issueId: command.issueId } : {}),
1893
+ ...(command.option !== undefined ? { option: command.option } : {}),
1894
+ };
1895
+ const result = taskMod.fix(fixOptions);
1896
+ if (command.mode === "dry-run") {
1897
+ if (result.remaining.length === 0) {
1898
+ return `task health: clean`;
1899
+ }
1900
+ const safeIssues = result.remaining.filter((i) => i.confidence === "safe");
1901
+ const reviewIssues = result.remaining.filter((i) => i.confidence === "needs_review");
1902
+ const lines = [`${result.remaining.length} issues found`];
1903
+ if (safeIssues.length > 0) {
1904
+ lines.push("", `safe fixes (${safeIssues.length}):`);
1905
+ for (const issue of safeIssues) {
1906
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1907
+ }
1908
+ }
1909
+ if (reviewIssues.length > 0) {
1910
+ lines.push("", `needs review (${reviewIssues.length}):`);
1911
+ for (const issue of reviewIssues) {
1912
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1913
+ }
1914
+ }
1915
+ lines.push("", `task health: ${result.health}`);
1916
+ return lines.join("\n");
1917
+ }
1918
+ // safe, single, or --all modes: show what was done
1919
+ const lines = [];
1920
+ if (result.applied.length > 0) {
1921
+ lines.push(`${result.applied.length} applied:`);
1922
+ for (const issue of result.applied) {
1923
+ lines.push(` ${issue.code}:${issue.target}`);
1924
+ }
1925
+ }
1926
+ if (result.remaining.length > 0) {
1927
+ lines.push(`${result.remaining.length} remaining:`);
1928
+ for (const issue of result.remaining) {
1929
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1930
+ }
1931
+ }
1932
+ if (result.applied.length === 0 && result.remaining.length === 0) {
1933
+ lines.push("no issues");
1934
+ }
1935
+ lines.push(`task health: ${result.health}`);
1936
+ return lines.join("\n");
1937
+ }
1938
+ catch (error) {
1939
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1940
+ }
1941
+ }
1942
+ // command.kind === "task.sessions"
1943
+ const lines = taskMod.boardSessions();
1944
+ return lines.length > 0 ? lines.join("\n") : "no active sessions";
1945
+ }
1946
+ const TRUST_RANK = { family: 4, friend: 3, acquaintance: 2, stranger: 1 };
1947
+ /* v8 ignore start -- defensive: ?? fallbacks are unreachable when inputs are valid TrustLevel values @preserve */
1948
+ function higherTrust(a, b) {
1949
+ const rankA = TRUST_RANK[a ?? "stranger"] ?? 1;
1950
+ const rankB = TRUST_RANK[b ?? "stranger"] ?? 1;
1951
+ return rankA >= rankB ? (a ?? "stranger") : (b ?? "stranger");
1952
+ }
1953
+ /* v8 ignore stop */
1954
+ async function executeFriendCommand(command, store) {
1955
+ if (command.kind === "friend.list") {
1956
+ const listAll = store.listAll;
1957
+ if (!listAll)
1958
+ return "friend store does not support listing";
1959
+ const friends = await listAll.call(store);
1960
+ if (friends.length === 0)
1961
+ return "no friends found";
1962
+ const lines = friends.map((f) => {
1963
+ const trust = f.trustLevel ?? "unknown";
1964
+ return `${f.id} ${f.name} ${trust}`;
1965
+ });
1966
+ return lines.join("\n");
1967
+ }
1968
+ if (command.kind === "friend.show") {
1969
+ const record = await store.get(command.friendId);
1970
+ if (!record)
1971
+ return `friend not found: ${command.friendId}`;
1972
+ return JSON.stringify(record, null, 2);
1973
+ }
1974
+ if (command.kind === "friend.create") {
1975
+ const now = new Date().toISOString();
1976
+ const id = (0, crypto_1.randomUUID)();
1977
+ const trustLevel = (command.trustLevel ?? "acquaintance");
1978
+ await store.put(id, {
1979
+ id,
1980
+ name: command.name,
1981
+ trustLevel,
1982
+ externalIds: [],
1983
+ tenantMemberships: [],
1984
+ toolPreferences: {},
1985
+ notes: {},
1986
+ totalTokens: 0,
1987
+ createdAt: now,
1988
+ updatedAt: now,
1989
+ schemaVersion: 1,
1990
+ });
1991
+ return `created: ${id} (${command.name}, ${trustLevel})`;
1992
+ }
1993
+ if (command.kind === "friend.update") {
1994
+ const current = await store.get(command.friendId);
1995
+ if (!current)
1996
+ return `friend not found: ${command.friendId}`;
1997
+ const now = new Date().toISOString();
1998
+ await store.put(command.friendId, {
1999
+ ...current,
2000
+ trustLevel: command.trustLevel,
2001
+ role: command.trustLevel,
2002
+ updatedAt: now,
2003
+ });
2004
+ return `updated: ${command.friendId} → trust=${command.trustLevel}`;
2005
+ }
2006
+ if (command.kind === "friend.link") {
2007
+ const current = await store.get(command.friendId);
2008
+ if (!current)
2009
+ return `friend not found: ${command.friendId}`;
2010
+ const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
2011
+ if (alreadyLinked)
2012
+ return `identity already linked: ${command.provider}:${command.externalId}`;
2013
+ const now = new Date().toISOString();
2014
+ const newExternalIds = [
2015
+ ...current.externalIds,
2016
+ { provider: command.provider, externalId: command.externalId, linkedAt: now },
2017
+ ];
2018
+ // Orphan cleanup: check if another friend has this externalId
2019
+ const orphan = await store.findByExternalId(command.provider, command.externalId);
2020
+ let mergeMessage = "";
2021
+ let mergedNotes = { ...current.notes };
2022
+ let mergedTrust = current.trustLevel;
2023
+ let orphanExternalIds = [];
2024
+ if (orphan && orphan.id !== command.friendId) {
2025
+ // Merge orphan's notes (target's notes take priority)
2026
+ mergedNotes = { ...orphan.notes, ...current.notes };
2027
+ // Keep higher trust level
2028
+ mergedTrust = higherTrust(current.trustLevel, orphan.trustLevel);
2029
+ // Collect orphan's other externalIds (excluding the one being linked)
2030
+ orphanExternalIds = orphan.externalIds.filter((ext) => !(ext.provider === command.provider && ext.externalId === command.externalId));
2031
+ await store.delete(orphan.id);
2032
+ mergeMessage = ` (merged orphan ${orphan.id})`;
2033
+ }
2034
+ await store.put(command.friendId, {
2035
+ ...current,
2036
+ externalIds: [...newExternalIds, ...orphanExternalIds],
2037
+ notes: mergedNotes,
2038
+ trustLevel: mergedTrust,
2039
+ updatedAt: now,
2040
+ });
2041
+ return `linked ${command.provider}:${command.externalId} to ${command.friendId}${mergeMessage}`;
2042
+ }
2043
+ // command.kind === "friend.unlink"
2044
+ const current = await store.get(command.friendId);
2045
+ if (!current)
2046
+ return `friend not found: ${command.friendId}`;
2047
+ const idx = current.externalIds.findIndex((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
2048
+ if (idx === -1)
2049
+ return `identity not linked: ${command.provider}:${command.externalId}`;
2050
+ const now = new Date().toISOString();
2051
+ const filtered = current.externalIds.filter((_, i) => i !== idx);
2052
+ await store.put(command.friendId, { ...current, externalIds: filtered, updatedAt: now });
2053
+ return `unlinked ${command.provider}:${command.externalId} from ${command.friendId}`;
2054
+ }
2055
+ function executeReminderCommand(command, taskMod) {
2056
+ try {
2057
+ const created = taskMod.createTask({
2058
+ title: command.title,
2059
+ type: command.cadence ? "ongoing" : "one-shot",
2060
+ category: command.category ?? "reminder",
2061
+ body: command.body,
2062
+ scheduledAt: command.scheduledAt,
2063
+ cadence: command.cadence,
2064
+ requester: command.requester,
2065
+ });
2066
+ return `created: ${created}`;
2067
+ }
2068
+ catch (error) {
2069
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
2070
+ }
2071
+ }
2072
+ /* v8 ignore start -- repo resolution for ouro dev: repoPath branch tested via daemon-cli-dev; clone requires real git/npm @preserve */
2073
+ function getDevConfigPath() {
2074
+ return path.join((0, ouro_version_manager_1.getOuroCliHome)(), "dev-config.json");
2075
+ }
2076
+ function readPersistedDevPath() {
2077
+ try {
2078
+ const data = JSON.parse(fs.readFileSync(getDevConfigPath(), "utf-8"));
2079
+ return typeof data.repoPath === "string" ? data.repoPath : null;
2080
+ }
2081
+ catch {
2082
+ return null;
2083
+ }
2084
+ }
2085
+ function persistDevPath(repoPath) {
2086
+ try {
2087
+ fs.mkdirSync(path.dirname(getDevConfigPath()), { recursive: true });
2088
+ fs.writeFileSync(getDevConfigPath(), JSON.stringify({ repoPath }, null, 2));
2089
+ }
2090
+ catch { /* best effort */ }
2091
+ }
2092
+ function resolveDevRepoCwd(command, checkExists, deps) {
2093
+ // 1. Explicit --repo-path: use it and persist for next time
2094
+ if (command.repoPath) {
2095
+ const resolved = path.resolve(command.repoPath);
2096
+ persistDevPath(resolved);
2097
+ return resolved;
2098
+ }
2099
+ // 2. Clone request
2100
+ if (command.clone)
2101
+ return resolveClonePath(command, checkExists, deps);
2102
+ // 3. If test/internal deps provide getRepoCwd, use it directly
2103
+ if (deps.getRepoCwd) {
2104
+ return deps.getRepoCwd();
2105
+ }
2106
+ // 4. Check CWD — if we're inside a harness repo, use it
2107
+ const cwd = process.cwd();
2108
+ if (checkExists(path.join(cwd, ".git")) && checkExists(path.join(cwd, "src", "heart", "daemon"))) {
2109
+ persistDevPath(cwd);
2110
+ return cwd;
2111
+ }
2112
+ // 5. Read persisted path from last --repo-path
2113
+ const persisted = readPersistedDevPath();
2114
+ if (persisted && checkExists(path.join(persisted, ".git"))) {
2115
+ deps.writeStdout(`using remembered dev path: ${persisted}`);
2116
+ return persisted;
2117
+ }
2118
+ // 6. Fall back to getRepoRoot (works when running from installed binary → resolves to npm package)
2119
+ return (0, identity_1.getRepoRoot)();
2120
+ }
2121
+ /* v8 ignore stop */
2122
+ /* v8 ignore start -- clone/build: requires real git clone + npm install on disk @preserve */
2123
+ function resolveClonePath(command, checkExists, deps) {
2124
+ const cloneTarget = command.clonePath
2125
+ ? path.resolve(command.clonePath)
2126
+ : path.join(os.homedir(), "Projects", "ouroboros");
2127
+ if (!checkExists(path.join(cloneTarget, ".git"))) {
2128
+ deps.writeStdout(`cloning ouroboros to ${cloneTarget}...`);
2129
+ try {
2130
+ (0, child_process_1.execSync)(`git clone ${identity_1.HARNESS_CANONICAL_REPO_URL} "${cloneTarget}"`, { stdio: "inherit" });
2131
+ }
2132
+ catch {
2133
+ throw new Error(`clone failed. check your network and try again, or clone manually and use --repo-path.`);
2134
+ }
2135
+ }
2136
+ else {
2137
+ deps.writeStdout(`repo already exists at ${cloneTarget}, pulling latest...`);
2138
+ try {
2139
+ (0, child_process_1.execSync)("git pull --ff-only", { cwd: cloneTarget, stdio: "inherit" });
2140
+ }
2141
+ catch {
2142
+ deps.writeStdout("pull failed (may have local changes). continuing with existing code.");
2143
+ }
2144
+ }
2145
+ deps.writeStdout("building...");
2146
+ try {
2147
+ (0, child_process_1.execSync)("npm install && npm run build", { cwd: cloneTarget, stdio: "inherit" });
2148
+ }
2149
+ catch {
2150
+ throw new Error(`build failed in ${cloneTarget}. check the output above.`);
2151
+ }
2152
+ return cloneTarget;
2153
+ }
2154
+ /* v8 ignore stop */
950
2155
  async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
951
- if (args.includes("--help") || args.includes("-h")) {
2156
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
952
2157
  const text = usage();
953
2158
  deps.writeStdout(text);
954
2159
  return text;
955
2160
  }
2161
+ if (args.length === 1 && (args[0] === "-v" || args[0] === "--version")) {
2162
+ const text = formatVersionOutput();
2163
+ deps.writeStdout(text);
2164
+ return text;
2165
+ }
956
2166
  let command;
957
2167
  try {
958
2168
  command = parseOuroCommand(args);
@@ -970,10 +2180,10 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
970
2180
  }
971
2181
  if (args.length === 0) {
972
2182
  const discovered = await Promise.resolve(deps.listDiscoveredAgents ? deps.listDiscoveredAgents() : defaultListDiscoveredAgents());
973
- if (discovered.length === 0 && deps.runAdoptionSpecialist) {
2183
+ if (discovered.length === 0 && deps.runSerpentGuide) {
974
2184
  // System setup first — ouro command, subagents, UTI — before the interactive specialist
975
2185
  await performSystemSetup(deps);
976
- const hatchlingName = await deps.runAdoptionSpecialist();
2186
+ const hatchlingName = await deps.runSerpentGuide();
977
2187
  if (!hatchlingName) {
978
2188
  return "";
979
2189
  }
@@ -1023,28 +2233,1068 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
1023
2233
  meta: { kind: command.kind },
1024
2234
  });
1025
2235
  if (command.kind === "daemon.up") {
2236
+ // ── dev mode cleanup: delete dev-config.json so the wrapper stops dispatching to dev repo ──
2237
+ /* v8 ignore start -- dev-config cleanup: requires real filesystem state @preserve */
2238
+ try {
2239
+ const devConfigPath = getDevConfigPath();
2240
+ if (fs.existsSync(devConfigPath)) {
2241
+ fs.unlinkSync(devConfigPath);
2242
+ }
2243
+ }
2244
+ catch { /* best effort */ }
2245
+ /* v8 ignore stop */
2246
+ // ── dev mode delegation: ouro up from a dev repo delegates to installed binary ──
2247
+ // Only runs when detectMode is explicitly injected (via createDefaultOuroCliDeps or tests)
2248
+ if (deps.detectMode) {
2249
+ const runtimeMode = deps.detectMode();
2250
+ if (runtimeMode === "dev") {
2251
+ /* v8 ignore next -- defensive: getInstalledBinaryPath always injected in tests @preserve */
2252
+ const installedBinary = deps.getInstalledBinaryPath ? deps.getInstalledBinaryPath() : null;
2253
+ if (installedBinary) {
2254
+ deps.writeStdout("delegating to installed ouro...");
2255
+ /* v8 ignore next 3 -- defensive: execInstalledBinary always injected; missing branch unreachable @preserve */
2256
+ if (deps.execInstalledBinary) {
2257
+ deps.execInstalledBinary(installedBinary, args);
2258
+ }
2259
+ /* v8 ignore next 2 -- unreachable after exec replaces process @preserve */
2260
+ return "";
2261
+ }
2262
+ const message = "no installed version found. run: npx @ouro.bot/cli@alpha";
2263
+ deps.writeStdout(message);
2264
+ return message;
2265
+ }
2266
+ }
2267
+ const linkedVersionBeforeUp = deps.getCurrentCliVersion?.() ?? null;
2268
+ // ── versioned CLI update check ──
2269
+ if (deps.checkForCliUpdate) {
2270
+ let pendingReExec = false;
2271
+ try {
2272
+ const updateResult = await deps.checkForCliUpdate();
2273
+ if (updateResult.available && updateResult.latestVersion) {
2274
+ /* v8 ignore next -- fallback: getCurrentCliVersion always injected in tests @preserve */
2275
+ const currentVersion = linkedVersionBeforeUp ?? "unknown";
2276
+ await deps.installCliVersion(updateResult.latestVersion);
2277
+ deps.activateCliVersion(updateResult.latestVersion);
2278
+ deps.writeStdout(`ouro updated to ${updateResult.latestVersion} (was ${currentVersion})`);
2279
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(currentVersion, updateResult.latestVersion);
2280
+ /* v8 ignore next -- buildChangelogCommand is non-null when an actual newer version is installed @preserve */
2281
+ if (changelogCommand) {
2282
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2283
+ }
2284
+ pendingReExec = true;
2285
+ }
2286
+ /* v8 ignore start -- update check error: tested via daemon-cli-update-flow.test.ts @preserve */
2287
+ }
2288
+ catch (error) {
2289
+ (0, runtime_1.emitNervesEvent)({
2290
+ level: "warn",
2291
+ component: "daemon",
2292
+ event: "daemon.cli_update_check_error",
2293
+ message: "CLI update check failed",
2294
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
2295
+ });
2296
+ }
2297
+ /* v8 ignore stop */
2298
+ if (pendingReExec) {
2299
+ deps.reExecFromNewVersion(args);
2300
+ }
2301
+ }
1026
2302
  await performSystemSetup(deps);
2303
+ const linkedVersionAfterSetup = deps.getCurrentCliVersion?.() ?? null;
2304
+ const runtimeVersion = (0, bundle_manifest_1.getPackageVersion)();
2305
+ if (linkedVersionBeforeUp && linkedVersionBeforeUp !== runtimeVersion && linkedVersionAfterSetup === runtimeVersion) {
2306
+ deps.writeStdout(`ouro updated to ${runtimeVersion} (was ${linkedVersionBeforeUp})`);
2307
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(linkedVersionBeforeUp, runtimeVersion);
2308
+ if (changelogCommand) {
2309
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2310
+ }
2311
+ }
2312
+ // Run update hooks before starting daemon so user sees the output
2313
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
2314
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
2315
+ const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
2316
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
2317
+ // Snapshot the previous CLI version from the first bundle-meta before
2318
+ // hooks overwrite it. This detects when npx downloaded a newer CLI.
2319
+ const previousCliVersion = readFirstBundleMetaVersion(bundlesRoot);
2320
+ const updateSummary = await (0, update_hooks_1.applyPendingUpdates)(bundlesRoot, currentVersion);
2321
+ // Notify about CLI binary update (npx downloaded a new version).
2322
+ // Skip when the symlink already points to the running version — that
2323
+ // means path 1 (checkForCliUpdate + reExecFromNewVersion) already
2324
+ // printed the update message before re-exec.
2325
+ /* v8 ignore start -- CLI update detection: tested via daemon-cli-version-detect.test.ts @preserve */
2326
+ if (previousCliVersion && previousCliVersion !== currentVersion && linkedVersionBeforeUp !== currentVersion) {
2327
+ deps.writeStdout(`ouro updated to ${currentVersion} (was ${previousCliVersion})`);
2328
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(previousCliVersion, currentVersion);
2329
+ /* v8 ignore next -- buildChangelogCommand is non-null when previous/current runtime versions differ @preserve */
2330
+ if (changelogCommand) {
2331
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2332
+ }
2333
+ }
2334
+ /* v8 ignore stop */
2335
+ if (updateSummary.updated.length > 0) {
2336
+ const agents = updateSummary.updated.map((e) => e.agent);
2337
+ const from = updateSummary.updated[0].from;
2338
+ const to = updateSummary.updated[0].to;
2339
+ const fromStr = from ? ` (was ${from})` : "";
2340
+ const count = agents.length;
2341
+ deps.writeStdout(`updated ${count} agent${count === 1 ? "" : "s"} to runtime ${to}${fromStr}`);
2342
+ }
1027
2343
  const daemonResult = await ensureDaemonRunning(deps);
1028
2344
  deps.writeStdout(daemonResult.message);
2345
+ // Persist boot startup AFTER daemon is running — bootstrap is safe now
2346
+ // because the daemon socket exists, so launchd's KeepAlive registers
2347
+ // for crash recovery without starting a competing process.
2348
+ if (deps.ensureDaemonBootPersistence) {
2349
+ try {
2350
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
2351
+ }
2352
+ catch (error) {
2353
+ (0, runtime_1.emitNervesEvent)({
2354
+ level: "warn",
2355
+ component: "daemon",
2356
+ event: "daemon.system_setup_launchd_error",
2357
+ message: "failed to persist daemon boot startup",
2358
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
2359
+ });
2360
+ }
2361
+ }
1029
2362
  return daemonResult.message;
1030
2363
  }
2364
+ if (command.kind === "daemon.dev") {
2365
+ /* v8 ignore next -- defensive: existsSync always injected in tests @preserve */
2366
+ const checkExists = deps.existsSync ?? fs.existsSync;
2367
+ /* v8 ignore next -- repo resolution dispatched to v8-ignored helper @preserve */
2368
+ let repoCwd = resolveDevRepoCwd(command, checkExists, deps);
2369
+ let entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2370
+ if (!checkExists(entryPath) || !checkExists(path.join(repoCwd, ".git"))) {
2371
+ if (command.repoPath) {
2372
+ // Explicit --repo-path didn't have a valid repo — error
2373
+ const message = `no harness repo found at ${repoCwd}. run npm run build first.`;
2374
+ deps.writeStdout(message);
2375
+ return message;
2376
+ }
2377
+ /* v8 ignore start -- auto-clone: interactive prompt + existing repo discovery + real git/npm @preserve */
2378
+ const defaultClonePath = path.join(os.homedir(), "Projects", "ouroboros");
2379
+ if (checkExists(path.join(defaultClonePath, ".git"))) {
2380
+ deps.writeStdout(`found existing repo at ${defaultClonePath}`);
2381
+ try {
2382
+ repoCwd = resolveClonePath({ clonePath: defaultClonePath }, checkExists, deps);
2383
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2384
+ }
2385
+ catch (err) {
2386
+ const message = err instanceof Error ? err.message : String(err);
2387
+ deps.writeStdout(message);
2388
+ return message;
2389
+ }
2390
+ }
2391
+ else if (deps.promptInput) {
2392
+ deps.writeStdout("no harness repo found.");
2393
+ const answer = await deps.promptInput(`already have a checkout? enter its path, or press enter to clone to ${defaultClonePath}: `);
2394
+ const cloneTarget = answer.trim() || defaultClonePath;
2395
+ try {
2396
+ repoCwd = resolveClonePath({ clonePath: cloneTarget }, checkExists, deps);
2397
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2398
+ }
2399
+ catch (err) {
2400
+ const message = err instanceof Error ? err.message : String(err);
2401
+ deps.writeStdout(message);
2402
+ return message;
2403
+ }
2404
+ }
2405
+ else {
2406
+ const message = `no harness repo found. run: ouro dev --repo-path /path/to/ouroboros`;
2407
+ deps.writeStdout(message);
2408
+ return message;
2409
+ }
2410
+ /* v8 ignore stop */
2411
+ }
2412
+ // Auto-build: always rebuild in dev mode so dist/ matches source
2413
+ /* v8 ignore start -- dev auto-build: execSync in repo cwd, tested manually @preserve */
2414
+ deps.writeStdout(`building from ${repoCwd}...`);
2415
+ try {
2416
+ (0, child_process_1.execSync)("npm run build", { cwd: repoCwd, stdio: "inherit" });
2417
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2418
+ }
2419
+ catch {
2420
+ const message = `build failed in ${repoCwd}. fix compilation errors and retry.`;
2421
+ deps.writeStdout(message);
2422
+ return message;
2423
+ }
2424
+ /* v8 ignore stop */
2425
+ /* v8 ignore start -- defensive: ensureDaemonBootPersistence always injected in tests @preserve */
2426
+ if (deps.ensureDaemonBootPersistence) {
2427
+ try {
2428
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
2429
+ /* v8 ignore next -- defensive: boot persistence error should not block dev mode @preserve */
2430
+ }
2431
+ catch (error) {
2432
+ (0, runtime_1.emitNervesEvent)({
2433
+ level: "warn",
2434
+ component: "daemon",
2435
+ event: "daemon.dev_boot_persistence_error",
2436
+ message: "failed to persist daemon boot startup in dev mode",
2437
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
2438
+ });
2439
+ }
2440
+ /* v8 ignore stop */
2441
+ }
2442
+ // Disable launchd KeepAlive before killing — prevents the installed daemon from respawning
2443
+ /* v8 ignore start -- dev launchd disable: requires real launchctl + plist on disk @preserve */
2444
+ const launchdDevDeps = {
2445
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd); },
2446
+ existsFile: (p) => fs.existsSync(p),
2447
+ removeFile: (p) => { try {
2448
+ fs.unlinkSync(p);
2449
+ }
2450
+ catch { /* best effort */ } },
2451
+ homeDir: os.homedir(),
2452
+ userUid: process.getuid?.() ?? 0,
2453
+ };
2454
+ if ((0, launchd_1.isDaemonInstalled)(launchdDevDeps)) {
2455
+ (0, launchd_1.uninstallLaunchAgent)(launchdDevDeps);
2456
+ deps.writeStdout("disabled launchd auto-restart for dev mode");
2457
+ }
2458
+ /* v8 ignore stop */
2459
+ // Always force-restart in dev mode — you rebuilt, you want this code running
2460
+ /* v8 ignore start -- dev force-restart: socket alive/stop/spawn tested via integration; tests inject mocks @preserve */
2461
+ const alive = await deps.checkSocketAlive(deps.socketPath);
2462
+ if (alive) {
2463
+ try {
2464
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
2465
+ }
2466
+ catch { /* already stopping */ }
2467
+ }
2468
+ deps.cleanupStaleSocket(deps.socketPath);
2469
+ const devEntry = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2470
+ const startDevDaemon = deps.startDaemonProcess === defaultStartDaemonProcess
2471
+ ? async (sp) => {
2472
+ const child = (0, child_process_1.spawn)("node", [devEntry, "--socket", sp], { detached: true, stdio: "ignore" });
2473
+ child.unref();
2474
+ return { pid: child.pid ?? null };
2475
+ }
2476
+ : deps.startDaemonProcess;
2477
+ /* v8 ignore stop */
2478
+ const started = await startDevDaemon(deps.socketPath);
2479
+ /* v8 ignore next -- defensive: pid is null only when spawn fails silently @preserve */
2480
+ const message = `daemon running in dev mode from ${repoCwd} (pid ${started.pid ?? "unknown"})\nrun 'ouro up' to return to production mode`;
2481
+ deps.writeStdout(message);
2482
+ return message;
2483
+ }
2484
+ // ── rollback command (local, no daemon socket needed for symlinks) ──
2485
+ /* v8 ignore start -- rollback/versions: tested via daemon-cli-rollback/versions tests @preserve */
2486
+ if (command.kind === "rollback") {
2487
+ const currentVersion = deps.getCurrentCliVersion?.() ?? "unknown";
2488
+ if (command.version) {
2489
+ // Rollback to a specific version
2490
+ const installed = deps.listCliVersions?.() ?? [];
2491
+ if (!installed.includes(command.version)) {
2492
+ try {
2493
+ await deps.installCliVersion(command.version);
2494
+ }
2495
+ catch (error) {
2496
+ const message = `failed to install version ${command.version}: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
2497
+ deps.writeStdout(message);
2498
+ return message;
2499
+ }
2500
+ }
2501
+ deps.activateCliVersion(command.version);
2502
+ }
2503
+ else {
2504
+ // Rollback to previous version
2505
+ const previousVersion = deps.getPreviousCliVersion?.();
2506
+ if (!previousVersion) {
2507
+ const message = "no previous version to roll back to";
2508
+ deps.writeStdout(message);
2509
+ return message;
2510
+ }
2511
+ deps.activateCliVersion(previousVersion);
2512
+ command = { ...command, version: previousVersion };
2513
+ }
2514
+ // Stop daemon (non-fatal if not running)
2515
+ try {
2516
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
2517
+ }
2518
+ catch {
2519
+ // Daemon may not be running — that's fine
2520
+ }
2521
+ const message = `rolled back to ${command.version} (was ${currentVersion})`;
2522
+ deps.writeStdout(message);
2523
+ return message;
2524
+ }
2525
+ // ── versions command (local install list + published update truth, no daemon socket needed) ──
2526
+ if (command.kind === "versions") {
2527
+ const versions = deps.listCliVersions?.() ?? [];
2528
+ const current = deps.getCurrentCliVersion?.();
2529
+ const previous = deps.getPreviousCliVersion?.();
2530
+ const localSection = versions.length === 0
2531
+ ? "no versions installed"
2532
+ : versions.map((v) => {
2533
+ let line = v;
2534
+ if (v === current)
2535
+ line += " * current";
2536
+ if (v === previous)
2537
+ line += " (previous)";
2538
+ return line;
2539
+ }).join("\n");
2540
+ const sections = [localSection];
2541
+ if (deps.checkForCliUpdate) {
2542
+ try {
2543
+ const updateResult = await deps.checkForCliUpdate();
2544
+ if (updateResult.latestVersion) {
2545
+ sections.push(`published alpha: ${updateResult.latestVersion} (${updateResult.available ? "update available" : "up to date"})`);
2546
+ }
2547
+ else if (updateResult.error) {
2548
+ sections.push(`published alpha: unavailable (${updateResult.error})`);
2549
+ }
2550
+ }
2551
+ catch (err) {
2552
+ const reason = err instanceof Error ? err.message : String(err);
2553
+ sections.push(`published alpha: unavailable (${reason})`);
2554
+ }
2555
+ }
2556
+ const message = sections.join("\n\n");
2557
+ deps.writeStdout(message);
2558
+ return message;
2559
+ }
2560
+ /* v8 ignore stop */
1031
2561
  if (command.kind === "daemon.logs" && deps.tailLogs) {
1032
2562
  deps.tailLogs();
1033
2563
  return "";
1034
2564
  }
1035
- if (command.kind === "friend.link") {
1036
- const linker = deps.linkFriendIdentity ?? defaultLinkFriendIdentity;
1037
- const message = await linker(command);
2565
+ if (command.kind === "outlook") {
2566
+ let status;
2567
+ try {
2568
+ status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
2569
+ /* v8 ignore start — error path: daemon not running */
2570
+ }
2571
+ catch {
2572
+ const message = "daemon unavailable — start with `ouro up` first";
2573
+ deps.writeStdout(message);
2574
+ return message;
2575
+ }
2576
+ /* v8 ignore stop */
2577
+ const payload = parseStatusPayload(status.data);
2578
+ /* v8 ignore start -- ?? branch: outlookUrl always present in test fixtures */
2579
+ const outlookUrl = payload?.overview.outlookUrl ?? "unavailable";
2580
+ /* v8 ignore stop */
2581
+ if (!command.json) {
2582
+ deps.writeStdout(outlookUrl);
2583
+ return outlookUrl;
2584
+ }
2585
+ /* v8 ignore start — error path: outlook URL not available */
2586
+ if (outlookUrl === "unavailable") {
2587
+ deps.writeStdout(outlookUrl);
2588
+ return outlookUrl;
2589
+ }
2590
+ /* v8 ignore stop */
2591
+ /* v8 ignore start -- ?? branch: tests always inject fetchImpl */
2592
+ const fetchImpl = deps.fetchImpl ?? fetch;
2593
+ /* v8 ignore stop */
2594
+ const response = await fetchImpl(`${outlookUrl}/api/machine`);
2595
+ const data = await response.json();
2596
+ const text = JSON.stringify(data, null, 2);
2597
+ deps.writeStdout(text);
2598
+ return text;
2599
+ }
2600
+ // ── hook: handle Claude Code lifecycle hooks ──
2601
+ /* v8 ignore start -- hook handler: reads real stdin, sends to real daemon @preserve */
2602
+ if (command.kind === "hook") {
2603
+ let stdinData = "";
2604
+ try {
2605
+ stdinData = require("fs").readFileSync(0, "utf-8");
2606
+ }
2607
+ catch { /* no stdin */ }
2608
+ let event = {};
2609
+ try {
2610
+ event = JSON.parse(stdinData);
2611
+ }
2612
+ catch { /* malformed */ }
2613
+ const eventType = command.event;
2614
+ const sessionId = event.session_id ?? "unknown";
2615
+ const cwd = event.cwd ?? "";
2616
+ // Build notification content based on event type
2617
+ let content;
2618
+ if (eventType === "session-start") {
2619
+ const model = event.model ?? "";
2620
+ const source = event.source ?? "";
2621
+ content = `[Claude Code session started: ${sessionId}, cwd: ${cwd}${model ? `, model: ${model}` : ""}${source ? `, source: ${source}` : ""}]`;
2622
+ }
2623
+ else if (eventType === "stop") {
2624
+ const lastMsg = event.last_assistant_message ?? "";
2625
+ content = `[Claude Code session ended: ${sessionId}${lastMsg ? `, last: ${lastMsg.slice(0, 200)}` : ""}]`;
2626
+ }
2627
+ else if (eventType === "post-tool-use") {
2628
+ const toolName = event.tool_name ?? "";
2629
+ content = `[Claude Code used ${toolName} in session ${sessionId}]`;
2630
+ }
2631
+ else {
2632
+ content = `[Claude Code hook: ${eventType} in session ${sessionId}]`;
2633
+ }
2634
+ // Send to the specific agent configured for this hook
2635
+ try {
2636
+ await deps.sendCommand(deps.socketPath, { kind: "message.send", from: `claude-code:${sessionId}`, to: command.agent, content }).catch(() => { });
2637
+ await deps.sendCommand(deps.socketPath, { kind: "inner.wake", agent: command.agent }).catch(() => { });
2638
+ }
2639
+ catch { /* daemon not running — silent */ }
2640
+ // Output for Claude Code hook system
2641
+ deps.writeStdout(JSON.stringify({ continue: true }));
2642
+ return JSON.stringify({ continue: true });
2643
+ }
2644
+ /* v8 ignore stop */
2645
+ // ── setup: configure dev tool integration ──
2646
+ if (command.kind === "setup") {
2647
+ const { tool, agent: setupAgent } = command;
2648
+ const sourceRoot = (0, identity_1.getRepoRoot)();
2649
+ const runtimeMode = (0, runtime_mode_1.detectRuntimeMode)(sourceRoot);
2650
+ const mcpServeCommand = runtimeMode === "dev"
2651
+ ? `node ${path.join(sourceRoot, "dist", "heart", "daemon", "ouro-bot-entry.js")} mcp-serve --agent ${setupAgent}`
2652
+ : `ouro mcp-serve --agent ${setupAgent}`;
2653
+ if (tool === "claude-code") {
2654
+ // 1. Register MCP server with Claude Code
2655
+ const mcpAddCmd = `claude mcp add ouro-${setupAgent} -s user -- ${mcpServeCommand}`;
2656
+ (0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
2657
+ // 2. Write hooks config to ~/.claude/settings.json
2658
+ const settingsPath = path.join(os.homedir(), ".claude", "settings.json");
2659
+ let settings = {};
2660
+ if (fs.existsSync(settingsPath)) {
2661
+ try {
2662
+ settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
2663
+ }
2664
+ catch { /* start fresh */ }
2665
+ }
2666
+ // Use `ouro hook <event>` — resolves the right code based on dev vs installed mode.
2667
+ // Bare `ouro` works because ouro is on PATH via ~/.ouro-cli/bin/.
2668
+ settings.hooks = {
2669
+ ...(settings.hooks ?? {}),
2670
+ SessionStart: [{ hooks: [{ type: "command", command: `ouro hook session-start --agent ${setupAgent}`, timeout: 5 }] }],
2671
+ Stop: [{ hooks: [{ type: "command", command: `ouro hook stop --agent ${setupAgent}`, timeout: 5 }] }],
2672
+ PostToolUse: [{ matcher: "Bash|Edit|Write", hooks: [{ type: "command", command: `ouro hook post-tool-use --agent ${setupAgent}`, timeout: 5 }] }],
2673
+ };
2674
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
2675
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
2676
+ (0, runtime_1.emitNervesEvent)({
2677
+ component: "daemon",
2678
+ event: "daemon.setup_complete",
2679
+ message: "dev tool setup complete",
2680
+ meta: { tool, agent: setupAgent, runtimeMode },
2681
+ });
2682
+ // 3. Write conversation formatting instructions to ~/.claude/CLAUDE.md
2683
+ const claudeMdPath = path.join(os.homedir(), ".claude", "CLAUDE.md");
2684
+ const agentInstructions = `\n## Agent conversations (ouro)\nWhen using MCP \`send_message\` to talk to an ouro agent, format the exchange clearly:\n- Before the tool call, briefly say what you're asking/telling the agent\n- After the response, quote the agent's reply in a blockquote, then add your reaction\n- Example: **Me → Agent:** "question" / > **Agent:** "response" / Your synthesis here\n`;
2685
+ let existingClaudeMd = "";
2686
+ if (fs.existsSync(claudeMdPath)) {
2687
+ existingClaudeMd = fs.readFileSync(claudeMdPath, "utf-8");
2688
+ }
2689
+ if (!existingClaudeMd.includes("Agent conversations (ouro)")) {
2690
+ fs.writeFileSync(claudeMdPath, existingClaudeMd + agentInstructions);
2691
+ }
2692
+ const message = `setup complete: claude-code + ${setupAgent}\n MCP server registered\n hooks configured\n conversation formatting instructions added`;
2693
+ deps.writeStdout(message);
2694
+ return message;
2695
+ }
2696
+ else {
2697
+ // tool === "codex" (parseSetupCommand validates tool, so this is the only remaining option)
2698
+ const mcpAddCmd = `codex mcp add ouro-${setupAgent} -- ${mcpServeCommand}`;
2699
+ (0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
2700
+ (0, runtime_1.emitNervesEvent)({
2701
+ component: "daemon",
2702
+ event: "daemon.setup_complete",
2703
+ message: "dev tool setup complete",
2704
+ meta: { tool, agent: setupAgent, runtimeMode },
2705
+ });
2706
+ const message = `setup complete: codex + ${setupAgent}\n MCP server registered`;
2707
+ deps.writeStdout(message);
2708
+ return message;
2709
+ }
2710
+ }
2711
+ /* v8 ignore start — mcp-serve block binds to process.stdin/stdout; tested via mcp-server unit tests */
2712
+ // ── mcp-serve: start MCP server in-process on stdin/stdout ──
2713
+ if (command.kind === "mcp-serve") {
2714
+ const { createMcpServer } = await Promise.resolve().then(() => __importStar(require("./mcp-server")));
2715
+ const friendId = command.friendId ?? `local-${os.userInfo().username}`;
2716
+ const mcpSocketPath = command.socketOverride ?? deps.socketPath;
2717
+ const server = createMcpServer({
2718
+ agent: command.agent,
2719
+ friendId,
2720
+ socketPath: mcpSocketPath,
2721
+ stdin: process.stdin,
2722
+ stdout: process.stdout,
2723
+ });
2724
+ server.start();
2725
+ (0, runtime_1.emitNervesEvent)({
2726
+ component: "daemon",
2727
+ event: "daemon.mcp_serve_started",
2728
+ message: "MCP server started via CLI",
2729
+ meta: { agent: command.agent, friendId },
2730
+ });
2731
+ // Keep process alive until stdin closes
2732
+ await new Promise((resolve) => {
2733
+ process.stdin.on("end", () => {
2734
+ server.stop();
2735
+ resolve();
2736
+ });
2737
+ });
2738
+ return "";
2739
+ }
2740
+ /* v8 ignore stop */
2741
+ // ── mcp subcommands (routed through daemon socket) ──
2742
+ if (command.kind === "mcp.list" || command.kind === "mcp.call") {
2743
+ const daemonCommand = toDaemonCommand(command);
2744
+ let response;
2745
+ try {
2746
+ response = await deps.sendCommand(deps.socketPath, daemonCommand);
2747
+ }
2748
+ catch {
2749
+ const message = "daemon unavailable — start with `ouro up` first";
2750
+ deps.writeStdout(message);
2751
+ return message;
2752
+ }
2753
+ if (!response.ok) {
2754
+ const message = response.error ?? "unknown error";
2755
+ deps.writeStdout(message);
2756
+ return message;
2757
+ }
2758
+ const message = formatMcpResponse(command, response);
2759
+ deps.writeStdout(message);
2760
+ return message;
2761
+ }
2762
+ // ── task subcommands (local, no daemon socket needed) ──
2763
+ if (command.kind === "task.board" || command.kind === "task.create" || command.kind === "task.update" ||
2764
+ command.kind === "task.show" || command.kind === "task.actionable" || command.kind === "task.deps" ||
2765
+ command.kind === "task.sessions" || command.kind === "task.fix") {
2766
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2767
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
2768
+ /* v8 ignore stop */
2769
+ const message = executeTaskCommand(command, taskMod);
2770
+ deps.writeStdout(message);
2771
+ return message;
2772
+ }
2773
+ // ── reminder subcommands (local, no daemon socket needed) ──
2774
+ if (command.kind === "reminder.create") {
2775
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2776
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
2777
+ /* v8 ignore stop */
2778
+ const message = executeReminderCommand(command, taskMod);
2779
+ deps.writeStdout(message);
2780
+ return message;
2781
+ }
2782
+ // ── habit subcommands (local, no daemon socket needed) ──
2783
+ if (command.kind === "habit.list" || command.kind === "habit.create") {
2784
+ const { parseHabitFile, renderHabitFile } = await Promise.resolve().then(() => __importStar(require("./habit-parser")));
2785
+ /* v8 ignore start -- production default: uses real bundle root @preserve */
2786
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
2787
+ const bundleRoot = deps.agentBundleRoot ?? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
2788
+ /* v8 ignore stop */
2789
+ const habitsDir = path.join(bundleRoot, "habits");
2790
+ if (command.kind === "habit.list") {
2791
+ let files;
2792
+ try {
2793
+ files = fs.readdirSync(habitsDir).filter((f) => f.endsWith(".md") && f !== "README.md");
2794
+ }
2795
+ catch {
2796
+ const message = "no habits found";
2797
+ deps.writeStdout(message);
2798
+ return message;
2799
+ }
2800
+ if (files.length === 0) {
2801
+ const message = "no habits found";
2802
+ deps.writeStdout(message);
2803
+ return message;
2804
+ }
2805
+ const lines = [];
2806
+ for (const file of files) {
2807
+ const content = fs.readFileSync(path.join(habitsDir, file), "utf-8");
2808
+ const habit = parseHabitFile(content, path.join(habitsDir, file));
2809
+ const lastRunStr = habit.lastRun ?? "never";
2810
+ lines.push(`${habit.name} cadence=${habit.cadence ?? "none"} status=${habit.status} lastRun=${lastRunStr}`);
2811
+ }
2812
+ const message = lines.join("\n");
2813
+ deps.writeStdout(message);
2814
+ return message;
2815
+ }
2816
+ // habit.create
2817
+ const filePath = path.join(habitsDir, `${command.name}.md`);
2818
+ if (fs.existsSync(filePath)) {
2819
+ const message = `error: habit '${command.name}' already exists`;
2820
+ deps.writeStdout(message);
2821
+ return message;
2822
+ }
2823
+ fs.mkdirSync(habitsDir, { recursive: true });
2824
+ const now = new Date().toISOString();
2825
+ const content = renderHabitFile({
2826
+ title: command.name,
2827
+ cadence: command.cadence ?? "null",
2828
+ status: "active",
2829
+ lastRun: now,
2830
+ created: now,
2831
+ }, `Habit: ${command.name}`);
2832
+ fs.writeFileSync(filePath, content, "utf-8");
2833
+ const message = `created: ${filePath}`;
2834
+ deps.writeStdout(message);
2835
+ return message;
2836
+ }
2837
+ // ── friend subcommands (local, no daemon socket needed) ──
2838
+ if (command.kind === "friend.list" || command.kind === "friend.show" || command.kind === "friend.create" ||
2839
+ command.kind === "friend.update" || command.kind === "friend.link" || command.kind === "friend.unlink") {
2840
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2841
+ let store = deps.friendStore;
2842
+ if (!store) {
2843
+ // Derive agent-scoped friends dir from --agent flag or link/unlink's agent field
2844
+ const agentName = ("agent" in command && command.agent) ? command.agent : undefined;
2845
+ const friendsDir = agentName
2846
+ ? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`, "friends")
2847
+ : path.join((0, identity_1.getAgentBundlesRoot)(), "friends");
2848
+ store = new store_file_1.FileFriendStore(friendsDir);
2849
+ }
2850
+ /* v8 ignore stop */
2851
+ const message = await executeFriendCommand(command, store);
2852
+ deps.writeStdout(message);
2853
+ return message;
2854
+ }
2855
+ // ── auth (local, no daemon socket needed) ──
2856
+ if (command.kind === "auth.run") {
2857
+ const provider = command.provider ?? (0, auth_flow_1.readAgentConfigForAgent)(command.agent).config.humanFacing.provider;
2858
+ /* v8 ignore next -- tests always inject runAuthFlow; default is for production @preserve */
2859
+ const authRunner = deps.runAuthFlow ?? auth_flow_1.runRuntimeAuthFlow;
2860
+ const result = await authRunner({
2861
+ agentName: command.agent,
2862
+ provider,
2863
+ promptInput: deps.promptInput,
2864
+ });
2865
+ // Behavior: ouro auth stores credentials only — does NOT switch provider.
2866
+ // Use `ouro auth switch` to change the active provider.
2867
+ deps.writeStdout(result.message);
2868
+ // Verify the credentials actually work by pinging the provider
2869
+ /* v8 ignore start -- integration: real API ping after auth @preserve */
2870
+ try {
2871
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2872
+ const status = await verifyProviderCredentials(provider, secrets.providers);
2873
+ deps.writeStdout(`${provider}: ${status}`);
2874
+ }
2875
+ catch {
2876
+ // Verification failure is non-blocking — credentials were saved regardless
2877
+ }
2878
+ /* v8 ignore stop */
2879
+ return result.message;
2880
+ }
2881
+ // ── auth verify (local, no daemon socket needed) ──
2882
+ /* v8 ignore start -- auth verify/switch: tested in daemon-cli.test.ts but v8 traces differ in CI @preserve */
2883
+ if (command.kind === "auth.verify") {
2884
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2885
+ const providers = secrets.providers;
2886
+ if (command.provider) {
2887
+ const status = await verifyProviderCredentials(command.provider, providers);
2888
+ const message = `${command.provider}: ${status}`;
2889
+ deps.writeStdout(message);
2890
+ return message;
2891
+ }
2892
+ const lines = [];
2893
+ for (const p of Object.keys(providers)) {
2894
+ const status = await verifyProviderCredentials(p, providers);
2895
+ lines.push(`${p}: ${status}`);
2896
+ }
2897
+ const message = lines.join("\n");
2898
+ deps.writeStdout(message);
2899
+ return message;
2900
+ }
2901
+ // ── auth switch (local, no daemon socket needed) ──
2902
+ if (command.kind === "auth.switch") {
2903
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2904
+ const providerSecrets = secrets.providers[command.provider];
2905
+ if (!providerSecrets || !hasStoredCredentials(command.provider, providerSecrets)) {
2906
+ const message = `no credentials stored for ${command.provider}. Run \`ouro auth --agent ${command.agent} --provider ${command.provider}\` first.`;
2907
+ deps.writeStdout(message);
2908
+ return message;
2909
+ }
2910
+ // Verify credentials actually work before switching
2911
+ const status = await verifyProviderCredentials(command.provider, secrets.providers);
2912
+ if (!status.startsWith("ok")) {
2913
+ const message = `${command.provider}: ${status}. fix credentials with \`ouro auth --agent ${command.agent} --provider ${command.provider}\` before switching.`;
2914
+ deps.writeStdout(message);
2915
+ return message;
2916
+ }
2917
+ if (command.facing) {
2918
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, command.facing, command.provider);
2919
+ }
2920
+ else {
2921
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, "human", command.provider);
2922
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, "agent", command.provider);
2923
+ }
2924
+ const message = `switched ${command.agent} to ${command.provider} (verified working)`;
2925
+ deps.writeStdout(message);
2926
+ return message;
2927
+ }
2928
+ /* v8 ignore stop */
2929
+ // ── config models (local, no daemon socket needed) ──
2930
+ /* v8 ignore start -- config models: tested via daemon-cli.test.ts @preserve */
2931
+ if (command.kind === "config.models") {
2932
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2933
+ const provider = config.humanFacing.provider;
2934
+ if (provider !== "github-copilot") {
2935
+ const message = `model listing not available for ${provider} — check provider documentation.`;
2936
+ deps.writeStdout(message);
2937
+ return message;
2938
+ }
2939
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2940
+ const ghConfig = secrets.providers["github-copilot"];
2941
+ if (!ghConfig.githubToken || !ghConfig.baseUrl) {
2942
+ throw new Error(`github-copilot credentials not configured. Run \`ouro auth --agent ${command.agent} --provider github-copilot\` first.`);
2943
+ }
2944
+ const fetchFn = deps.fetchImpl ?? fetch;
2945
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2946
+ if (models.length === 0) {
2947
+ const message = "no models found";
2948
+ deps.writeStdout(message);
2949
+ return message;
2950
+ }
2951
+ const lines = ["available models:"];
2952
+ for (const m of models) {
2953
+ const caps = m.capabilities?.length ? ` (${m.capabilities.join(", ")})` : "";
2954
+ lines.push(` ${m.id}${caps}`);
2955
+ }
2956
+ const message = lines.join("\n");
1038
2957
  deps.writeStdout(message);
1039
2958
  return message;
1040
2959
  }
2960
+ /* v8 ignore stop */
2961
+ // ── config model (local, no daemon socket needed) ──
2962
+ /* v8 ignore start -- config model: tested via daemon-cli.test.ts @preserve */
2963
+ if (command.kind === "config.model") {
2964
+ const facing = command.facing ?? "human";
2965
+ // Validate model availability for github-copilot before writing
2966
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2967
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
2968
+ if (facingConfig.provider === "github-copilot") {
2969
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2970
+ const ghConfig = secrets.providers["github-copilot"];
2971
+ if (ghConfig.githubToken && ghConfig.baseUrl) {
2972
+ const fetchFn = deps.fetchImpl ?? fetch;
2973
+ try {
2974
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2975
+ const available = models.map((m) => m.id);
2976
+ if (available.length > 0 && !available.includes(command.modelName)) {
2977
+ const message = `model '${command.modelName}' not found. available models:\n${available.map((id) => ` ${id}`).join("\n")}`;
2978
+ deps.writeStdout(message);
2979
+ return message;
2980
+ }
2981
+ }
2982
+ catch {
2983
+ // Catalog validation failed — fall through to ping test
2984
+ }
2985
+ // Ping test: verify the model actually works before switching
2986
+ const pingResult = await pingGithubCopilotModel(ghConfig.baseUrl, ghConfig.githubToken, command.modelName, fetchFn);
2987
+ if (!pingResult.ok) {
2988
+ const message = `model '${command.modelName}' ping failed: ${pingResult.error}\nrun \`ouro config models --agent ${command.agent}\` to see available models.`;
2989
+ deps.writeStdout(message);
2990
+ return message;
2991
+ }
2992
+ }
2993
+ }
2994
+ const { provider, previousModel } = (0, auth_flow_1.writeAgentModel)(command.agent, facing, command.modelName);
2995
+ const message = previousModel
2996
+ ? `updated ${command.agent} model on ${provider}: ${previousModel} → ${command.modelName}`
2997
+ : `set ${command.agent} model on ${provider}: ${command.modelName}`;
2998
+ deps.writeStdout(message);
2999
+ return message;
3000
+ }
3001
+ /* v8 ignore stop */
3002
+ // ── whoami (local, no daemon socket needed) ──
3003
+ if (command.kind === "whoami") {
3004
+ if (command.agent) {
3005
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`);
3006
+ const message = [
3007
+ `agent: ${command.agent}`,
3008
+ `home: ${agentRoot}`,
3009
+ `bones: ${(0, runtime_metadata_1.getRuntimeMetadata)().version}`,
3010
+ ].join("\n");
3011
+ deps.writeStdout(message);
3012
+ return message;
3013
+ }
3014
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
3015
+ try {
3016
+ const info = deps.whoamiInfo
3017
+ ? deps.whoamiInfo()
3018
+ : {
3019
+ agentName: (0, identity_1.getAgentName)(),
3020
+ homePath: path.join((0, identity_1.getAgentBundlesRoot)(), `${(0, identity_1.getAgentName)()}.ouro`),
3021
+ bonesVersion: (0, runtime_metadata_1.getRuntimeMetadata)().version,
3022
+ };
3023
+ const message = [
3024
+ `agent: ${info.agentName}`,
3025
+ `home: ${info.homePath}`,
3026
+ `bones: ${info.bonesVersion}`,
3027
+ ].join("\n");
3028
+ deps.writeStdout(message);
3029
+ return message;
3030
+ }
3031
+ catch {
3032
+ const message = "error: no agent context — use --agent <name> to specify";
3033
+ deps.writeStdout(message);
3034
+ return message;
3035
+ }
3036
+ /* v8 ignore stop */
3037
+ }
3038
+ // ── changelog (local, no daemon socket needed) ──
3039
+ if (command.kind === "changelog") {
3040
+ try {
3041
+ const changelogPath = deps.getChangelogPath
3042
+ ? deps.getChangelogPath()
3043
+ : (0, bundle_manifest_1.getChangelogPath)();
3044
+ const raw = fs.readFileSync(changelogPath, "utf-8");
3045
+ const parsed = JSON.parse(raw);
3046
+ const entries = Array.isArray(parsed) ? parsed : (parsed.versions ?? []);
3047
+ let filtered = entries;
3048
+ if (command.from) {
3049
+ const fromVersion = command.from;
3050
+ filtered = entries.filter((e) => semver.valid(e.version) && semver.gt(e.version, fromVersion));
3051
+ }
3052
+ if (filtered.length === 0) {
3053
+ const message = "no changelog entries found.";
3054
+ deps.writeStdout(message);
3055
+ return message;
3056
+ }
3057
+ const lines = [];
3058
+ for (const entry of filtered) {
3059
+ lines.push(`## ${entry.version}${entry.date ? ` (${entry.date})` : ""}`);
3060
+ if (entry.changes) {
3061
+ for (const change of entry.changes) {
3062
+ lines.push(`- ${change}`);
3063
+ }
3064
+ }
3065
+ lines.push("");
3066
+ }
3067
+ const message = lines.join("\n").trim();
3068
+ deps.writeStdout(message);
3069
+ return message;
3070
+ }
3071
+ catch {
3072
+ const message = "no changelog entries found.";
3073
+ deps.writeStdout(message);
3074
+ return message;
3075
+ }
3076
+ }
3077
+ // ── thoughts (local, no daemon socket needed) ──
3078
+ if (command.kind === "thoughts") {
3079
+ try {
3080
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3081
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
3082
+ const sessionFilePath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
3083
+ if (command.json) {
3084
+ try {
3085
+ const raw = fs.readFileSync(sessionFilePath, "utf-8");
3086
+ deps.writeStdout(raw);
3087
+ return raw;
3088
+ }
3089
+ catch {
3090
+ const message = "no inner dialog session found";
3091
+ deps.writeStdout(message);
3092
+ return message;
3093
+ }
3094
+ }
3095
+ const turns = (0, thoughts_1.parseInnerDialogSession)(sessionFilePath);
3096
+ const message = (0, thoughts_1.formatThoughtTurns)(turns, command.last ?? 10);
3097
+ deps.writeStdout(message);
3098
+ if (command.follow) {
3099
+ deps.writeStdout("\n\n--- following (ctrl+c to stop) ---\n");
3100
+ /* v8 ignore start -- callback tested via followThoughts unit tests @preserve */
3101
+ const stop = (0, thoughts_1.followThoughts)(sessionFilePath, (formatted) => {
3102
+ deps.writeStdout("\n" + formatted);
3103
+ });
3104
+ /* v8 ignore stop */
3105
+ // Block until process exit; cleanup watcher on SIGINT/SIGTERM
3106
+ return new Promise((resolve) => {
3107
+ const cleanup = () => { stop(); resolve(message); };
3108
+ process.once("SIGINT", cleanup);
3109
+ process.once("SIGTERM", cleanup);
3110
+ });
3111
+ }
3112
+ return message;
3113
+ }
3114
+ catch {
3115
+ const message = "error: no agent context — use --agent <name> to specify";
3116
+ deps.writeStdout(message);
3117
+ return message;
3118
+ }
3119
+ }
3120
+ // ── attention queue (local, no daemon socket needed) ──
3121
+ /* v8 ignore start -- CLI attention handler: requires real obligation store on disk @preserve */
3122
+ if (command.kind === "attention.list" || command.kind === "attention.show" || command.kind === "attention.history") {
3123
+ try {
3124
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3125
+ const { listActiveObligations, readObligation } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3126
+ if (command.kind === "attention.list") {
3127
+ const obligations = listActiveObligations(agentName);
3128
+ if (obligations.length === 0) {
3129
+ const message = "nothing held — attention queue is empty";
3130
+ deps.writeStdout(message);
3131
+ return message;
3132
+ }
3133
+ const lines = obligations.map((o) => `[${o.id}] ${o.origin.friendId} via ${o.origin.channel}/${o.origin.key} — ${o.delegatedContent.slice(0, 60)}${o.delegatedContent.length > 60 ? "..." : ""} (${o.status})`);
3134
+ const message = lines.join("\n");
3135
+ deps.writeStdout(message);
3136
+ return message;
3137
+ }
3138
+ if (command.kind === "attention.show") {
3139
+ const obligation = readObligation(agentName, command.id);
3140
+ if (!obligation) {
3141
+ const message = `no obligation found with id ${command.id}`;
3142
+ deps.writeStdout(message);
3143
+ return message;
3144
+ }
3145
+ const message = JSON.stringify(obligation, null, 2);
3146
+ deps.writeStdout(message);
3147
+ return message;
3148
+ }
3149
+ // attention.history: show returned obligations
3150
+ const { getObligationsDir } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3151
+ const obligationsDir = getObligationsDir(agentName);
3152
+ let entries = [];
3153
+ try {
3154
+ entries = fs.readdirSync(obligationsDir);
3155
+ }
3156
+ catch { /* empty */ }
3157
+ const returned = entries
3158
+ .filter((e) => e.endsWith(".json"))
3159
+ .map((e) => { try {
3160
+ return JSON.parse(fs.readFileSync(path.join(obligationsDir, e), "utf-8"));
3161
+ }
3162
+ catch {
3163
+ return null;
3164
+ } })
3165
+ .filter((o) => o?.status === "returned")
3166
+ .sort((a, b) => (b.returnedAt ?? 0) - (a.returnedAt ?? 0))
3167
+ .slice(0, 20);
3168
+ if (returned.length === 0) {
3169
+ const message = "no surfacing history yet";
3170
+ deps.writeStdout(message);
3171
+ return message;
3172
+ }
3173
+ const lines = returned.map((o) => {
3174
+ const when = o.returnedAt ? new Date(o.returnedAt).toISOString() : "unknown";
3175
+ return `[${o.id}] → ${o.origin.friendId} via ${o.returnTarget ?? "unknown"} at ${when}`;
3176
+ });
3177
+ const message = lines.join("\n");
3178
+ deps.writeStdout(message);
3179
+ return message;
3180
+ }
3181
+ catch {
3182
+ const message = "error: no agent context — use --agent <name> to specify";
3183
+ deps.writeStdout(message);
3184
+ return message;
3185
+ }
3186
+ }
3187
+ /* v8 ignore stop */
3188
+ // ── inner dialog status (local, no daemon socket needed) ──
3189
+ /* v8 ignore start -- inner status handler: requires real agent state on disk @preserve */
3190
+ if (command.kind === "inner.status") {
3191
+ try {
3192
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3193
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
3194
+ const { buildInnerStatusOutput } = await Promise.resolve().then(() => __importStar(require("./inner-status")));
3195
+ const { sessionPath: getSessionPath } = await Promise.resolve().then(() => __importStar(require("../config")));
3196
+ const { parseCadenceToMs: parseCadenceMs, DEFAULT_CADENCE_MS } = await Promise.resolve().then(() => __importStar(require("./cadence")));
3197
+ const { parseFrontmatter } = await Promise.resolve().then(() => __importStar(require("../../repertoire/tasks/parser")));
3198
+ const { listActiveObligations } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3199
+ // Read runtime state
3200
+ const innerSessionPath = getSessionPath("inner-dialog", "inner", "session");
3201
+ const runtimeJsonPath = path.join(path.dirname(innerSessionPath), "runtime.json");
3202
+ let runtimeState = null;
3203
+ try {
3204
+ const raw = fs.readFileSync(runtimeJsonPath, "utf-8");
3205
+ runtimeState = JSON.parse(raw);
3206
+ }
3207
+ catch { /* missing or corrupt — will show "unknown" */ }
3208
+ // Read journal files
3209
+ const journalDir = path.join(agentRoot, "journal");
3210
+ let journalFiles = [];
3211
+ try {
3212
+ const entries = fs.readdirSync(journalDir, { withFileTypes: true });
3213
+ journalFiles = entries
3214
+ .filter((e) => e.isFile() && !e.name.startsWith("."))
3215
+ .map((e) => {
3216
+ const stat = fs.statSync(path.join(journalDir, e.name));
3217
+ return { name: e.name, mtimeMs: stat.mtimeMs };
3218
+ });
3219
+ }
3220
+ catch { /* missing dir — will show (empty) */ }
3221
+ // Read heartbeat cadence
3222
+ let heartbeat = null;
3223
+ try {
3224
+ const habitsDir = path.join(agentRoot, "habits");
3225
+ const heartbeatPath = path.join(habitsDir, "heartbeat.md");
3226
+ let cadenceMs = DEFAULT_CADENCE_MS;
3227
+ if (fs.existsSync(heartbeatPath)) {
3228
+ const content = fs.readFileSync(heartbeatPath, "utf-8");
3229
+ const lines = content.split(/\r?\n/);
3230
+ if (lines[0]?.trim() === "---") {
3231
+ const closing = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
3232
+ if (closing !== -1) {
3233
+ const rawFrontmatter = lines.slice(1, closing).join("\n");
3234
+ const frontmatter = parseFrontmatter(rawFrontmatter);
3235
+ const parsed = parseCadenceMs(frontmatter.cadence);
3236
+ if (parsed !== null)
3237
+ cadenceMs = parsed;
3238
+ }
3239
+ }
3240
+ }
3241
+ let lastCompletedAt = null;
3242
+ if (runtimeState?.lastCompletedAt) {
3243
+ const ms = new Date(runtimeState.lastCompletedAt).getTime();
3244
+ if (!Number.isNaN(ms))
3245
+ lastCompletedAt = ms;
3246
+ }
3247
+ heartbeat = { cadenceMs, lastCompletedAt };
3248
+ }
3249
+ catch { /* no habits — heartbeat unknown */ }
3250
+ // Attention count
3251
+ const activeObligations = listActiveObligations(agentName);
3252
+ const message = buildInnerStatusOutput({
3253
+ agentName,
3254
+ runtimeState,
3255
+ journalFiles,
3256
+ heartbeat,
3257
+ attentionCount: activeObligations.length,
3258
+ now: Date.now(),
3259
+ });
3260
+ deps.writeStdout(message);
3261
+ return message;
3262
+ }
3263
+ catch {
3264
+ const message = "error: no agent context — use --agent <name> to specify";
3265
+ deps.writeStdout(message);
3266
+ return message;
3267
+ }
3268
+ }
3269
+ /* v8 ignore stop */
3270
+ // ── session list (local, no daemon socket needed) ──
3271
+ if (command.kind === "session.list") {
3272
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
3273
+ const scanner = deps.scanSessions ?? (async () => []);
3274
+ /* v8 ignore stop */
3275
+ const sessions = await scanner();
3276
+ if (sessions.length === 0) {
3277
+ const message = "no active sessions";
3278
+ deps.writeStdout(message);
3279
+ return message;
3280
+ }
3281
+ const lines = sessions.map((s) => `${s.friendId} ${s.friendName} ${s.channel} ${s.lastActivity}`);
3282
+ const message = lines.join("\n");
3283
+ deps.writeStdout(message);
3284
+ return message;
3285
+ }
3286
+ if (command.kind === "chat.connect" && deps.startChat) {
3287
+ await ensureDaemonRunning(deps);
3288
+ await deps.startChat(command.agent);
3289
+ return "";
3290
+ }
1041
3291
  if (command.kind === "hatch.start") {
1042
- // Route through adoption specialist when no explicit hatch args were provided
3292
+ // Route through serpent guide when no explicit hatch args were provided
1043
3293
  const hasExplicitHatchArgs = !!(command.agentName || command.humanName || command.provider || command.credentials);
1044
- if (deps.runAdoptionSpecialist && !hasExplicitHatchArgs) {
3294
+ if (deps.runSerpentGuide && !hasExplicitHatchArgs) {
1045
3295
  // System setup first — ouro command, subagents, UTI — before the interactive specialist
1046
3296
  await performSystemSetup(deps);
1047
- const hatchlingName = await deps.runAdoptionSpecialist();
3297
+ const hatchlingName = await deps.runSerpentGuide();
1048
3298
  if (!hatchlingName) {
1049
3299
  return "";
1050
3300
  }
@@ -1085,6 +3335,16 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
1085
3335
  deps.writeStdout(message);
1086
3336
  return message;
1087
3337
  }
3338
+ if (command.kind === "daemon.status" && isDaemonUnavailableError(error)) {
3339
+ const message = daemonUnavailableStatusOutput(deps.socketPath, deps.healthFilePath);
3340
+ deps.writeStdout(message);
3341
+ return message;
3342
+ }
3343
+ if (command.kind === "daemon.stop" && isDaemonUnavailableError(error)) {
3344
+ const message = "daemon not running";
3345
+ deps.writeStdout(message);
3346
+ return message;
3347
+ }
1088
3348
  throw error;
1089
3349
  }
1090
3350
  const fallbackMessage = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);