@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,386 @@
1
+ /**
2
+ * MemoryManager — Cross-session memory for daemon persistent context
3
+ *
4
+ * Three memory scopes:
5
+ * session — in-memory only, cleared on daemon stop
6
+ * project — .aiwg/daemon/memory/ (project-local, committed with project)
7
+ * user — ~/.aiwg/daemon/memory/ (global user preferences)
8
+ *
9
+ * Format mirrors the auto-memory pattern:
10
+ * MEMORY.md — index of all entries (one line per entry)
11
+ * <key>.md — individual memory file with YAML frontmatter
12
+ *
13
+ * @implements Issue #608
14
+ */
15
+
16
+ import fs from 'fs';
17
+ import path from 'path';
18
+ import os from 'os';
19
+
20
+ const MEMORY_INDEX_FILE = 'MEMORY.md';
21
+ const MAX_SESSION_ENTRIES = 100;
22
+
23
+ // Safety: never write these patterns to persistent memory
24
+ const FORBIDDEN_PATTERNS = [
25
+ /token\s*[:=]/i,
26
+ /password\s*[:=]/i,
27
+ /secret\s*[:=]/i,
28
+ /api[_-]?key\s*[:=]/i,
29
+ /bearer\s+[a-z0-9._-]{10,}/i,
30
+ /-----BEGIN\s+(RSA|EC|OPENSSH|PRIVATE)/i,
31
+ ];
32
+
33
+ export class MemoryManager {
34
+ /**
35
+ * @param {object} opts
36
+ * @param {string} [opts.projectRoot] — project working directory (default: cwd)
37
+ * @param {string} [opts.userHome] — user home for user-scope storage (default: os.homedir())
38
+ */
39
+ constructor(opts = {}) {
40
+ this.projectRoot = opts.projectRoot || process.cwd();
41
+ this.userHome = opts.userHome || os.homedir();
42
+
43
+ this.paths = {
44
+ project: path.join(this.projectRoot, '.aiwg', 'daemon', 'memory'),
45
+ user: path.join(this.userHome, '.aiwg', 'daemon', 'memory'),
46
+ };
47
+
48
+ // Session scope: in-memory only, never written to disk
49
+ this._session = new Map(); // key -> { name, description, content, updatedAt }
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Lifecycle
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /**
57
+ * Load project and user memory indexes into an in-memory summary.
58
+ * Called at daemon/session start. Safe to call when directories don't exist yet.
59
+ *
60
+ * @returns {{ project: object[], user: object[] }}
61
+ */
62
+ load() {
63
+ return {
64
+ project: this._loadIndex(this.paths.project),
65
+ user: this._loadIndex(this.paths.user),
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Flush session-scope entries to project memory as a session log entry.
71
+ * Called at daemon shutdown or end of concierge session.
72
+ *
73
+ * @param {object} [summary] — optional summary metadata (taskCount, duration, etc.)
74
+ */
75
+ flushSession(summary = {}) {
76
+ if (this._session.size === 0) return;
77
+
78
+ const lines = [];
79
+ for (const [key, entry] of this._session) {
80
+ lines.push(`- **${entry.name || key}**: ${entry.description || entry.content?.slice(0, 80) || '(no description)'}`);
81
+ }
82
+
83
+ const content = [
84
+ `Session ended: ${new Date().toISOString()}`,
85
+ summary.taskCount ? `Tasks completed: ${summary.taskCount}` : '',
86
+ summary.duration ? `Duration: ${summary.duration}` : '',
87
+ '',
88
+ '### Session Events',
89
+ ...lines,
90
+ ].filter(Boolean).join('\n');
91
+
92
+ this.write('project', 'session_log', content, {
93
+ name: 'Session Log',
94
+ description: `Session summary — ${new Date().toLocaleDateString()}`,
95
+ type: 'project',
96
+ });
97
+
98
+ this._session.clear();
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Write
103
+ // ---------------------------------------------------------------------------
104
+
105
+ /**
106
+ * Write a memory entry to the specified scope.
107
+ *
108
+ * @param {'session'|'project'|'user'} scope
109
+ * @param {string} key — filename stem (e.g. 'user_preferences', 'project_context')
110
+ * @param {string} content — markdown body
111
+ * @param {object} [meta] — { name, description, type }
112
+ * @returns {{ scope, key, path: string|null }}
113
+ */
114
+ write(scope, key, content, meta = {}) {
115
+ this._validateContent(content);
116
+ this._validateKey(key);
117
+
118
+ const entry = {
119
+ name: meta.name || key,
120
+ description: meta.description || '',
121
+ type: meta.type || scope,
122
+ content,
123
+ updatedAt: new Date().toISOString(),
124
+ };
125
+
126
+ if (scope === 'session') {
127
+ if (this._session.size >= MAX_SESSION_ENTRIES) {
128
+ // Drop the oldest entry
129
+ const oldest = this._session.keys().next().value;
130
+ this._session.delete(oldest);
131
+ }
132
+ this._session.set(key, entry);
133
+ return { scope, key, path: null };
134
+ }
135
+
136
+ const dir = this.paths[scope];
137
+ if (!dir) throw new Error(`Unknown memory scope: ${scope}`);
138
+
139
+ this._ensureDir(dir);
140
+
141
+ const filePath = path.join(dir, `${key}.md`);
142
+ const fileContent = this._renderMemoryFile(entry);
143
+ this._writeAtomic(filePath, fileContent);
144
+ this._updateIndex(dir, key, entry);
145
+
146
+ return { scope, key, path: filePath };
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // Read
151
+ // ---------------------------------------------------------------------------
152
+
153
+ /**
154
+ * Read a single memory entry by scope and key.
155
+ *
156
+ * @param {'session'|'project'|'user'} scope
157
+ * @param {string} key
158
+ * @returns {{ name, description, type, content, updatedAt }|null}
159
+ */
160
+ read(scope, key) {
161
+ if (scope === 'session') {
162
+ return this._session.get(key) || null;
163
+ }
164
+
165
+ const dir = this.paths[scope];
166
+ if (!dir) return null;
167
+
168
+ const filePath = path.join(dir, `${key}.md`);
169
+ if (!fs.existsSync(filePath)) return null;
170
+
171
+ return this._parseMemoryFile(fs.readFileSync(filePath, 'utf8'));
172
+ }
173
+
174
+ /**
175
+ * Build a formatted context string for injection into a concierge session preamble.
176
+ * Includes user-scope and project-scope memory. Session scope is omitted (it's live).
177
+ *
178
+ * @returns {string}
179
+ */
180
+ getContext() {
181
+ const sections = [];
182
+
183
+ const userEntries = this._loadEntries(this.paths.user);
184
+ if (userEntries.length > 0) {
185
+ sections.push('## User Memory\n');
186
+ for (const e of userEntries) {
187
+ sections.push(`### ${e.name}\n${e.content}\n`);
188
+ }
189
+ }
190
+
191
+ const projectEntries = this._loadEntries(this.paths.project);
192
+ if (projectEntries.length > 0) {
193
+ sections.push('## Project Memory\n');
194
+ for (const e of projectEntries) {
195
+ sections.push(`### ${e.name}\n${e.content}\n`);
196
+ }
197
+ }
198
+
199
+ if (sections.length === 0) return '';
200
+
201
+ return ['# Daemon Memory Context\n', ...sections].join('\n');
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Show / Clear
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /**
209
+ * Return a structured summary of all memory scopes for display.
210
+ *
211
+ * @param {string} [scope] — restrict to one scope; omit for all
212
+ * @returns {object}
213
+ */
214
+ show(scope) {
215
+ const scopes = scope ? [scope] : ['session', 'project', 'user'];
216
+ const result = {};
217
+
218
+ for (const s of scopes) {
219
+ if (s === 'session') {
220
+ result.session = {
221
+ entries: Array.from(this._session.entries()).map(([key, e]) => ({
222
+ key,
223
+ name: e.name,
224
+ description: e.description,
225
+ updatedAt: e.updatedAt,
226
+ })),
227
+ count: this._session.size,
228
+ };
229
+ } else {
230
+ const dir = this.paths[s];
231
+ const entries = dir ? this._loadIndex(dir) : [];
232
+ result[s] = {
233
+ path: dir || null,
234
+ entries,
235
+ count: entries.length,
236
+ };
237
+ }
238
+ }
239
+
240
+ return result;
241
+ }
242
+
243
+ /**
244
+ * Clear memory for a given scope.
245
+ *
246
+ * @param {'session'|'project'|'user'} scope
247
+ * @returns {{ scope, cleared: number }}
248
+ */
249
+ clear(scope) {
250
+ if (scope === 'session') {
251
+ const count = this._session.size;
252
+ this._session.clear();
253
+ return { scope, cleared: count };
254
+ }
255
+
256
+ const dir = this.paths[scope];
257
+ if (!dir) throw new Error(`Unknown memory scope: ${scope}`);
258
+
259
+ if (!fs.existsSync(dir)) return { scope, cleared: 0 };
260
+
261
+ const files = fs.readdirSync(dir).filter(f => f.endsWith('.md'));
262
+ for (const f of files) {
263
+ fs.unlinkSync(path.join(dir, f));
264
+ }
265
+
266
+ return { scope, cleared: files.length };
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Internal helpers
271
+ // ---------------------------------------------------------------------------
272
+
273
+ _ensureDir(dir) {
274
+ if (!fs.existsSync(dir)) {
275
+ fs.mkdirSync(dir, { recursive: true });
276
+ }
277
+ }
278
+
279
+ _writeAtomic(filePath, content) {
280
+ const tmp = `${filePath}.tmp`;
281
+ fs.writeFileSync(tmp, content, 'utf8');
282
+ fs.renameSync(tmp, filePath);
283
+ }
284
+
285
+ _renderMemoryFile(entry) {
286
+ return [
287
+ '---',
288
+ `name: ${entry.name}`,
289
+ `description: ${entry.description}`,
290
+ `type: ${entry.type}`,
291
+ `updated_at: ${entry.updatedAt}`,
292
+ '---',
293
+ '',
294
+ entry.content,
295
+ '',
296
+ ].join('\n');
297
+ }
298
+
299
+ _parseMemoryFile(raw) {
300
+ const frontmatterMatch = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
301
+ if (!frontmatterMatch) {
302
+ return { name: '', description: '', type: '', content: raw.trim(), updatedAt: '' };
303
+ }
304
+
305
+ const meta = {};
306
+ for (const line of frontmatterMatch[1].split('\n')) {
307
+ const colonIdx = line.indexOf(':');
308
+ if (colonIdx === -1) continue;
309
+ const key = line.slice(0, colonIdx).trim();
310
+ const val = line.slice(colonIdx + 1).trim();
311
+ meta[key] = val;
312
+ }
313
+
314
+ return {
315
+ name: meta.name || '',
316
+ description: meta.description || '',
317
+ type: meta.type || '',
318
+ content: frontmatterMatch[2].trim(),
319
+ updatedAt: meta.updated_at || '',
320
+ };
321
+ }
322
+
323
+ _updateIndex(dir, key, entry) {
324
+ const indexPath = path.join(dir, MEMORY_INDEX_FILE);
325
+ let lines = [];
326
+
327
+ if (fs.existsSync(indexPath)) {
328
+ lines = fs.readFileSync(indexPath, 'utf8')
329
+ .split('\n')
330
+ .filter(l => l.trim())
331
+ // Remove existing entry for this key
332
+ .filter(l => !l.includes(`](${key}.md)`));
333
+ }
334
+
335
+ const hook = entry.description?.slice(0, 120) || entry.name;
336
+ lines.push(`- [${entry.name}](${key}.md) — ${hook}`);
337
+
338
+ const header = '# Daemon Memory Index\n';
339
+ this._writeAtomic(indexPath, header + '\n' + lines.join('\n') + '\n');
340
+ }
341
+
342
+ _loadIndex(dir) {
343
+ if (!dir || !fs.existsSync(dir)) return [];
344
+
345
+ const indexPath = path.join(dir, MEMORY_INDEX_FILE);
346
+ if (!fs.existsSync(indexPath)) return [];
347
+
348
+ const lines = fs.readFileSync(indexPath, 'utf8')
349
+ .split('\n')
350
+ .filter(l => l.startsWith('- ['));
351
+
352
+ return lines.map(line => {
353
+ const match = line.match(/^- \[([^\]]+)\]\(([^)]+)\)\s*—?\s*(.*)/);
354
+ if (!match) return null;
355
+ return { name: match[1], file: match[2], description: match[3].trim() };
356
+ }).filter(Boolean);
357
+ }
358
+
359
+ _loadEntries(dir) {
360
+ const index = this._loadIndex(dir);
361
+ return index.map(({ file }) => {
362
+ const filePath = path.join(dir, file);
363
+ if (!fs.existsSync(filePath)) return null;
364
+ try {
365
+ return this._parseMemoryFile(fs.readFileSync(filePath, 'utf8'));
366
+ } catch {
367
+ return null;
368
+ }
369
+ }).filter(Boolean);
370
+ }
371
+
372
+ _validateContent(content) {
373
+ if (typeof content !== 'string') throw new Error('Memory content must be a string');
374
+ for (const pattern of FORBIDDEN_PATTERNS) {
375
+ if (pattern.test(content)) {
376
+ throw new Error('Memory content must not contain secrets, tokens, or credentials');
377
+ }
378
+ }
379
+ }
380
+
381
+ _validateKey(key) {
382
+ if (!/^[a-z0-9_-]+$/.test(key)) {
383
+ throw new Error(`Invalid memory key "${key}": use lowercase letters, digits, hyphens, underscores only`);
384
+ }
385
+ }
386
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * MessageRouter — decouples daemon commands/events from delivery channels
3
+ *
4
+ * The router sits between the daemon's internal event model and any number of
5
+ * outbound channel adapters (webhooks, SSE feeds, WebSocket clients, etc.).
6
+ * Adapters register themselves; the router fans broadcast() calls out to all
7
+ * of them and normalises inbound commands from bidirectional adapters before
8
+ * forwarding them to the AgentSupervisor.
9
+ *
10
+ * @implements #521
11
+ * @tests @test/unit/message-router.test.mjs
12
+ */
13
+
14
+ import { EventEmitter } from 'node:events';
15
+
16
+ export class MessageRouter extends EventEmitter {
17
+ /**
18
+ * @param {Object} [options]
19
+ * @param {import('./agent-supervisor.mjs').AgentSupervisor} [options.supervisor]
20
+ * Optional AgentSupervisor instance used to fulfil command dispatch.
21
+ * If omitted, all command calls return a 'supervisor unavailable' error.
22
+ */
23
+ constructor({ supervisor } = {}) {
24
+ super();
25
+ this._adapters = new Map(); // adapterId -> ChannelAdapter
26
+ this.supervisor = supervisor || null;
27
+ }
28
+
29
+ // =========================================================================
30
+ // Adapter lifecycle
31
+ // =========================================================================
32
+
33
+ /**
34
+ * Register a channel adapter with the router.
35
+ *
36
+ * The adapter must expose: id, type, send(), start(), stop(), getInfo().
37
+ * After registration its inbound commands are wired to handleCommand().
38
+ *
39
+ * @param {import('./adapters/base-adapter.mjs').ChannelAdapter} adapter
40
+ * @throws {Error} if an adapter with the same id is already registered
41
+ */
42
+ registerAdapter(adapter) {
43
+ if (!adapter || !adapter.id) {
44
+ throw new Error('registerAdapter requires an adapter with an id property');
45
+ }
46
+
47
+ if (this._adapters.has(adapter.id)) {
48
+ throw new Error(`Adapter '${adapter.id}' is already registered`);
49
+ }
50
+
51
+ // Wire inbound commands from bidirectional adapters
52
+ if (typeof adapter.onCommand === 'function') {
53
+ adapter.onCommand((payload) => this.handleCommand(payload));
54
+ }
55
+
56
+ this._adapters.set(adapter.id, adapter);
57
+ this.emit('adapter:registered', { adapterId: adapter.id, type: adapter.type });
58
+ }
59
+
60
+ /**
61
+ * Stop and deregister an adapter by id.
62
+ * No-ops silently if the id is not found.
63
+ *
64
+ * @param {string} adapterId
65
+ * @returns {Promise<void>}
66
+ */
67
+ async removeAdapter(adapterId) {
68
+ const adapter = this._adapters.get(adapterId);
69
+ if (!adapter) return;
70
+
71
+ try {
72
+ await adapter.stop();
73
+ } catch {
74
+ // Best-effort stop; proceed with removal regardless
75
+ }
76
+
77
+ this._adapters.delete(adapterId);
78
+ this.emit('adapter:removed', { adapterId });
79
+ }
80
+
81
+ // =========================================================================
82
+ // Command dispatch
83
+ // =========================================================================
84
+
85
+ /**
86
+ * Normalise and dispatch an inbound command from any adapter.
87
+ *
88
+ * Supported commands:
89
+ * submit - Submit a new agent task (args: { prompt, agent?, priority? })
90
+ * cancel - Cancel a task (args: { taskId })
91
+ * status - Supervisor status (no args)
92
+ * loops - Alias for status
93
+ * history - Task list (args: { state?, limit? })
94
+ *
95
+ * @param {Object} payload
96
+ * @param {string} payload.source - Adapter id that originated the command
97
+ * @param {string} payload.command - Command name
98
+ * @param {Object} [payload.args] - Command arguments
99
+ * @param {string} [payload.replyTo] - Optional reply-target hint for the adapter
100
+ * @returns {Object} result object with { ok: boolean, data?, error? }
101
+ */
102
+ handleCommand({ source, command, args = {}, replyTo } = {}) {
103
+ if (!this.supervisor) {
104
+ return { ok: false, error: 'supervisor unavailable' };
105
+ }
106
+
107
+ try {
108
+ switch (command) {
109
+ case 'submit': {
110
+ if (!args.prompt) {
111
+ return { ok: false, error: 'submit requires args.prompt' };
112
+ }
113
+ const task = this.supervisor.submit(args.prompt, {
114
+ agent: args.agent,
115
+ priority: args.priority || 0,
116
+ });
117
+ return { ok: true, data: { taskId: task.id, state: task.state } };
118
+ }
119
+
120
+ case 'cancel': {
121
+ if (!args.taskId) {
122
+ return { ok: false, error: 'cancel requires args.taskId' };
123
+ }
124
+ const cancelled = this.supervisor.cancel(args.taskId);
125
+ return { ok: true, data: { cancelled } };
126
+ }
127
+
128
+ case 'status':
129
+ case 'loops': {
130
+ return { ok: true, data: this.supervisor.getStatus() };
131
+ }
132
+
133
+ case 'history': {
134
+ if (!this.supervisor.taskStore) {
135
+ return { ok: false, error: 'task store unavailable' };
136
+ }
137
+ const tasks = this.supervisor.taskStore.getTasks({
138
+ state: args.state,
139
+ limit: args.limit || 20,
140
+ });
141
+ return { ok: true, data: tasks };
142
+ }
143
+
144
+ default:
145
+ return { ok: false, error: `unknown command: ${command}` };
146
+ }
147
+ } catch (err) {
148
+ return { ok: false, error: err.message };
149
+ }
150
+ }
151
+
152
+ // =========================================================================
153
+ // Event fan-out
154
+ // =========================================================================
155
+
156
+ /**
157
+ * Fan an event out to every registered adapter.
158
+ *
159
+ * Delivery errors from individual adapters are caught and emitted as
160
+ * 'adapter:error' events so one failing adapter cannot block the others.
161
+ *
162
+ * @param {Object} event
163
+ * @param {string} event.type - Event type
164
+ * @param {*} [event.data] - Payload
165
+ * @param {string} [event.timestamp] - ISO timestamp; injected if absent
166
+ */
167
+ broadcast(event) {
168
+ const normalised = {
169
+ ...event,
170
+ timestamp: event.timestamp || new Date().toISOString(),
171
+ };
172
+
173
+ for (const [adapterId, adapter] of this._adapters) {
174
+ Promise.resolve()
175
+ .then(() => adapter.send(normalised))
176
+ .catch((err) => {
177
+ this.emit('adapter:error', { adapterId, error: err.message, event: normalised });
178
+ });
179
+ }
180
+ }
181
+
182
+ // =========================================================================
183
+ // Introspection
184
+ // =========================================================================
185
+
186
+ /**
187
+ * Return a snapshot of all registered adapters' info objects.
188
+ *
189
+ * @returns {Array<{ id: string, type: string, status: string, connectedAt: string|null }>}
190
+ */
191
+ getAdapters() {
192
+ return Array.from(this._adapters.values()).map((a) => a.getInfo());
193
+ }
194
+ }