@aiwg/cli 2026.10.15 → 2026.10.18

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 (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,1169 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import Config from './config.mjs';
7
+ import FileWatcher from './file-watcher.mjs';
8
+ import CronScheduler from './cron-scheduler.mjs';
9
+ import EventRouter from './event-router.mjs';
10
+ import { IPCServer } from './ipc-server.mjs';
11
+ import { AgentSupervisor } from './agent-supervisor.mjs';
12
+ import { TaskStore } from './task-store.mjs';
13
+ import { AutomationEngine } from './automation-engine.mjs';
14
+ import { registerOpsHandlers } from './ipc-ops-handlers.mjs';
15
+ import { DaemonSupervisor } from '../ralph-external/daemon-supervisor.mjs';
16
+ import { BehaviorRegistry } from '../ralph-external/lib/behavior-registry.mjs';
17
+ import { WebServer } from './web-server.mjs';
18
+ import { MessageRouter } from './message-router.mjs';
19
+ import { ScheduledTaskRunner } from './scheduled-task-runner.mjs';
20
+ import { normalizeResources } from './resource-bounds.mjs';
21
+ import { AutonomousEngine } from './autonomous-engine.mjs';
22
+ import { MemoryManager } from './memory-manager.mjs';
23
+ import { ProviderWatcher } from './provider-watcher.mjs';
24
+ import { DaemonBehaviorLoader } from './behavior-loader.mjs';
25
+ import { createMessagingHub } from '../messaging/index.mjs';
26
+
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+
29
+ class DaemonMain {
30
+ constructor(deps = {}) {
31
+ // Injectable construction sites for the conversational stack. The
32
+ // housekeeper profile test (#3353 B5) passes throwing stubs here to
33
+ // prove the minimal profile never constructs the skipped modules.
34
+ this.deps = {
35
+ MemoryManager,
36
+ AgentSupervisor,
37
+ AutomationEngine,
38
+ DaemonSupervisor,
39
+ BehaviorRegistry,
40
+ DaemonBehaviorLoader,
41
+ MessageRouter,
42
+ ScheduledTaskRunner,
43
+ AutonomousEngine,
44
+ ProviderWatcher,
45
+ WebServer,
46
+ createMessagingHub,
47
+ ...deps,
48
+ };
49
+ this.config = null;
50
+ this.fileWatcher = null;
51
+ this.cronScheduler = null;
52
+ this.eventRouter = null;
53
+ this.messagingBus = null;
54
+ this.ipcServer = null;
55
+ this.supervisor = null;
56
+ this.taskStore = null;
57
+ this.automationEngine = null;
58
+ this.daemonSupervisor = null;
59
+ this.behaviorRegistry = null;
60
+ this.webServer = null;
61
+ this.messageRouter = null;
62
+ this.opsHandlersApi = null;
63
+ this.scheduledTaskRunner = null;
64
+ this.autonomousEngine = null;
65
+ this.roomManager = null;
66
+ this.memoryManager = null;
67
+ this.providerWatcher = null;
68
+ this.behaviorLoader = null;
69
+ this.shutdownInProgress = false;
70
+ this.isRotating = false;
71
+ this.startTime = Date.now();
72
+ this.pidFile = '.aiwg/daemon.pid';
73
+ this.lockFile = '.aiwg/daemon/.lock';
74
+ this.heartbeatFile = '.aiwg/daemon/heartbeat';
75
+ this.stateFile = '.aiwg/daemon/state.json';
76
+ this.logFile = '.aiwg/daemon/daemon.log';
77
+ this.socketPath = '.aiwg/daemon/daemon.sock';
78
+ this.taskStorePath = '.aiwg/daemon/tasks.json';
79
+ this.lockFd = null;
80
+ }
81
+
82
+ async start() {
83
+ try {
84
+ this.setupDirectories();
85
+ this.acquireLock();
86
+ this.writePidFile();
87
+ this.setupSignalHandlers();
88
+ this.redirectLogs();
89
+ await this.loadConfig();
90
+ await this.initializeSubsystems();
91
+ this.startHeartbeat();
92
+ this.log('Daemon started successfully');
93
+ } catch (error) {
94
+ this.log(`Fatal error during startup: ${error.message}`);
95
+ process.exit(1);
96
+ }
97
+ }
98
+
99
+ setupDirectories() {
100
+ const dirs = [
101
+ '.aiwg/daemon',
102
+ '.aiwg/daemon/actions',
103
+ '.aiwg/daemon/events',
104
+ '.aiwg/daemon/memory',
105
+ ];
106
+
107
+ for (const dir of dirs) {
108
+ if (!fs.existsSync(dir)) {
109
+ fs.mkdirSync(dir, { recursive: true });
110
+ }
111
+ }
112
+ }
113
+
114
+ acquireLock() {
115
+ try {
116
+ this.lockFd = fs.openSync(this.lockFile, 'wx');
117
+ fs.writeSync(this.lockFd, String(process.pid));
118
+ } catch (error) {
119
+ if (error.code === 'EEXIST') {
120
+ this.log('Daemon is already running (lock file exists)');
121
+ process.exit(1);
122
+ }
123
+ throw error;
124
+ }
125
+ }
126
+
127
+ writePidFile() {
128
+ const tmpFile = `${this.pidFile}.tmp`;
129
+ fs.writeFileSync(tmpFile, String(process.pid));
130
+ fs.renameSync(tmpFile, this.pidFile);
131
+ }
132
+
133
+ setupSignalHandlers() {
134
+ process.on('SIGTERM', () => this.shutdown('SIGTERM'));
135
+ process.on('SIGINT', () => this.shutdown('SIGINT'));
136
+ process.on('SIGHUP', () => this.reloadConfig());
137
+ }
138
+
139
+ redirectLogs() {
140
+ const logStream = fs.createWriteStream(this.logFile, { flags: 'a' });
141
+
142
+ process.stdout.write = (chunk) => {
143
+ this.rotateLogIfNeeded();
144
+ return logStream.write(chunk);
145
+ };
146
+
147
+ process.stderr.write = (chunk) => {
148
+ this.rotateLogIfNeeded();
149
+ return logStream.write(chunk);
150
+ };
151
+ }
152
+
153
+ rotateLogIfNeeded() {
154
+ if (this.isRotating) return;
155
+
156
+ try {
157
+ const stats = fs.statSync(this.logFile);
158
+ const maxSize = (this.config?.get('daemon.log.max_size_mb') || 50) * 1024 * 1024;
159
+ const maxFiles = this.config?.get('daemon.log.max_files') || 5;
160
+
161
+ if (stats.size > maxSize) {
162
+ this.isRotating = true;
163
+
164
+ for (let i = maxFiles - 1; i >= 1; i--) {
165
+ const oldFile = `${this.logFile}.${i}`;
166
+ const newFile = `${this.logFile}.${i + 1}`;
167
+ if (fs.existsSync(oldFile)) {
168
+ fs.renameSync(oldFile, newFile);
169
+ }
170
+ }
171
+
172
+ fs.renameSync(this.logFile, `${this.logFile}.1`);
173
+
174
+ if (fs.existsSync(`${this.logFile}.${maxFiles + 1}`)) {
175
+ fs.unlinkSync(`${this.logFile}.${maxFiles + 1}`);
176
+ }
177
+
178
+ this.isRotating = false;
179
+ }
180
+ } catch (error) {
181
+ this.isRotating = false;
182
+ }
183
+ }
184
+
185
+ async loadConfig() {
186
+ const config = new Config();
187
+ config.load();
188
+
189
+ const errors = config.validate();
190
+ if (errors.length > 0) {
191
+ this.log(`Configuration validation errors: ${errors.join(', ')}`);
192
+ throw new Error('Invalid configuration');
193
+ }
194
+ await config.resolveSecrets();
195
+ this.config = config;
196
+ }
197
+
198
+ async reloadConfig() {
199
+ this.log('Reloading configuration (SIGHUP received)');
200
+ try {
201
+ await this.loadConfig();
202
+ await this.stopSubsystems();
203
+ await this.initializeSubsystems();
204
+ this.log('Configuration reloaded successfully');
205
+ } catch (error) {
206
+ this.log(`Failed to reload configuration: ${error.message}`);
207
+ }
208
+ }
209
+
210
+ async initializeSubsystems() {
211
+ // Epic #3353 B5: the single profile gate. The housekeeper profile loads
212
+ // only the deterministic maintenance stack (scheduler/runner/store,
213
+ // watcher/router, minimal IPC) and never constructs the conversational
214
+ // stack below, so no model calls are possible in this profile.
215
+ if (this.config.get('daemon.profile') === 'housekeeper') {
216
+ await this.initializeHousekeeperSubsystems();
217
+ return;
218
+ }
219
+ // Initialize memory manager (cross-session context for concierge)
220
+ this.memoryManager = new this.deps.MemoryManager({ projectRoot: process.cwd() });
221
+ const memorySnapshot = this.memoryManager.load();
222
+ const totalEntries = memorySnapshot.project.length + memorySnapshot.user.length;
223
+ this.log(`Memory manager initialized (${totalEntries} persistent entries loaded)`);
224
+
225
+ this.eventRouter = new EventRouter();
226
+
227
+ // Initialize task store (persistent task tracking)
228
+ this.taskStore = new TaskStore(this.taskStorePath);
229
+ await this.taskStore.initialize();
230
+ this.log(`Task store initialized (${this.taskStore.size} existing tasks)`);
231
+
232
+ // Initialize agent supervisor (spawns claude -p subprocesses)
233
+ const maxConcurrency = this.config.get('daemon.max_parallel_actions') || 3;
234
+ const taskTimeoutMs = (this.config.get('daemon.action_timeout_minutes') || 120) * 60 * 1000;
235
+ this.supervisor = new this.deps.AgentSupervisor({
236
+ maxConcurrency,
237
+ taskStore: this.taskStore,
238
+ taskTimeout: taskTimeoutMs,
239
+ environment: this.config.workerEnvironment?.(),
240
+ });
241
+ this.supervisor.on('task:started', (e) => this.log(`Agent task started: ${e.taskId} (PID ${e.pid})`));
242
+ this.supervisor.on('task:completed', (e) => this.log(`Agent task completed: ${e.taskId} (${e.duration}ms)`));
243
+ this.supervisor.on('task:failed', (e) => this.log(`Agent task failed: ${e.taskId} - ${e.error}`));
244
+ this.supervisor.on('task:timeout', (e) => this.log(`Agent task timed out: ${e.taskId}`));
245
+ this.log(`Agent supervisor started (max ${maxConcurrency} concurrent)`);
246
+
247
+ // Wrap AgentSupervisor with DaemonSupervisor for production governance
248
+ const supConfig = this.config.get('supervisor') || {};
249
+ this.daemonSupervisor = new this.deps.DaemonSupervisor({
250
+ agentSupervisor: this.supervisor,
251
+ maxConcurrent: supConfig.max_concurrent ?? maxConcurrency,
252
+ maxQueueDepth: supConfig.max_queue_depth ?? 20,
253
+ dailyBudgetUsd: supConfig.daily_budget_usd ?? 0,
254
+ restartIntensity: {
255
+ maxRestarts: supConfig.restart_intensity?.max_restarts ?? 3,
256
+ windowMs: (supConfig.restart_intensity?.window_seconds ?? 300) * 1000,
257
+ },
258
+ circuitBreaker: supConfig.circuit_breaker,
259
+ });
260
+ this.daemonSupervisor.on('loop:started', (e) => this.log(`Loop started: ${e.loopId}`));
261
+ this.daemonSupervisor.on('loop:completed', (e) => this.log(`Loop completed: ${e.loopId}`));
262
+ this.daemonSupervisor.on('loop:failed', (e) => this.log(`Loop failed: ${e.loopId} (permanent: ${e.permanent})`));
263
+ this.daemonSupervisor.on('circuit:trip', (e) => this.log(`Circuit breaker tripped: ${e.consecutiveFailures} failures`));
264
+ this.daemonSupervisor.on('budget:warning', (e) => this.log(`Budget warning: ${e.percentUsed}% used`));
265
+ this.log('DaemonSupervisor initialized');
266
+
267
+ // Load behavior registry
268
+ try {
269
+ const projectRoot = process.cwd();
270
+ this.behaviorRegistry = new this.deps.BehaviorRegistry({
271
+ projectRoot,
272
+ frameworkRoot: projectRoot,
273
+ });
274
+ const behaviors = await this.behaviorRegistry.loadAll();
275
+ this.log(`Behavior registry loaded ${behaviors.size} behavior(s)`);
276
+ } catch (err) {
277
+ this.log(`Behavior registry init failed (non-fatal): ${err.message}`);
278
+ }
279
+
280
+ // Load and activate daemon behaviors (injectable orchestrators)
281
+ try {
282
+ this.behaviorLoader = new this.deps.DaemonBehaviorLoader({
283
+ projectRoot: process.cwd(),
284
+ supervisor: this.supervisor,
285
+ memoryManager: this.memoryManager,
286
+ provider: this.config.get('provider') || null,
287
+ config: this.config,
288
+ });
289
+ const active = await this.behaviorLoader.loadAll();
290
+ if (active.size > 0) {
291
+ this.log(`Daemon behaviors activated: ${[...active.keys()].join(', ')}`);
292
+ }
293
+ } catch (err) {
294
+ this.log(`Behavior loader init failed (non-fatal): ${err.message}`);
295
+ }
296
+
297
+ // Initialize MessageRouter
298
+ this.messageRouter = new this.deps.MessageRouter({ supervisor: this.supervisor });
299
+ this.log('MessageRouter initialized');
300
+
301
+ // Initialize automation engine (trigger-action rules)
302
+ this.automationEngine = new this.deps.AutomationEngine({
303
+ supervisor: this.supervisor,
304
+ });
305
+ const rules = this.config.get('rules') || [];
306
+ if (rules.length > 0) {
307
+ this.automationEngine.loadRules(rules);
308
+ this.log(`Automation engine loaded ${this.automationEngine.ruleCount} rules`);
309
+ }
310
+
311
+ // Initialize IPC server (Unix domain socket for CLI communication)
312
+ this.ipcServer = new IPCServer(this.socketPath);
313
+ this._registerIPCMethods();
314
+ await this.ipcServer.start();
315
+ this.log(`IPC server listening on ${this.socketPath}`);
316
+
317
+ const watchConfig = this.config.get('watch');
318
+ if (watchConfig?.enabled) {
319
+ this.fileWatcher = new FileWatcher(watchConfig, watchConfig.debounce_ms, {
320
+ deliver: event => this.eventRouter.deliver(event)
321
+ });
322
+ this.fileWatcher.on('delivery-failed', ({ error }) => this.log(`Watcher recovery required: ${error.message}`));
323
+ this.log('File watcher started');
324
+ }
325
+
326
+ // Initialize RoomManager for multi-room messaging
327
+ try {
328
+ const { RoomManager } = await import('../messaging/room-manager.mjs');
329
+ this.roomManager = new RoomManager();
330
+ const messagingConfig = this.config.get('messaging');
331
+ if (messagingConfig) {
332
+ this.roomManager.loadFromConfig(Object.fromEntries(Object.entries(messagingConfig)
333
+ .map(([name, settings]) => [name, { rooms: settings?.rooms }])));
334
+ this.log(`RoomManager loaded ${this.roomManager.size} room(s)`);
335
+ }
336
+ } catch (error) {
337
+ this.log(`RoomManager init failed (non-fatal): ${error.message}`);
338
+ }
339
+
340
+ // Initialize messaging subsystem if any adapters are configured
341
+ try {
342
+ const adapterConfigs = Object.fromEntries(['telegram', 'discord', 'slack']
343
+ .map(name => [name, this.config.recipientConfig?.(name)]).filter(([, value]) => value));
344
+ this.messagingBus = await this.deps.createMessagingHub({
345
+ roomManager: this.roomManager,
346
+ adapterConfigs,
347
+ environment: this.config.workerEnvironment?.(),
348
+ });
349
+ if (this.messagingBus) {
350
+ this.log(`Messaging hub initialized with ${this.messagingBus.adapterCount} adapter(s)`);
351
+ }
352
+ } catch (error) {
353
+ this.log(`Messaging subsystem not available: ${error.message}`);
354
+ }
355
+
356
+ // Initialize ScheduledTaskRunner to bridge cron events to tasks
357
+ if (this.daemonSupervisor && this.eventRouter) {
358
+ this.scheduledTaskRunner = new this.deps.ScheduledTaskRunner({
359
+ supervisor: this.daemonSupervisor,
360
+ eventRouter: this.eventRouter,
361
+ roomManager: this.roomManager,
362
+ taskStore: this.taskStore,
363
+ environment: this.config.workerEnvironment?.(),
364
+ });
365
+ this.scheduledTaskRunner.on('recovery-required', ({ error }) => this.log(`Scheduled task recovery required: ${error.message}`));
366
+ this.scheduledTaskRunner.start();
367
+ this.log('ScheduledTaskRunner started');
368
+ }
369
+
370
+ const scheduleConfig = this.config.get('schedule');
371
+ if (scheduleConfig?.enabled) {
372
+ this.cronScheduler = new CronScheduler(scheduleConfig, { taskStore: this.taskStore });
373
+ this.cronScheduler.on('event', (event) => this.eventRouter.route(event));
374
+ this.cronScheduler.on('recovery-required', ({ jobId, error }) => this.log(`Schedule ${jobId} recovery required: ${error.message}`));
375
+ this.cronScheduler.start();
376
+ this.log('Cron scheduler started');
377
+ }
378
+
379
+ // Initialize AutonomousEngine if enabled
380
+ const modesConfig = this.config.get('modes');
381
+ if (modesConfig?.autonomous && this.daemonSupervisor) {
382
+ this.autonomousEngine = new this.deps.AutonomousEngine({
383
+ supervisor: this.daemonSupervisor,
384
+ config: modesConfig.autonomous,
385
+ roomManager: this.roomManager,
386
+ });
387
+ if (modesConfig.autonomous.enabled) {
388
+ this.autonomousEngine.start();
389
+ this.log('AutonomousEngine started');
390
+ } else {
391
+ this.log('AutonomousEngine initialized (disabled — enable via config or IPC)');
392
+ }
393
+ }
394
+
395
+ // Initialize ProviderWatcher if configured
396
+ const providerWatchConfig = this.config.get('provider_watch');
397
+ if (providerWatchConfig?.enabled) {
398
+ this.providerWatcher = new this.deps.ProviderWatcher({
399
+ stateDir: '.aiwg/daemon/provider-watch',
400
+ providers: providerWatchConfig.providers || undefined,
401
+ intervalHours: providerWatchConfig.interval_hours || 6,
402
+ environment: this.config.workerEnvironment?.(),
403
+ });
404
+ this.providerWatcher.on('changes-detected', (e) => {
405
+ this.log(`Provider changes detected: ${e.changes.length} change(s)`);
406
+ this.eventRouter.route({
407
+ source: 'provider-watch',
408
+ type: 'provider.changes',
409
+ payload: e,
410
+ });
411
+ });
412
+ this.providerWatcher.on('error', (e) => {
413
+ this.log(`Provider watcher error (${e.provider}): ${e.error}`);
414
+ });
415
+ this.providerWatcher.start();
416
+
417
+ // Register default automation rule for PR creation on provider changes
418
+ if (this.automationEngine) {
419
+ const existingRule = this.automationEngine.getRule('provider-watch-pr');
420
+ if (!existingRule) {
421
+ const prRule = ProviderWatcher.getAutomationRule();
422
+ this.automationEngine.loadRules([
423
+ ...this.automationEngine.rules,
424
+ prRule,
425
+ ]);
426
+ this.log('Registered provider-watch-pr automation rule');
427
+ }
428
+ }
429
+
430
+ this.log(`ProviderWatcher initialized (${this.providerWatcher.providers.length} providers, every ${this.providerWatcher.intervalHours}h)`);
431
+ }
432
+
433
+ // Start web server if configured
434
+ const webConfig = this.config.recipientConfig?.('web') ?? this.config.get('interface.web');
435
+ if (webConfig?.enabled) {
436
+ // In Docker mode, bind to 0.0.0.0 so port mapping works
437
+ const webHost = process.env.AIWG_DOCKER === '1' ? '0.0.0.0' : (webConfig.host ?? '127.0.0.1');
438
+ this.webServer = new this.deps.WebServer({
439
+ port: webConfig.port ?? 7474,
440
+ host: webHost,
441
+ token: webConfig.token || null,
442
+ daemonSupervisor: this.daemonSupervisor,
443
+ opsHandlers: this.opsHandlersApi,
444
+ });
445
+ await this.webServer.start();
446
+ this.log(`Web server listening on ${this.webServer.url}`);
447
+ }
448
+
449
+ // Route events through automation engine and adapters
450
+ this.eventRouter.on('event', (event) => {
451
+ this.handleEvent(event);
452
+ return this.automationEngine.processEvent(event);
453
+ });
454
+ this.fileWatcher?.start();
455
+
456
+ // Forward DaemonSupervisor events to MessageRouter and WebServer
457
+ if (this.daemonSupervisor) {
458
+ for (const eventName of ['loop:started', 'loop:completed', 'loop:failed', 'loop:queued', 'circuit:trip', 'circuit:recover', 'budget:warning']) {
459
+ this.daemonSupervisor.on(eventName, (data) => {
460
+ if (this.messageRouter) {
461
+ this.messageRouter.broadcast({ type: eventName, data });
462
+ }
463
+ if (this.webServer) {
464
+ this.webServer.broadcastEvent(eventName, data);
465
+ }
466
+ });
467
+ }
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Minimal housekeeper profile (epic #3353 B5, design note §1.1).
473
+ *
474
+ * Loads only Config (already loaded), EventRouter, TaskStore, FileWatcher,
475
+ * CronScheduler, the deterministic ScheduledTaskRunner (maintenance jobs,
476
+ * no prompts, no supervisor) and the minimal IPC subset. Never constructs
477
+ * the conversational stack (MemoryManager, AgentSupervisor,
478
+ * DaemonSupervisor, behaviors, MessageRouter, AutomationEngine, rooms /
479
+ * messaging, AutonomousEngine, ProviderWatcher, WebServer) and registers
480
+ * none of their IPC methods, so no model calls are possible here.
481
+ */
482
+ async initializeHousekeeperSubsystems() {
483
+ this.eventRouter = new EventRouter();
484
+
485
+ // Task store doubles as the persisted receipt substrate for schedules.
486
+ this.taskStore = new TaskStore(this.taskStorePath);
487
+ await this.taskStore.initialize();
488
+ this.log(`Task store initialized (${this.taskStore.size} existing tasks)`);
489
+
490
+ // Minimal IPC subset: ping, daemon.status, schedule.status, the
491
+ // housekeeper.* methods, and read-only task.list/get/stats.
492
+ this.ipcServer = new IPCServer(this.socketPath);
493
+ this._registerHousekeeperIPCMethods();
494
+ await this.ipcServer.start();
495
+ this.log(`IPC server listening on ${this.socketPath}`);
496
+
497
+ // B6 resource bounds: validated once here; the runner and watcher enforce
498
+ // the normalized values (concurrency, queue, timeout ceiling, niceness,
499
+ // watch-handle cap). Invalid blocks fail startup loudly, never silently.
500
+ const { config: resources, errors: resourceErrors } = normalizeResources(this.config.get('resources'));
501
+ if (resourceErrors.length > 0) throw new Error(`Invalid resources: ${resourceErrors.join('; ')}`);
502
+ this.resources = resources;
503
+
504
+ const watchConfig = this.config.get('watch');
505
+ if (watchConfig?.enabled) {
506
+ this.fileWatcher = new FileWatcher(watchConfig, watchConfig.debounce_ms, {
507
+ deliver: event => this.eventRouter.deliver(event),
508
+ maxHandles: resources.maxWatchHandles,
509
+ });
510
+ this.fileWatcher.on('delivery-failed', ({ error }) => this.log(`Watcher recovery required: ${error.message}`));
511
+ this.log('File watcher started');
512
+ }
513
+
514
+ // Deterministic dispatcher: maintenance owner operations only. No
515
+ // supervisor is passed, so legacy prompt-based actions cannot run.
516
+ this.scheduledTaskRunner = new this.deps.ScheduledTaskRunner({
517
+ eventRouter: this.eventRouter,
518
+ taskStore: this.taskStore,
519
+ resources,
520
+ environment: this.config.workerEnvironment?.(),
521
+ });
522
+ this.scheduledTaskRunner.on('recovery-required', ({ error }) => this.log(`Scheduled task recovery required: ${error.message}`));
523
+ this.scheduledTaskRunner.start();
524
+ this.log('ScheduledTaskRunner started (housekeeper maintenance jobs)');
525
+
526
+ const scheduleConfig = this.config.get('schedule');
527
+ if (scheduleConfig?.enabled) {
528
+ this.cronScheduler = new CronScheduler(scheduleConfig, { taskStore: this.taskStore });
529
+ this.cronScheduler.on('event', (event) => this.eventRouter.route(event));
530
+ this.cronScheduler.on('recovery-required', ({ jobId, error }) => this.log(`Schedule ${jobId} recovery required: ${error.message}`));
531
+ this.cronScheduler.start();
532
+ this.log('Cron scheduler started');
533
+ }
534
+
535
+ // Housekeeper events fan out read-only: no automation engine, no
536
+ // messaging bus, no supervisor broadcast.
537
+ this.eventRouter.on('event', (event) => this.handleEvent(event));
538
+ this.fileWatcher?.start();
539
+ }
540
+
541
+ /**
542
+ * Null-safe daemon status payload shared by both profiles. Absent
543
+ * subsystems report as disabled instead of throwing, so the housekeeper
544
+ * profile (which never constructs them) still answers daemon.status.
545
+ */
546
+ _daemonStatusPayload() {
547
+ return {
548
+ pid: process.pid,
549
+ uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),
550
+ started_at: new Date(this.startTime).toISOString(),
551
+ health: 'healthy',
552
+ profile: this.config.get('daemon.profile') || 'default',
553
+ subsystems: {
554
+ ipc: { clients: this.ipcServer.clientCount },
555
+ supervisor: this.supervisor ? this.supervisor.getStatus() : { enabled: false },
556
+ automation: this.automationEngine ? this.automationEngine.getStatus() : { enabled: false },
557
+ file_watcher: this.fileWatcher?.getStats() || { enabled: false },
558
+ scheduler: this.cronScheduler?.getStats() || { enabled: false },
559
+ messaging: this.messagingBus ? { enabled: true, adapters: this.messagingBus.adapterCount } : { enabled: false },
560
+ provider_watcher: this.providerWatcher ? { enabled: true, ...this.providerWatcher.getStatus() } : { enabled: false },
561
+ behaviors: this.behaviorLoader ? this.behaviorLoader.getStatus() : { active: {}, count: 0 },
562
+ },
563
+ };
564
+ }
565
+
566
+ /**
567
+ * Housekeeper status section (design note §6 HousekeeperStatus).
568
+ * Freshness probes are best-effort: when the compiled index surface is
569
+ * unavailable the section reports an empty list rather than failing.
570
+ */
571
+ async getHousekeeperStatus() {
572
+ const schedules = this.taskStore ? this.taskStore.getSchedules() : [];
573
+ const jobs = schedules.map(record => ({
574
+ id: record.job.id,
575
+ kind: record.job.kind || null,
576
+ lastState: record.lastReceipt?.state || 'never',
577
+ lastRun: record.lastRun || null,
578
+ nextFire: record.nextRun || null,
579
+ }));
580
+ let freshness = [];
581
+ try {
582
+ const { importImpl } = await import('../_resolve-impl.mjs');
583
+ const { collectIndexStatus } = await importImpl(import.meta.url, 'artifacts/index-status.js');
584
+ const report = collectIndexStatus(process.cwd(), Date.now());
585
+ freshness = (report.indices || []).map(index => ({
586
+ index: index.name,
587
+ state: index.status,
588
+ targetMs: index.policy?.targetStaleAfterMs ?? null,
589
+ converged: index.convergence?.converged ?? null,
590
+ }));
591
+ } catch {
592
+ freshness = [];
593
+ }
594
+ const updateReceipts = schedules
595
+ .filter(record => record.job.kind === 'update.check')
596
+ .map(record => record.lastReceipt)
597
+ .filter(Boolean);
598
+ const lastCheck = updateReceipts.length
599
+ ? updateReceipts.map(receipt => receipt.finishedAt).sort().pop()
600
+ : null;
601
+ const available = updateReceipts.length
602
+ ? updateReceipts.map(receipt => receipt.detail?.available ?? null).pop() ?? null
603
+ : null;
604
+ const channel = updateReceipts.length
605
+ ? updateReceipts.map(receipt => receipt.detail?.channel || 'stable').pop()
606
+ : 'stable';
607
+ // B6 recovery reporting: the latest install outcome (old/new version,
608
+ // success/failure, rollback) surfaces here; uncertain outcomes stay on
609
+ // the schedule-recovery-required path and are never auto-retried.
610
+ const installReceipts = schedules
611
+ .filter(record => record.job.kind === 'update.install')
612
+ .map(record => record.lastReceipt)
613
+ .filter(Boolean);
614
+ const last = installReceipts.length
615
+ ? installReceipts.sort((a, b) => (a.finishedAt < b.finishedAt ? -1 : 1)).pop()
616
+ : null;
617
+ return {
618
+ profile: 'housekeeper',
619
+ pid: process.pid,
620
+ uptimeSeconds: Math.floor((Date.now() - this.startTime) / 1000),
621
+ jobs,
622
+ freshness,
623
+ update: { channel, checkOnly: true, lastCheck, available,
624
+ lastInstall: last ? { state: last.state, reason: last.reason || null,
625
+ finishedAt: last.finishedAt, summary: last.summary,
626
+ oldVersion: last.detail?.oldVersion ?? null,
627
+ newVersion: last.detail?.newVersion ?? null } : null },
628
+ };
629
+ }
630
+
631
+ /**
632
+ * Minimal IPC subset for the housekeeper profile (design note §1.1):
633
+ * ping, daemon.status, schedule.status, housekeeper.* plus read-only
634
+ * task.list/get/stats over the receipt store. Conversational methods
635
+ * (chat.send, memory.*, behaviors.*, autonomous.*, task.submit/cancel,
636
+ * automation.*, provider-watch.*, rooms.*) are never registered here.
637
+ */
638
+ _registerHousekeeperIPCMethods() {
639
+ this.ipcServer.registerMethods({
640
+ 'ping': () => ({ pong: true, timestamp: new Date().toISOString() }),
641
+
642
+ 'daemon.status': () => this._daemonStatusPayload(),
643
+
644
+ 'schedule.status': () => {
645
+ return this.scheduledTaskRunner ? this.scheduledTaskRunner.getStatus() : { started: false };
646
+ },
647
+
648
+ 'housekeeper.status': () => this.getHousekeeperStatus(),
649
+
650
+ 'housekeeper.jobs': () => {
651
+ const schedules = this.taskStore ? this.taskStore.getSchedules() : [];
652
+ return {
653
+ jobs: schedules.map(record => ({
654
+ id: record.job.id,
655
+ kind: record.job.kind || null,
656
+ state: record.state,
657
+ lastReceipt: record.lastReceipt || null,
658
+ nextRun: record.nextRun || null,
659
+ })),
660
+ };
661
+ },
662
+
663
+ 'task.list': (params) => {
664
+ return this.taskStore.getTasks({
665
+ state: params?.state,
666
+ limit: params?.limit || 20,
667
+ });
668
+ },
669
+
670
+ 'task.get': (params) => {
671
+ if (!params.taskId) {
672
+ const err = new Error('Missing required parameter: taskId');
673
+ err.code = 'INVALID_PARAMS';
674
+ throw err;
675
+ }
676
+ const task = this.taskStore.getTask(params.taskId);
677
+ if (!task) {
678
+ const err = new Error(`Task not found: ${params.taskId}`);
679
+ err.code = 'INVALID_PARAMS';
680
+ throw err;
681
+ }
682
+ return task;
683
+ },
684
+
685
+ 'task.stats': () => {
686
+ return this.taskStore.getStats();
687
+ },
688
+ });
689
+ }
690
+
691
+ /**
692
+ * Register IPC method handlers for CLI communication
693
+ */
694
+ _registerIPCMethods() {
695
+ this.ipcServer.registerMethods({
696
+ // Daemon status
697
+ 'daemon.status': () => this._daemonStatusPayload(),
698
+
699
+ // Task management
700
+ 'task.submit': (params) => {
701
+ if (!params.prompt) {
702
+ const err = new Error('Missing required parameter: prompt');
703
+ err.code = 'INVALID_PARAMS';
704
+ throw err;
705
+ }
706
+ const task = this.supervisor.submit(params.prompt, {
707
+ agent: params.agent,
708
+ priority: params.priority || 0,
709
+ });
710
+ return { taskId: task.id, state: task.state };
711
+ },
712
+
713
+ 'task.cancel': (params) => {
714
+ if (!params.taskId) {
715
+ const err = new Error('Missing required parameter: taskId');
716
+ err.code = 'INVALID_PARAMS';
717
+ throw err;
718
+ }
719
+ const cancelled = this.supervisor.cancel(params.taskId);
720
+ return { cancelled };
721
+ },
722
+
723
+ 'task.list': (params) => {
724
+ return this.taskStore.getTasks({
725
+ state: params?.state,
726
+ limit: params?.limit || 20,
727
+ });
728
+ },
729
+
730
+ 'task.get': (params) => {
731
+ if (!params.taskId) {
732
+ const err = new Error('Missing required parameter: taskId');
733
+ err.code = 'INVALID_PARAMS';
734
+ throw err;
735
+ }
736
+ const task = this.taskStore.getTask(params.taskId);
737
+ if (!task) {
738
+ const err = new Error(`Task not found: ${params.taskId}`);
739
+ err.code = 'INVALID_PARAMS';
740
+ throw err;
741
+ }
742
+ return task;
743
+ },
744
+
745
+ 'task.stats': () => {
746
+ return this.taskStore.getStats();
747
+ },
748
+
749
+ // Automation
750
+ 'automation.status': () => {
751
+ return this.automationEngine.getStatus();
752
+ },
753
+
754
+ 'automation.enable': (params) => {
755
+ if (params.ruleId) {
756
+ return { success: this.automationEngine.setRuleEnabled(params.ruleId, true) };
757
+ }
758
+ this.automationEngine.setEnabled(true);
759
+ return { enabled: true };
760
+ },
761
+
762
+ 'automation.disable': (params) => {
763
+ if (params.ruleId) {
764
+ return { success: this.automationEngine.setRuleEnabled(params.ruleId, false) };
765
+ }
766
+ this.automationEngine.setEnabled(false);
767
+ return { enabled: false };
768
+ },
769
+
770
+ // Chat (send message via IPC for non-tmux clients)
771
+ // Routes through active chat-message behaviors when available.
772
+ 'chat.send': async (params) => {
773
+ if (!params.message) {
774
+ const err = new Error('Missing required parameter: message');
775
+ err.code = 'INVALID_PARAMS';
776
+ throw err;
777
+ }
778
+ // Route through behaviors registered for chat-message trigger
779
+ if (this.behaviorLoader && !params.raw) {
780
+ const handlers = this.behaviorLoader.getForTrigger('chat-message');
781
+ for (const handler of handlers) {
782
+ if (typeof handler.handleMessage === 'function') {
783
+ try {
784
+ return await handler.handleMessage(params.message, {
785
+ source: 'ipc-chat',
786
+ provider: params.provider,
787
+ });
788
+ } catch (err) {
789
+ this.log(`Behavior chat handler error (falling back): ${err.message}`);
790
+ }
791
+ }
792
+ }
793
+ }
794
+ // Fallback: direct supervisor submit (no behavior mediation)
795
+ const task = this.supervisor.submit(params.message, {
796
+ priority: params.priority || 5,
797
+ metadata: { source: 'ipc-chat' },
798
+ });
799
+ return { taskId: task.id };
800
+ },
801
+
802
+ // Ping for health checks
803
+ 'ping': () => ({ pong: true, timestamp: new Date().toISOString() }),
804
+
805
+ // Memory management (cross-session context)
806
+ 'memory.show': (params) => {
807
+ if (!this.memoryManager) return { error: 'Memory manager not initialized', available: false };
808
+ return this.memoryManager.show(params?.scope);
809
+ },
810
+
811
+ 'memory.clear': (params) => {
812
+ if (!this.memoryManager) return { error: 'Memory manager not initialized', available: false };
813
+ const scope = params?.scope;
814
+ if (!scope) {
815
+ const err = new Error('Missing required parameter: scope');
816
+ err.code = 'INVALID_PARAMS';
817
+ throw err;
818
+ }
819
+ return this.memoryManager.clear(scope);
820
+ },
821
+
822
+ 'memory.write': (params) => {
823
+ if (!this.memoryManager) return { error: 'Memory manager not initialized', available: false };
824
+ const { scope, key, content, name, description, type } = params || {};
825
+ if (!scope || !key || !content) {
826
+ const err = new Error('Missing required parameters: scope, key, content');
827
+ err.code = 'INVALID_PARAMS';
828
+ throw err;
829
+ }
830
+ return this.memoryManager.write(scope, key, content, { name, description, type });
831
+ },
832
+
833
+ 'memory.context': () => {
834
+ if (!this.memoryManager) return { context: '', available: false };
835
+ return { context: this.memoryManager.getContext(), available: true };
836
+ },
837
+
838
+ // Behavior management (injectable daemon behaviors)
839
+ 'behaviors.status': () => {
840
+ return this.behaviorLoader ? this.behaviorLoader.getStatus() : { active: {}, count: 0 };
841
+ },
842
+
843
+ 'behaviors.list': () => {
844
+ if (!this.behaviorLoader) return { behaviors: [] };
845
+ const status = this.behaviorLoader.getStatus();
846
+ return { behaviors: Object.entries(status.active).map(([name, info]) => ({ name, ...info })) };
847
+ },
848
+
849
+ 'behaviors.apply': async (params) => {
850
+ if (!params?.name) {
851
+ const err = new Error('Missing required parameter: name');
852
+ err.code = 'INVALID_PARAMS';
853
+ throw err;
854
+ }
855
+ if (!this.behaviorLoader) {
856
+ const err = new Error('Behavior loader not initialized');
857
+ err.code = 'INVALID_STATE';
858
+ throw err;
859
+ }
860
+ return await this.behaviorLoader.apply(params.name);
861
+ },
862
+
863
+ 'behaviors.remove': (params) => {
864
+ if (!params?.name) {
865
+ const err = new Error('Missing required parameter: name');
866
+ err.code = 'INVALID_PARAMS';
867
+ throw err;
868
+ }
869
+ if (!this.behaviorLoader) {
870
+ return { removed: false, name: params.name };
871
+ }
872
+ return this.behaviorLoader.remove(params.name);
873
+ },
874
+
875
+ // Autonomous mode management
876
+ 'autonomous.status': () => {
877
+ return this.autonomousEngine ? this.autonomousEngine.getStatus() : { enabled: false };
878
+ },
879
+
880
+ 'autonomous.enable': () => {
881
+ if (!this.autonomousEngine) {
882
+ const err = new Error('Autonomous engine not initialized');
883
+ err.code = 'INVALID_STATE';
884
+ throw err;
885
+ }
886
+ this.autonomousEngine.enable();
887
+ return { enabled: true };
888
+ },
889
+
890
+ 'autonomous.disable': () => {
891
+ if (!this.autonomousEngine) {
892
+ const err = new Error('Autonomous engine not initialized');
893
+ err.code = 'INVALID_STATE';
894
+ throw err;
895
+ }
896
+ this.autonomousEngine.disable();
897
+ return { enabled: false };
898
+ },
899
+
900
+ // Scheduled task runner
901
+ 'schedule.status': () => {
902
+ return this.scheduledTaskRunner ? this.scheduledTaskRunner.getStatus() : { started: false };
903
+ },
904
+
905
+ // Provider watch
906
+ 'provider-watch.status': () => {
907
+ return this.providerWatcher ? this.providerWatcher.getStatus() : { enabled: false };
908
+ },
909
+
910
+ 'provider-watch.check': async () => {
911
+ if (!this.providerWatcher) {
912
+ const err = new Error('Provider watcher not initialized — enable provider_watch in daemon config');
913
+ err.code = 'INVALID_STATE';
914
+ throw err;
915
+ }
916
+ const changes = await this.providerWatcher.checkAll();
917
+ return { changes, count: changes.length };
918
+ },
919
+
920
+ // Room management
921
+ 'rooms.list': () => {
922
+ return this.roomManager ? this.roomManager.getStatus() : { totalRooms: 0 };
923
+ },
924
+ });
925
+
926
+ // Register ops-toolset IPC methods
927
+ if (this.daemonSupervisor) {
928
+ this.opsHandlersApi = registerOpsHandlers(this.ipcServer, this.daemonSupervisor);
929
+ this.log('Ops-toolset IPC methods registered (7 methods)');
930
+ }
931
+ }
932
+
933
+ handleEvent(event) {
934
+ this.log(`Event received: ${event.source} - ${event.type}`);
935
+
936
+ // Forward daemon events to messaging bus if available
937
+ if (this.messagingBus) {
938
+ this.messagingBus.publish({
939
+ topic: event.type,
940
+ source: event.source || 'daemon',
941
+ severity: 'info',
942
+ summary: `${event.source}: ${event.type}`,
943
+ details: event.payload || {},
944
+ project: path.basename(process.cwd()),
945
+ timestamp: new Date().toISOString(),
946
+ });
947
+ }
948
+ }
949
+
950
+ startHeartbeat() {
951
+ const intervalSeconds = this.config.get('daemon.heartbeat_interval_seconds') || 30;
952
+
953
+ setInterval(() => {
954
+ this.writeHeartbeat();
955
+ this.writeState();
956
+ }, intervalSeconds * 1000);
957
+
958
+ this.writeHeartbeat();
959
+ this.writeState();
960
+ }
961
+
962
+ writeHeartbeat() {
963
+ const heartbeat = {
964
+ pid: process.pid,
965
+ timestamp: new Date().toISOString(),
966
+ uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000)
967
+ };
968
+
969
+ const tmpFile = `${this.heartbeatFile}.tmp`;
970
+ fs.writeFileSync(tmpFile, JSON.stringify(heartbeat, null, 2));
971
+ fs.renameSync(tmpFile, this.heartbeatFile);
972
+ }
973
+
974
+ writeState() {
975
+ const supervisorStatus = this.supervisor ? this.supervisor.getStatus() : { running: 0, queued: 0, tasks: { running: [], queued: [] } };
976
+ const daemonStatus = this.daemonSupervisor ? this.daemonSupervisor.status() : null;
977
+ const taskStats = this.taskStore ? this.taskStore.getStats() : {};
978
+
979
+ const state = {
980
+ pid: process.pid,
981
+ started_at: new Date(this.startTime).toISOString(),
982
+ last_heartbeat: new Date().toISOString(),
983
+ uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),
984
+ restart_count: 0,
985
+ ipc: {
986
+ socket: this.socketPath,
987
+ clients: this.ipcServer ? this.ipcServer.clientCount : 0,
988
+ },
989
+ agents: {
990
+ running: supervisorStatus.running,
991
+ queued: supervisorStatus.queued,
992
+ max_concurrency: supervisorStatus.maxConcurrency,
993
+ tasks: supervisorStatus.tasks,
994
+ },
995
+ task_stats: taskStats,
996
+ monitors: {
997
+ file_watcher: this.fileWatcher?.getStats() || { enabled: false },
998
+ webhook: { enabled: false },
999
+ scheduler: this.cronScheduler?.getStats() || { enabled: false }
1000
+ },
1001
+ automation: this.automationEngine ? {
1002
+ enabled: this.automationEngine.enabled,
1003
+ rule_count: this.automationEngine.ruleCount,
1004
+ } : { enabled: false },
1005
+ daemon_supervisor: daemonStatus ? {
1006
+ concurrency: `${daemonStatus.concurrencyUsed}/${daemonStatus.concurrencyMax}`,
1007
+ queue: `${daemonStatus.queueDepth}/${daemonStatus.queueMax}`,
1008
+ circuit: daemonStatus.circuitState?.state || 'unknown',
1009
+ budget: daemonStatus.budgetLimit > 0
1010
+ ? `$${daemonStatus.budgetUsed.toFixed(2)}/$${daemonStatus.budgetLimit.toFixed(2)}`
1011
+ : 'unlimited',
1012
+ } : null,
1013
+ web_server: this.webServer ? { url: this.webServer.url } : null,
1014
+ rooms: this.roomManager ? this.roomManager.getStatus() : null,
1015
+ scheduled_tasks: this.scheduledTaskRunner ? this.scheduledTaskRunner.getStatus() : null,
1016
+ autonomous: this.autonomousEngine ? this.autonomousEngine.getStatus() : null,
1017
+ health: {
1018
+ status: 'healthy',
1019
+ last_check: new Date().toISOString(),
1020
+ issues: []
1021
+ }
1022
+ };
1023
+
1024
+ const tmpFile = `${this.stateFile}.tmp`;
1025
+ fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2));
1026
+ fs.renameSync(tmpFile, this.stateFile);
1027
+ }
1028
+
1029
+ stopSubsystems() {
1030
+ if (this.fileWatcher) {
1031
+ this.fileWatcher.stop();
1032
+ this.fileWatcher = null;
1033
+ }
1034
+
1035
+ if (this.cronScheduler) {
1036
+ this.cronScheduler.stop();
1037
+ this.cronScheduler = null;
1038
+ }
1039
+
1040
+ if (this.scheduledTaskRunner) {
1041
+ this.scheduledTaskRunner.stop();
1042
+ this.scheduledTaskRunner = null;
1043
+ }
1044
+
1045
+ if (this.autonomousEngine) {
1046
+ this.autonomousEngine.stop();
1047
+ this.autonomousEngine = null;
1048
+ }
1049
+
1050
+ if (this.providerWatcher) {
1051
+ this.providerWatcher.stop();
1052
+ this.providerWatcher = null;
1053
+ }
1054
+
1055
+ if (this.behaviorLoader) {
1056
+ this.behaviorLoader = null;
1057
+ }
1058
+ }
1059
+
1060
+ async shutdown(signal) {
1061
+ if (this.shutdownInProgress) {
1062
+ return;
1063
+ }
1064
+
1065
+ this.shutdownInProgress = true;
1066
+ this.log(`Shutdown initiated (${signal})`);
1067
+
1068
+ // Stop IPC server (reject new connections)
1069
+ if (this.ipcServer) {
1070
+ try {
1071
+ await this.ipcServer.stop();
1072
+ this.log('IPC server stopped');
1073
+ } catch (error) {
1074
+ this.log(`Error stopping IPC server: ${error.message}`);
1075
+ }
1076
+ }
1077
+
1078
+ // Stop web server
1079
+ if (this.webServer) {
1080
+ try {
1081
+ await this.webServer.stop();
1082
+ this.log('Web server stopped');
1083
+ } catch (error) {
1084
+ this.log(`Error stopping web server: ${error.message}`);
1085
+ }
1086
+ }
1087
+
1088
+ // Drain DaemonSupervisor (which delegates to AgentSupervisor)
1089
+ if (this.daemonSupervisor) {
1090
+ try {
1091
+ await this.daemonSupervisor.shutdown(15000);
1092
+ this.log('DaemonSupervisor drained');
1093
+ } catch (error) {
1094
+ this.log(`Error draining DaemonSupervisor: ${error.message}`);
1095
+ }
1096
+ } else if (this.supervisor) {
1097
+ try {
1098
+ this.log(`Draining supervisor (${this.supervisor.runningCount} running, ${this.supervisor.queuedCount} queued)`);
1099
+ await this.supervisor.shutdown(15000);
1100
+ this.log('Agent supervisor drained');
1101
+ } catch (error) {
1102
+ this.log(`Error draining supervisor: ${error.message}`);
1103
+ }
1104
+ }
1105
+
1106
+ // Shutdown messaging adapters
1107
+ if (this.messagingBus) {
1108
+ try {
1109
+ await this.messagingBus.shutdown();
1110
+ this.log('Messaging hub shut down');
1111
+ } catch (error) {
1112
+ this.log(`Error shutting down messaging: ${error.message}`);
1113
+ }
1114
+ }
1115
+
1116
+ // Flush session memory to project scope before exit
1117
+ if (this.memoryManager) {
1118
+ try {
1119
+ const uptime = Math.floor((Date.now() - this.startTime) / 1000);
1120
+ this.memoryManager.flushSession({ duration: `${uptime}s` });
1121
+ this.log('Session memory flushed to project scope');
1122
+ } catch (error) {
1123
+ this.log(`Memory flush failed (non-fatal): ${error.message}`);
1124
+ }
1125
+ }
1126
+
1127
+ this.stopSubsystems();
1128
+ this.writeState();
1129
+ this.cleanup();
1130
+
1131
+ this.log('Daemon stopped gracefully');
1132
+ process.exit(0);
1133
+ }
1134
+
1135
+ cleanup() {
1136
+ try {
1137
+ if (fs.existsSync(this.pidFile)) {
1138
+ fs.unlinkSync(this.pidFile);
1139
+ }
1140
+ } catch (error) {
1141
+ this.log(`Failed to remove PID file: ${error.message}`);
1142
+ }
1143
+
1144
+ try {
1145
+ if (this.lockFd !== null) {
1146
+ fs.closeSync(this.lockFd);
1147
+ fs.unlinkSync(this.lockFile);
1148
+ }
1149
+ } catch (error) {
1150
+ this.log(`Failed to remove lock file: ${error.message}`);
1151
+ }
1152
+ }
1153
+
1154
+ log(message) {
1155
+ const timestamp = new Date().toISOString();
1156
+ console.log(`[${timestamp}] ${message}`);
1157
+ }
1158
+ }
1159
+
1160
+ const daemon = new DaemonMain();
1161
+ // Importing this module must not start a daemon: unit tests import
1162
+ // DaemonMain to prove the housekeeper profile never constructs the
1163
+ // conversational stack (#3353 B5).
1164
+ if (process.env.AIWG_DAEMON_NO_AUTOSTART !== '1') {
1165
+ daemon.start();
1166
+ }
1167
+
1168
+ export { DaemonMain };
1169
+ export default daemon;