@aiwg/cli 2026.10.15 → 2026.10.16

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 (180) 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 +23 -9
  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/cli/handlers/daemon.js +17 -1
  26. package/dist/src/cli/handlers/doctor-args.js +10 -5
  27. package/dist/src/cli/handlers/doctor-help.js +4 -1
  28. package/dist/src/cli/handlers/index.js +2 -2
  29. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  30. package/dist/src/cli/handlers/models.js +3 -2
  31. package/dist/src/cli/handlers/regenerate.js +8 -16
  32. package/dist/src/cli/handlers/sessions.js +7 -7
  33. package/dist/src/cli/handlers/subcommands.js +8 -0
  34. package/dist/src/cli/handlers/update.js +157 -0
  35. package/dist/src/cli/handlers/use.js +14 -4
  36. package/dist/src/cli/handlers/utilities.js +3 -560
  37. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  38. package/dist/src/cli/services/deployment-verification.js +0 -1
  39. package/dist/src/config/aiwg-config.js +2 -1
  40. package/dist/src/config/authorization-cli.js +7 -3
  41. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  42. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  43. package/dist/src/config/framework-aliases.js +12 -0
  44. package/dist/src/config/host-resource-report.d.mts +19 -0
  45. package/dist/src/config/host-resource-report.mjs +80 -0
  46. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  47. package/dist/src/config/host-resource-runtime.mjs +293 -0
  48. package/dist/src/config/installed-selection.js +22 -0
  49. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  50. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  51. package/dist/src/decision/heldout/access.js +74 -0
  52. package/dist/src/decision/heldout/calibration.js +1 -0
  53. package/dist/src/decision/heldout/collector.js +8 -1
  54. package/dist/src/effects/verifiers/file.js +22 -5
  55. package/dist/src/extensions/claude-attribution.js +82 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  57. package/dist/src/extensions/commands/daemon.js +109 -0
  58. package/dist/src/extensions/commands/definitions.js +5 -89
  59. package/dist/src/gates/heldout.js +17 -7
  60. package/dist/src/lint/check-patterns.js +163 -0
  61. package/dist/src/lint/checks.js +268 -0
  62. package/dist/src/lint/reference-resolution.js +54 -0
  63. package/dist/src/lint/runner.js +3 -465
  64. package/dist/src/mcp/helpers.mjs +11 -1
  65. package/dist/src/memory/project-registry.js +44 -4
  66. package/dist/src/models/worker-plan.js +36 -5
  67. package/dist/src/models/wrapper-deployment.js +25 -12
  68. package/dist/src/models/wrapper-enforcement.js +47 -7
  69. package/dist/src/network-analysis/research.js +2 -1
  70. package/dist/src/policy/hitl-check.js +14 -4
  71. package/dist/src/policy/hitl-consume.js +54 -0
  72. package/dist/src/policy/hitl-receipt.js +2 -0
  73. package/dist/src/policy/hitl.js +11 -3
  74. package/dist/src/providers/provider-context-contracts.js +162 -0
  75. package/dist/src/providers/provider-definition-schema.js +136 -0
  76. package/dist/src/providers/provider-definitions.js +8 -1298
  77. package/dist/src/providers/provider-seeds-1.js +360 -0
  78. package/dist/src/providers/provider-seeds-2.js +387 -0
  79. package/dist/src/providers/provider-seeds-3.js +262 -0
  80. package/dist/src/research/clients/arxiv.js +4 -30
  81. package/dist/src/research/clients/base.js +48 -22
  82. package/dist/src/research/identity.js +34 -2
  83. package/dist/src/research/query-cli.js +3 -87
  84. package/dist/src/research/query-options.js +87 -0
  85. package/dist/src/research/reference-match.js +70 -24
  86. package/dist/src/research/services/acquisition.js +9 -7
  87. package/dist/src/research/services/citation.js +5 -2
  88. package/dist/src/research/types.js +2 -0
  89. package/dist/src/serve/mission-conductor.js +48 -4
  90. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  91. package/dist/src/sessions/adapters/grok-build.js +14 -7
  92. package/dist/src/sessions/workspace-discovery.js +5 -5
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
  94. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  95. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  96. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  97. package/dist/src/smiths/context-pipeline/generator.js +9 -10
  98. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  99. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  100. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  101. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  102. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  103. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  104. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  105. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  106. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  107. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  108. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  109. package/package.json +10 -1
  110. package/schemas/decision/D29Study.v10.schema.json +65 -0
  111. package/tools/agents/deploy-agents.mjs +10 -0
  112. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  113. package/tools/agents/providers/context-write.mjs +4 -0
  114. package/tools/agents/providers/pi.mjs +3 -1
  115. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  116. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  117. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  118. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  119. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  120. package/tools/daemon/README.md +511 -0
  121. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  122. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  123. package/tools/daemon/agent-supervisor.mjs +299 -0
  124. package/tools/daemon/automation-engine.mjs +310 -0
  125. package/tools/daemon/autonomous-engine.mjs +346 -0
  126. package/tools/daemon/behavior-loader.mjs +316 -0
  127. package/tools/daemon/behavior.mjs +174 -0
  128. package/tools/daemon/concierge/intent-router.mjs +401 -0
  129. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  130. package/tools/daemon/concierge/response-translator.mjs +462 -0
  131. package/tools/daemon/config.mjs +377 -0
  132. package/tools/daemon/cron-scheduler.mjs +178 -0
  133. package/tools/daemon/daemon-main.mjs +1169 -0
  134. package/tools/daemon/event-router.mjs +84 -0
  135. package/tools/daemon/file-watcher.mjs +383 -0
  136. package/tools/daemon/index.mjs +1181 -0
  137. package/tools/daemon/init-profile.mjs +124 -0
  138. package/tools/daemon/ipc-client.mjs +197 -0
  139. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  140. package/tools/daemon/ipc-server.mjs +275 -0
  141. package/tools/daemon/maintenance-owner.mjs +79 -0
  142. package/tools/daemon/memory-manager.mjs +386 -0
  143. package/tools/daemon/message-router.mjs +194 -0
  144. package/tools/daemon/provider-watcher.mjs +585 -0
  145. package/tools/daemon/pty-adapter.mjs +420 -0
  146. package/tools/daemon/repl-chat.mjs +359 -0
  147. package/tools/daemon/resource-bounds.mjs +88 -0
  148. package/tools/daemon/sandbox-transport.mjs +295 -0
  149. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  150. package/tools/daemon/task-store.mjs +450 -0
  151. package/tools/daemon/tmux-manager.mjs +324 -0
  152. package/tools/daemon/update-policy.mjs +517 -0
  153. package/tools/daemon/web-server.mjs +399 -0
  154. package/tools/daemon/web-ui/index.html +585 -0
  155. package/tools/daemon/web-ui/styles.css +156 -0
  156. package/tools/docker/Dockerfile.daemon +35 -0
  157. package/tools/docker/container-manager.mjs +291 -0
  158. package/tools/messaging/adapter-registry.mjs +230 -0
  159. package/tools/messaging/adapters/base.mjs +326 -0
  160. package/tools/messaging/adapters/discord.mjs +462 -0
  161. package/tools/messaging/adapters/slack.mjs +402 -0
  162. package/tools/messaging/adapters/telegram.mjs +552 -0
  163. package/tools/messaging/chat-handler.mjs +297 -0
  164. package/tools/messaging/command-router.mjs +269 -0
  165. package/tools/messaging/event-bus.mjs +199 -0
  166. package/tools/messaging/index.mjs +456 -0
  167. package/tools/messaging/message-formatter.mjs +320 -0
  168. package/tools/messaging/room-manager.mjs +277 -0
  169. package/tools/messaging/types.mjs +94 -0
  170. package/tools/providers/pi-bridge-policy.mjs +4 -0
  171. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  172. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  173. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  174. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  175. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  176. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  177. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  178. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  179. package/tools/ralph-external/session-launcher.mjs +7 -7
  180. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,511 @@
1
+ # AIWG Daemon Mode
2
+
3
+ Implementation of background daemon for AIWG following ADR-daemon-mode.
4
+
5
+ ## Architecture
6
+
7
+ The daemon implements a Unix-style PID-file based lifecycle with event-driven architecture:
8
+
9
+ ```
10
+ CLI (index.mjs)
11
+ ├─ start: Spawns daemon-main.mjs detached
12
+ ├─ stop: Sends SIGTERM to PID
13
+ ├─ status: Reads state.json
14
+ └─ logs: Tails daemon.log
15
+
16
+ Daemon (daemon-main.mjs)
17
+ ├─ Lifecycle Manager (PID, signals, heartbeat)
18
+ ├─ Event Sources
19
+ │ ├─ FileWatcher (fs.watch with debounce)
20
+ │ └─ CronScheduler (setInterval with cron matching)
21
+ └─ Event Router (pub/sub event bus)
22
+ ```
23
+
24
+ ## Files
25
+
26
+ | File | Purpose |
27
+ |------|---------|
28
+ | `index.mjs` | CLI entry point (start/stop/status/logs) |
29
+ | `daemon-main.mjs` | Main daemon process and subsystem orchestration |
30
+ | `config.mjs` | Configuration loader and validator |
31
+ | `file-watcher.mjs` | File system change detection |
32
+ | `cron-scheduler.mjs` | Periodic task scheduling |
33
+ | `event-router.mjs` | Event pub/sub with dead letter queue |
34
+ | `ipc-server.mjs` | JSON-RPC 2.0 server over Unix domain socket |
35
+ | `ipc-client.mjs` | IPC client for CLI↔daemon communication |
36
+ | `agent-supervisor.mjs` | Spawns and tracks `claude -p` subprocesses with concurrency limits |
37
+ | `task-store.mjs` | Persistent task queue with state tracking |
38
+ | `automation-engine.mjs` | Trigger→condition→action rule engine |
39
+ | `tmux-manager.mjs` | Tmux session management for interactive agent sessions |
40
+ | `repl-chat.mjs` | Interactive terminal chat with AI via daemon |
41
+
42
+ ## Usage
43
+
44
+ ### Start Daemon
45
+
46
+ ```bash
47
+ # Start in background (normal mode)
48
+ node tools/daemon/index.mjs start
49
+
50
+ # Start in foreground (Docker/systemd)
51
+ node tools/daemon/index.mjs start --foreground
52
+ ```
53
+
54
+ ### Stop Daemon
55
+
56
+ ```bash
57
+ node tools/daemon/index.mjs stop
58
+ ```
59
+
60
+ ### Check Status
61
+
62
+ ```bash
63
+ node tools/daemon/index.mjs status
64
+ ```
65
+
66
+ ### View Logs
67
+
68
+ ```bash
69
+ # Show last 50 lines
70
+ node tools/daemon/index.mjs logs
71
+
72
+ # Show last 100 lines
73
+ node tools/daemon/index.mjs logs --lines 100
74
+
75
+ # Follow logs in real-time
76
+ node tools/daemon/index.mjs logs --follow
77
+ ```
78
+
79
+ ### Restart Daemon
80
+
81
+ ```bash
82
+ node tools/daemon/index.mjs restart
83
+ ```
84
+
85
+ ## Configuration
86
+
87
+ Configuration stored in `.aiwg/daemon.json`. Default configuration created on first start.
88
+
89
+ ### Default Configuration
90
+
91
+ ```json
92
+ {
93
+ "daemon": {
94
+ "heartbeat_interval_seconds": 30,
95
+ "max_parallel_actions": 3,
96
+ "action_timeout_minutes": 120,
97
+ "log": {
98
+ "max_size_mb": 50,
99
+ "max_files": 5,
100
+ "level": "info"
101
+ }
102
+ },
103
+ "watch": {
104
+ "enabled": true,
105
+ "paths": [
106
+ {
107
+ "path": ".aiwg/",
108
+ "events": ["create", "modify", "delete"],
109
+ "ignore": ["*.tmp", "working/**", "daemon/**"]
110
+ },
111
+ {
112
+ "path": "src/",
113
+ "events": ["modify"],
114
+ "extensions": [".ts", ".js", ".mjs"]
115
+ }
116
+ ],
117
+ "debounce_ms": 2000
118
+ },
119
+ "schedule": {
120
+ "enabled": true,
121
+ "jobs": [
122
+ {
123
+ "id": "health-check",
124
+ "cron": "0 */6 * * *",
125
+ "action": "doctor"
126
+ }
127
+ ]
128
+ }
129
+ }
130
+ ```
131
+
132
+ ## File System Layout
133
+
134
+ ```
135
+ .aiwg/
136
+ daemon.pid # PID file (only when running)
137
+ daemon.json # Configuration
138
+ daemon/
139
+ state.json # Daemon state
140
+ daemon.log # Current log
141
+ daemon.log.1 # Rotated log
142
+ heartbeat # Liveness indicator
143
+ actions/ # Action outputs
144
+ events/ # Event history
145
+ .lock # Advisory lock file
146
+ ```
147
+
148
+ ## Lifecycle
149
+
150
+ ### Startup
151
+
152
+ 1. Check for existing daemon (validate PID file)
153
+ 2. Create directories (`.aiwg/daemon/`, etc.)
154
+ 3. Acquire advisory lock (`.aiwg/daemon/.lock`)
155
+ 4. Spawn detached process (or run in foreground)
156
+ 5. Write PID file (`.aiwg/daemon.pid`)
157
+ 6. Install signal handlers (SIGTERM, SIGINT, SIGHUP)
158
+ 7. Load configuration
159
+ 8. Initialize subsystems (FileWatcher, CronScheduler)
160
+ 9. Start heartbeat writer
161
+ 10. Begin event processing
162
+
163
+ ### Shutdown
164
+
165
+ 1. Receive SIGTERM/SIGINT
166
+ 2. Set shutdown flag (reject new events)
167
+ 3. Stop event sources (close watchers, clear intervals)
168
+ 4. Write final state
169
+ 5. Remove PID file
170
+ 6. Release lock file
171
+ 7. Exit gracefully
172
+
173
+ ### Config Reload
174
+
175
+ Send SIGHUP to reload configuration:
176
+
177
+ ```bash
178
+ kill -HUP $(cat .aiwg/daemon.pid)
179
+ ```
180
+
181
+ ## Docker Usage
182
+
183
+ Use `--foreground` flag to run as PID 1 in containers:
184
+
185
+ ```dockerfile
186
+ FROM node:24-alpine
187
+ WORKDIR /app
188
+ COPY . .
189
+ CMD ["node", "tools/daemon/index.mjs", "start", "--foreground"]
190
+ ```
191
+
192
+ ## Features
193
+
194
+ ### File Watching
195
+
196
+ - Uses `fs.watch` with recursive support
197
+ - Debounce mechanism (500ms default)
198
+ - Configurable paths and file extensions
199
+ - Automatic ignore patterns (node_modules, .git, working/, daemon/)
200
+
201
+ ### Cron Scheduling
202
+
203
+ - Standard 5-field cron expressions
204
+ - Minute-level granularity
205
+ - Supports wildcards, ranges, steps, lists
206
+ - Example: `0 */6 * * *` = every 6 hours
207
+
208
+ ### Event Routing
209
+
210
+ - Pub/sub event bus
211
+ - Dead letter queue for failed handlers
212
+ - Max 3 retries with exponential backoff
213
+ - Event history (last 1000 events)
214
+
215
+ ### Log Rotation
216
+
217
+ - Size-based rotation (50MB default)
218
+ - Keep N rotated files (5 default)
219
+ - Automatic cleanup of old logs
220
+
221
+ ### Health Monitoring
222
+
223
+ - Heartbeat file updated every 30s
224
+ - State file with uptime, monitors, actions
225
+ - PID validation on status check
226
+
227
+ ## Token Security
228
+
229
+ Configuration never contains secrets. All sensitive values referenced via environment variables:
230
+
231
+ ```json
232
+ {
233
+ "webhook": {
234
+ "secret_env": "AIWG_WEBHOOK_SECRET"
235
+ }
236
+ }
237
+ ```
238
+
239
+ Secrets loaded from `process.env` at runtime.
240
+
241
+ ## Implementation Notes
242
+
243
+ ### Advisory Locking
244
+
245
+ Uses `fs.openSync(lockFile, 'wx')` for atomic lock acquisition. Prevents multiple daemon instances.
246
+
247
+ ### PID File Management
248
+
249
+ Atomic write pattern:
250
+ ```javascript
251
+ fs.writeFileSync(`${pidFile}.tmp`, String(pid));
252
+ fs.renameSync(`${pidFile}.tmp`, pidFile);
253
+ ```
254
+
255
+ ### Detached Process
256
+
257
+ ```javascript
258
+ const child = spawn(process.execPath, [daemonScript], {
259
+ detached: true,
260
+ stdio: ['ignore', logFd, logFd],
261
+ env: process.env
262
+ });
263
+ child.unref();
264
+ ```
265
+
266
+ ### Signal Handling
267
+
268
+ Graceful shutdown preserves state:
269
+ ```javascript
270
+ process.on('SIGTERM', () => {
271
+ shutdownInProgress = true;
272
+ stopSubsystems();
273
+ writeState();
274
+ cleanup();
275
+ process.exit(0);
276
+ });
277
+ ```
278
+
279
+ ## Testing
280
+
281
+ Test daemon lifecycle:
282
+
283
+ ```bash
284
+ # Start daemon
285
+ node tools/daemon/index.mjs start
286
+
287
+ # Verify running
288
+ node tools/daemon/index.mjs status
289
+
290
+ # Watch logs
291
+ node tools/daemon/index.mjs logs --follow &
292
+
293
+ # Stop daemon
294
+ node tools/daemon/index.mjs stop
295
+ ```
296
+
297
+ ## Troubleshooting
298
+
299
+ ### Daemon won't start
300
+
301
+ Check for stale PID file:
302
+ ```bash
303
+ cat .aiwg/daemon.pid
304
+ ps -p $(cat .aiwg/daemon.pid)
305
+ ```
306
+
307
+ If process is dead, remove PID file:
308
+ ```bash
309
+ rm .aiwg/daemon.pid
310
+ ```
311
+
312
+ ### Daemon won't stop
313
+
314
+ Force kill:
315
+ ```bash
316
+ kill -9 $(cat .aiwg/daemon.pid)
317
+ rm .aiwg/daemon.pid
318
+ ```
319
+
320
+ ### Check logs
321
+
322
+ ```bash
323
+ tail -f .aiwg/daemon/daemon.log
324
+ ```
325
+
326
+ ### Verify state
327
+
328
+ ```bash
329
+ cat .aiwg/daemon/state.json | jq .
330
+ ```
331
+
332
+ ## Subsystem Architecture
333
+
334
+ The daemon orchestrates several subsystems initialized in this order:
335
+
336
+ ```
337
+ EventRouter → TaskStore → AgentSupervisor → AutomationEngine
338
+ → IPCServer → FileWatcher → CronScheduler → MessagingHub
339
+ ```
340
+
341
+ ### IPC Server (`ipc-server.mjs`)
342
+
343
+ JSON-RPC 2.0 protocol over Unix domain socket (`.aiwg/daemon/daemon.sock`). Supports methods: `daemon.status`, `task.submit`, `task.cancel`, `task.list`, `task.get`, `task.stats`, `automation.status`, `automation.enable`, `automation.disable`, `chat.send`, `ping`.
344
+
345
+ ### Agent Supervisor (`agent-supervisor.mjs`)
346
+
347
+ Manages a pool of `claude -p` subprocesses with configurable concurrency (default: 3). Emits events: `task:started`, `task:completed`, `task:failed`, `task:timeout`. Tasks are persisted in the Task Store.
348
+
349
+ ### Task Store (`task-store.mjs`)
350
+
351
+ Persistent JSON-based task queue at `.aiwg/daemon/tasks.json`. Tracks task state (queued, running, completed, failed), priority, timestamps, and output.
352
+
353
+ ### Automation Engine (`automation-engine.mjs`)
354
+
355
+ Event-driven rule system. Rules define trigger→condition→action workflows loaded from `.aiwg/daemon.json`. Supports event matching, shell-based conditions, and agent task actions.
356
+
357
+ ### Messaging Integration
358
+
359
+ The daemon dynamically imports `tools/messaging/index.mjs` to connect Slack, Discord, and Telegram. See [Messaging Guide](../../docs/messaging-guide.md).
360
+
361
+ ## References
362
+
363
+ - ADR: `.aiwg/architecture/adrs/ADR-daemon-mode.md`
364
+ - ADR: `.aiwg/architecture/adrs/ADR-ipc-protocol.md`
365
+ - ADR: `.aiwg/architecture/adrs/ADR-2way-chat.md`
366
+ - User Guide: `docs/daemon-guide.md`
367
+ - Issues: #312, #315, #316, #317, #318
368
+ - Ralph External: `tools/ralph-external/` (background process pattern)
369
+
370
+ ## Deterministic scheduled maintenance (#3353 B2)
371
+
372
+ The existing CronScheduler and ScheduledTaskRunner also accept typed jobs. These
373
+ jobs invoke owner APIs in a bounded Node worker; they never submit prompts or
374
+ construct a model supervisor. No dependencies or second scheduler are added.
375
+ Existing `action` jobs retain their agent submission behavior; `kind: agent.prompt`
376
+ explicitly selects that same opt-in behavior. Maintenance jobs cannot carry prompts,
377
+ install flags, or force cleanup authority.
378
+
379
+ | `kind` | Deterministic owner entry point | Meaning |
380
+ | --- | --- | --- |
381
+ | `index.verify` (`index.freshness`) | `src/artifacts/index-status.ts:collectIndexStatus(cwd)` (`aiwg index status`) | Read the registered graph status, missing indices and warnings. This is a status probe, not a checksum audit or B4 convergence claim. |
382
+ | `index.reconcile` (`index.refresh`) | `src/artifacts/index-refresh.ts:runIndexRefresh(args, cwd)` (`aiwg index refresh`) | Existing incremental reconciliation; `args.index` maps to the owner's `--only`, with optional `workspace`, `root`, `dryRun`. |
383
+ | `cache.retention` (`cache.prune`) | `src/resources/cache-cleanup.ts:cleanWebResourceCache(cwd, options)` (`aiwg versions clean-cache`) | Prune unreferenced release generations, preserving lockfile-protected items. Optional `cacheRoot` and `dryRun`; never `force`. Retention follows this owner's policy. |
384
+ | `update.check` | `src/update/checker.mjs:checkUpdateStatus({channel})` | Check stable/next/nightly registry versions. No prompt, install, config save, or redeploy. Edge returns `deferred/unsupported`; the old forced checker can install on edge and is deliberately excluded. |
385
+
386
+ Example job in the existing `schedule.jobs` array:
387
+
388
+ ```json
389
+ {
390
+ "id": "reconcile-sessions",
391
+ "kind": "index.reconcile",
392
+ "cron": "15 * * * *",
393
+ "timezone": "America/New_York",
394
+ "missedRunPolicy": "run-once",
395
+ "timeoutMs": 60000,
396
+ "retries": 2,
397
+ "backoff": { "baseMs": 1000, "maxMs": 300000 },
398
+ "args": { "index": "sessions" }
399
+ }
400
+ ```
401
+
402
+ `cron` also accepts the B1 name `schedule`. Timezone defaults to UTC. Cron has
403
+ five fields (wildcards, lists, ranges, steps; weekday 0=Sunday), with the existing
404
+ AND convention for day-of-month and weekday. Invalid expressions fail closed.
405
+ Cron works in civil time using IANA zones: a nonexistent time shifts forward by
406
+ the gap (New York 2026-03-08 02:30 becomes 03:30); a repeated time fires only at
407
+ its first occurrence (2026-11-01 01:30 EDT, never again at 01:30 EST). Next-run
408
+ calculation after a restart inside the fold uses the same rule. Overlapping gap
409
+ and ordinary occurrences at the same instant coalesce. UTC schedules have no DST.
410
+
411
+ ### Persisted state and retries
412
+
413
+ `tasks.json` version 2 preserves the version 1 `tasks` array and adds `schedules`.
414
+ Version 1 files load without rewriting until a mutation. Missing schedule fields
415
+ default to `timezone: UTC`, `missedRunPolicy: skip`, `state: idle`,
416
+ `attemptCount: 0`, empty `receipts`, and null `nextRun`, `lastRun`, `lastReceipt`,
417
+ `pendingFireTime`, `retryAt`, `ownerPid`, and `workerPid`. Registration computes
418
+ an absent next-run value. Existing agent task fields and IDs stay intact.
419
+
420
+ Each schedule stores its complete `job`, civil timezone, next scheduled UTC
421
+ instant, last owner start, policy, state (`idle|pending|running|retry|blocked`),
422
+ attempt count for the current fire identity, pending fire time, retry deadline,
423
+ parent/worker PIDs, last receipt, and attempt receipts. Receipts include job ID,
424
+ fire time, `ok|failed|skipped|deferred`, exit status (null if unknown/not run),
425
+ summary, owner detail, start/finish timestamps, duration, attempt count, and
426
+ whether the receipt settles that fire identity. Receipts remain retained for
427
+ deduplication; bounded retention needs a retained deduplication watermark before
428
+ it can safely prune them.
429
+
430
+ Startup and each tick reconcile at most one pending identity per job. `skip`
431
+ records one skipped receipt for the missed interval; `run-once` executes one
432
+ coalesced run identified by the oldest retained due time. Both advance nextRun
433
+ past the current time without enumerating missed slots. Completion also advances
434
+ past time spent running. New typed jobs start at their next future slot. A
435
+ pending/retrying job never accumulates a second queue of missed runs.
436
+
437
+ Known owner failures retry the same identity up to `retries + 1` attempts
438
+ (default 3, maximum 3). Equal jitter chooses a delay in `[ceiling/2, ceiling]`,
439
+ where `ceiling = min(maxMs, baseMs * 2^(attemptCount-1))`. Deadline, attempts, and
440
+ receipts persist before another attempt; one tick can dispatch only one attempt.
441
+ Downtime during backoff yields one attempt after restart, with no retry burst.
442
+ Typed schedules poll once per second, so a due deadline can run up to a tick
443
+ later. Clock and RNG are injectable. Invalid kinds/authority fail terminally;
444
+ owner deferrals do not retry. An uncertain owner result blocks for review.
445
+
446
+ ### One scheduled-work recovery policy: retain, block, inspect, acknowledge
447
+
448
+ The store is the authority for maintenance intent, attempts, and receipts.
449
+ Transient router history/DLQ is never the recovery authority for typed jobs.
450
+
451
+ 1. Persist intent and claim under an exclusive short store transaction **before**
452
+ giving a worker execution authority. Record the worker PID before sending it
453
+ the job. Daemon and manual callers use the same transactions and fire-time
454
+ deduplication. Atomic temp-file writes, file/directory fsync, and rename keep
455
+ readers from observing partial JSON. A failed write stops execution.
456
+ 2. Known owner exit results receive receipts. A thrown executor error, killed or
457
+ timed-out worker, missing receipt, or interrupted persisted `running` state
458
+ has an uncertain outcome: retain the identity and block it. There is no
459
+ automatic replay of uncertain work. A live run returns `deferred/lock-held`.
460
+ 3. Corrupt/unreadable/unsupported store data or a disappearing persisted file
461
+ stops use of that store and preserves the source. Restore a verified backup
462
+ and inspect any affected owner effects; never start from an empty file.
463
+ 4. Existing store transaction locks (including stale locks) remain in place and
464
+ produce `lock-held/recovery-required`. Stop all writers, inspect the lock's
465
+ PID and any owner worker, preserve a copy of the lock/store, and remove only
466
+ the verified abandoned lock. Restart still blocks unresolved run intent.
467
+ The daemon's existing lifecycle lock follows the same stop-and-inspect rule;
468
+ this slice does not steal it or change lifecycle locking.
469
+ 5. After checking owner effects and verifying parent/worker processes are gone,
470
+ explicitly acknowledge the blocked job with `--resolve "inspection summary"`
471
+ (below). This records `skipped/operator-resolved` for that fire identity and
472
+ re-enables future scheduled slots. It does **not** replay the uncertain run.
473
+ If work remains necessary, invoke the next fire minute explicitly. A replay
474
+ of the resolved identity remains deduplicated.
475
+
476
+ The runner emits `recovery-required` for diagnostics. Typed failures explicitly
477
+ sent to `EventRouter.handleFailedEvent` go straight to a persisted blocked
478
+ receipt through the runner; they bypass the router's independent retry timer.
479
+ The router edit changes only this failure handoff, not `route()` or watcher
480
+ routing. Other event sources and legacy agent actions retain their existing
481
+ behavior for B3. Unresolved pending jobs remain in the store even if delivery is
482
+ interrupted before a handler starts.
483
+
484
+ ### Manual execution with the daemon disabled
485
+
486
+ Use the existing daemon CLI script and its `schedule` command. In a source
487
+ checkout, run `npm run build:cli` first to materialize the owner modules;
488
+ installed packages already include them:
489
+
490
+ ```bash
491
+ node tools/daemon/index.mjs schedule --run-once --job reconcile-sessions --json
492
+ node tools/daemon/index.mjs schedule --run-once --job reconcile-sessions \
493
+ --fire-time 2026-10-24T12:15:00Z --json
494
+ node tools/daemon/index.mjs schedule --run-once --job reconcile-sessions \
495
+ --resolve "Verified owner effects and no live worker" --json
496
+ ```
497
+
498
+ `--config PATH` and `--store-path PATH` support isolated runs. Manual mode reads
499
+ the job even when `schedule.enabled` is false. It loads no watcher, timers, IPC
500
+ server or model supervisor, and creates no scratch directories. The owner uses
501
+ its existing workspace/cache/temp rules. `--json` stdout is exactly one receipt;
502
+ owner stdout is isolated from it. Exit 0 means success/already settled, 1 owner
503
+ failure, 3 deferral. Invocation/store errors produce a diagnostic and nonzero
504
+ exit. This script is the existing CLI surface; no new `housekeeper` command
505
+ family is introduced by B2. Linux/macOS are supported; Windows should use WSL2.
506
+ Native timers can invoke this same manual command as the D2 alternative.
507
+
508
+ Per-index targets, adapter registration, convergence, watch reconciliation,
509
+ resource/maintenance-window gates, minimal daemon profiles, and broader status
510
+ surfaces remain follow-on integration work. This slice records owner reports;
511
+ it never derives a freshness or convergence claim from a configured target.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * ChannelAdapter — base class for all delivery channel adapters
3
+ *
4
+ * Channel adapters bridge the MessageRouter to external delivery mechanisms
5
+ * (webhooks, websockets, SSE, etc.). Subclasses implement send() and may
6
+ * override start()/stop() for lifecycle management.
7
+ *
8
+ * @implements #521
9
+ */
10
+
11
+ export class ChannelAdapter {
12
+ /**
13
+ * @param {Object} options
14
+ * @param {string} options.id - Unique adapter identifier within the router
15
+ * @param {string} options.type - Adapter type label (e.g. 'webhook', 'sse')
16
+ */
17
+ constructor({ id, type }) {
18
+ if (!id) throw new Error('ChannelAdapter requires an id');
19
+ if (!type) throw new Error('ChannelAdapter requires a type');
20
+
21
+ this.id = id;
22
+ this.type = type;
23
+ this.status = 'stopped';
24
+ this._commandHandler = null;
25
+ this._connectedAt = null;
26
+ }
27
+
28
+ /**
29
+ * Register a handler that will be called when the adapter receives an
30
+ * inbound command (e.g. over a bidirectional channel like WebSocket).
31
+ *
32
+ * @param {Function} handler - Called with ({ source, command, args, replyTo })
33
+ */
34
+ onCommand(handler) {
35
+ this._commandHandler = handler;
36
+ }
37
+
38
+ /**
39
+ * Send an event/message through this channel.
40
+ * Must be implemented by subclasses.
41
+ *
42
+ * @param {Object} message - Event object (shape: { type, data, timestamp })
43
+ * @param {Object} [options]
44
+ * @returns {Promise<void>}
45
+ */
46
+ async send(message, options) {
47
+ throw new Error(`${this.constructor.name}.send() must be implemented`);
48
+ }
49
+
50
+ /**
51
+ * Start the adapter (open connections, begin listening, etc.).
52
+ * Subclasses may override but should call super.start() to set state.
53
+ *
54
+ * @returns {Promise<void>}
55
+ */
56
+ async start() {
57
+ this.status = 'running';
58
+ this._connectedAt = new Date().toISOString();
59
+ }
60
+
61
+ /**
62
+ * Stop the adapter (close connections, release resources, etc.).
63
+ * Subclasses may override but should call super.stop() to set state.
64
+ *
65
+ * @returns {Promise<void>}
66
+ */
67
+ async stop() {
68
+ this.status = 'stopped';
69
+ }
70
+
71
+ /**
72
+ * Return a plain-object snapshot of this adapter's identity and state.
73
+ *
74
+ * @returns {{ id: string, type: string, status: string, connectedAt: string|null }}
75
+ */
76
+ getInfo() {
77
+ return {
78
+ id: this.id,
79
+ type: this.type,
80
+ status: this.status,
81
+ connectedAt: this._connectedAt,
82
+ };
83
+ }
84
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * WebhookAdapter — sends daemon events as HTTP POST with optional HMAC signature
3
+ *
4
+ * Each call to send() POSTs the event as JSON to the configured URL.
5
+ * When a secret is provided the request includes an X-AIWG-Signature header
6
+ * computed as HMAC-SHA256 over the serialised body (same convention as
7
+ * GitHub webhooks). An event-type filter can be supplied so the adapter
8
+ * only forwards events the consumer cares about.
9
+ *
10
+ * @implements #521
11
+ */
12
+
13
+ import { ChannelAdapter } from './base-adapter.mjs';
14
+ import http from 'node:http';
15
+ import https from 'node:https';
16
+ import crypto from 'node:crypto';
17
+
18
+ export class WebhookAdapter extends ChannelAdapter {
19
+ /**
20
+ * @param {Object} options
21
+ * @param {string} [options.id='webhook'] - Adapter identifier
22
+ * @param {string} options.url - Destination URL (http or https)
23
+ * @param {string} [options.secret] - HMAC secret; omit to skip signing
24
+ * @param {string[]|null} [options.events] - Allowlist of event types; null = all
25
+ */
26
+ constructor({ id, url, secret, events } = {}) {
27
+ super({ id: id || 'webhook', type: 'webhook' });
28
+
29
+ if (!url) throw new Error('WebhookAdapter requires a url');
30
+
31
+ this.url = new URL(url);
32
+ this.secret = secret || null;
33
+ this.events = events || null; // null means accept every event type
34
+ }
35
+
36
+ /**
37
+ * POST an event to the webhook URL.
38
+ *
39
+ * Skipped silently when an events allowlist is configured and the
40
+ * message type is not in that list.
41
+ *
42
+ * @param {Object} message - Event object
43
+ * @param {string} message.type - Event type used for filtering and headers
44
+ * @param {*} [message.data] - Arbitrary event payload
45
+ * @param {string} [message.timestamp]
46
+ * @returns {Promise<{ statusCode: number, body: string }>}
47
+ */
48
+ async send(message) {
49
+ // Apply event-type filter
50
+ if (this.events !== null && !this.events.includes(message.type)) {
51
+ return;
52
+ }
53
+
54
+ const body = JSON.stringify(message);
55
+
56
+ const headers = {
57
+ 'Content-Type': 'application/json',
58
+ 'Content-Length': Buffer.byteLength(body),
59
+ 'X-AIWG-Event': message.type || 'unknown',
60
+ };
61
+
62
+ if (this.secret) {
63
+ const sig = crypto
64
+ .createHmac('sha256', this.secret)
65
+ .update(body)
66
+ .digest('hex');
67
+ headers['X-AIWG-Signature'] = `sha256=${sig}`;
68
+ }
69
+
70
+ return this._post(body, headers);
71
+ }
72
+
73
+ // --- Private helpers ---
74
+
75
+ /**
76
+ * Perform the HTTP(S) POST and return a promise that resolves to
77
+ * { statusCode, body } or rejects on a network error.
78
+ *
79
+ * @param {string} body
80
+ * @param {Object} headers
81
+ * @returns {Promise<{ statusCode: number, body: string }>}
82
+ */
83
+ _post(body, headers) {
84
+ const transport = this.url.protocol === 'https:' ? https : http;
85
+
86
+ const options = {
87
+ hostname: this.url.hostname,
88
+ port: this.url.port || (this.url.protocol === 'https:' ? 443 : 80),
89
+ path: this.url.pathname + this.url.search,
90
+ method: 'POST',
91
+ headers,
92
+ };
93
+
94
+ return new Promise((resolve, reject) => {
95
+ const req = transport.request(options, (res) => {
96
+ let responseBody = '';
97
+ res.on('data', (chunk) => { responseBody += chunk; });
98
+ res.on('end', () => resolve({ statusCode: res.statusCode, body: responseBody }));
99
+ });
100
+
101
+ req.on('error', reject);
102
+
103
+ req.write(body);
104
+ req.end();
105
+ });
106
+ }
107
+ }