@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,346 @@
1
+ /**
2
+ * AutonomousThinkingEngine — Self-directed task generation with safety constraints.
3
+ *
4
+ * Periodically reviews project state and proposes bounded improvement tasks.
5
+ * Off by default. When enabled, constrained by allowlist, budget cap,
6
+ * daily task limit, and optional human approval gate.
7
+ *
8
+ * @implements Plan: Daemon Starter — Autonomous Mode
9
+ */
10
+
11
+ import { EventEmitter } from 'events';
12
+
13
+ /**
14
+ * @typedef {Object} AutonomousConfig
15
+ * @property {boolean} enabled
16
+ * @property {number} thinking_interval_minutes
17
+ * @property {number} max_daily_tasks
18
+ * @property {number} budget_cap_usd
19
+ * @property {boolean} require_approval
20
+ * @property {string[]} allowed_actions
21
+ * @property {string[]} blocked_actions
22
+ */
23
+
24
+ /**
25
+ * @typedef {Object} AutonomousEngineOptions
26
+ * @property {import('../ralph-external/daemon-supervisor.mjs').DaemonSupervisor} supervisor
27
+ * @property {AutonomousConfig} config
28
+ * @property {import('../messaging/room-manager.mjs').RoomManager} [roomManager]
29
+ */
30
+
31
+ /**
32
+ * @typedef {Object} Proposal
33
+ * @property {string} id
34
+ * @property {string} action
35
+ * @property {string} description
36
+ * @property {string} prompt
37
+ * @property {number} estimatedMinutes
38
+ * @property {number} estimatedCostUsd
39
+ * @property {'pending'|'approved'|'rejected'|'submitted'} status
40
+ * @property {string} createdAt
41
+ */
42
+
43
+ export class AutonomousEngine extends EventEmitter {
44
+ /** @type {import('../ralph-external/daemon-supervisor.mjs').DaemonSupervisor} */
45
+ #supervisor;
46
+
47
+ /** @type {AutonomousConfig} */
48
+ #config;
49
+
50
+ /** @type {import('../messaging/room-manager.mjs').RoomManager|null} */
51
+ #roomManager;
52
+
53
+ /** @type {NodeJS.Timeout|null} */
54
+ #timer = null;
55
+
56
+ /** @type {number} */
57
+ #dailyTaskCount = 0;
58
+
59
+ /** @type {number} */
60
+ #dailySpendUsd = 0;
61
+
62
+ /** @type {string|null} */
63
+ #lastResetDate = null;
64
+
65
+ /** @type {Map<string, Proposal>} */
66
+ #proposals = new Map();
67
+
68
+ /** @type {number} */
69
+ #proposalCounter = 0;
70
+
71
+ /** @type {boolean} */
72
+ #running = false;
73
+
74
+ /**
75
+ * @param {AutonomousEngineOptions} options
76
+ */
77
+ constructor(options) {
78
+ super();
79
+ this.#supervisor = options.supervisor;
80
+ this.#config = options.config;
81
+ this.#roomManager = options.roomManager || null;
82
+ }
83
+
84
+ /**
85
+ * Start the autonomous thinking loop.
86
+ */
87
+ start() {
88
+ if (this.#running) return;
89
+ if (!this.#config.enabled) return;
90
+
91
+ this.#running = true;
92
+ const intervalMs = (this.#config.thinking_interval_minutes || 30) * 60 * 1000;
93
+
94
+ this.#timer = setInterval(() => {
95
+ this.#think().catch(err => {
96
+ console.error(`[autonomous] Thinking cycle error: ${err.message}`);
97
+ });
98
+ }, intervalMs);
99
+
100
+ console.log(`[autonomous] Started (interval: ${this.#config.thinking_interval_minutes}min, ` +
101
+ `max daily: ${this.#config.max_daily_tasks}, budget: $${this.#config.budget_cap_usd})`);
102
+ }
103
+
104
+ /**
105
+ * Stop the autonomous thinking loop.
106
+ */
107
+ stop() {
108
+ if (this.#timer) {
109
+ clearInterval(this.#timer);
110
+ this.#timer = null;
111
+ }
112
+ this.#running = false;
113
+ }
114
+
115
+ /**
116
+ * Enable autonomous mode at runtime.
117
+ */
118
+ enable() {
119
+ this.#config.enabled = true;
120
+ if (!this.#running) this.start();
121
+ }
122
+
123
+ /**
124
+ * Disable autonomous mode at runtime.
125
+ */
126
+ disable() {
127
+ this.#config.enabled = false;
128
+ this.stop();
129
+ }
130
+
131
+ /**
132
+ * Approve a pending proposal.
133
+ *
134
+ * @param {string} proposalId
135
+ * @returns {boolean}
136
+ */
137
+ async approveProposal(proposalId) {
138
+ const proposal = this.#proposals.get(proposalId);
139
+ if (!proposal || proposal.status !== 'pending') return false;
140
+
141
+ proposal.status = 'approved';
142
+ await this.#submitProposal(proposal);
143
+ return true;
144
+ }
145
+
146
+ /**
147
+ * Reject a pending proposal.
148
+ *
149
+ * @param {string} proposalId
150
+ * @param {string} [reason]
151
+ * @returns {boolean}
152
+ */
153
+ rejectProposal(proposalId, reason) {
154
+ const proposal = this.#proposals.get(proposalId);
155
+ if (!proposal || proposal.status !== 'pending') return false;
156
+
157
+ proposal.status = 'rejected';
158
+ this.emit('proposal:rejected', { proposal, reason });
159
+ return true;
160
+ }
161
+
162
+ /**
163
+ * Run one thinking cycle.
164
+ */
165
+ async #think() {
166
+ this.#resetDailyCountersIfNeeded();
167
+
168
+ // Check daily limits
169
+ if (this.#dailyTaskCount >= (this.#config.max_daily_tasks || 10)) {
170
+ console.log('[autonomous] Daily task limit reached, skipping');
171
+ return;
172
+ }
173
+
174
+ if (this.#dailySpendUsd >= (this.#config.budget_cap_usd || 5)) {
175
+ console.log('[autonomous] Daily budget cap reached, skipping');
176
+ return;
177
+ }
178
+
179
+ // Generate a thinking prompt
180
+ const prompt = this.#buildThinkingPrompt();
181
+
182
+ try {
183
+ // Use the supervisor to run a lightweight analysis task
184
+ const result = await this.#supervisor.submit({
185
+ prompt,
186
+ priority: 1, // Lowest priority — interactive and scheduled tasks first
187
+ metadata: {
188
+ source: 'autonomous',
189
+ type: 'thinking',
190
+ },
191
+ });
192
+
193
+ // The task output should contain a JSON proposal
194
+ // For now, track that we submitted a thinking task
195
+ this.#dailyTaskCount++;
196
+ this.emit('think:completed', { taskId: result?.loopId || result?.taskId });
197
+ } catch (error) {
198
+ console.error(`[autonomous] Failed to submit thinking task: ${error.message}`);
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Build the prompt for a thinking cycle.
204
+ *
205
+ * @returns {string}
206
+ */
207
+ #buildThinkingPrompt() {
208
+ const allowed = (this.#config.allowed_actions || []).join(', ');
209
+ const blocked = (this.#config.blocked_actions || []).join(', ');
210
+
211
+ return `You are the autonomous maintenance daemon for this project.
212
+
213
+ Review the following and propose ONE specific, bounded improvement:
214
+ - Check .aiwg/ artifact health (missing fields, stale dates)
215
+ - Check recent git log (last 24h) for incomplete work
216
+ - Check test coverage gaps
217
+ - Check documentation drift
218
+
219
+ Constraints:
220
+ - You may ONLY perform actions in this allowlist: [${allowed}]
221
+ - You may NOT perform: [${blocked}]
222
+ - Keep the task under 10 minutes estimated execution time
223
+ - Keep estimated cost under $${this.#config.budget_cap_usd || 5}
224
+
225
+ Respond with ONLY a JSON object (no markdown fences):
226
+ {
227
+ "action": "one of the allowed actions",
228
+ "description": "what you want to do and why",
229
+ "prompt": "the exact prompt to execute the action",
230
+ "estimatedMinutes": 5,
231
+ "estimatedCostUsd": 0.50,
232
+ "skip": false,
233
+ "skipReason": "only if skip is true — why nothing needs doing"
234
+ }
235
+
236
+ If the project is in good shape and nothing needs doing, set skip: true.`;
237
+ }
238
+
239
+ /**
240
+ * Submit an approved proposal as a task.
241
+ *
242
+ * @param {Proposal} proposal
243
+ */
244
+ async #submitProposal(proposal) {
245
+ // Validate against constraints
246
+ if (!this.#validateProposal(proposal)) {
247
+ proposal.status = 'rejected';
248
+ return;
249
+ }
250
+
251
+ try {
252
+ const result = await this.#supervisor.submit({
253
+ prompt: proposal.prompt,
254
+ priority: 1,
255
+ metadata: {
256
+ source: 'autonomous',
257
+ type: 'proposal',
258
+ proposalId: proposal.id,
259
+ action: proposal.action,
260
+ },
261
+ });
262
+
263
+ proposal.status = 'submitted';
264
+ this.#dailyTaskCount++;
265
+ this.#dailySpendUsd += proposal.estimatedCostUsd || 0;
266
+
267
+ this.emit('proposal:submitted', {
268
+ proposal,
269
+ taskId: result?.loopId || result?.taskId,
270
+ });
271
+ } catch (error) {
272
+ console.error(`[autonomous] Failed to submit proposal ${proposal.id}: ${error.message}`);
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Validate a proposal against safety constraints.
278
+ *
279
+ * @param {Proposal} proposal
280
+ * @returns {boolean}
281
+ */
282
+ #validateProposal(proposal) {
283
+ const allowed = this.#config.allowed_actions || [];
284
+ const blocked = this.#config.blocked_actions || [];
285
+
286
+ if (blocked.includes(proposal.action)) {
287
+ console.warn(`[autonomous] Blocked action: ${proposal.action}`);
288
+ return false;
289
+ }
290
+
291
+ if (allowed.length > 0 && !allowed.includes(proposal.action)) {
292
+ console.warn(`[autonomous] Action not in allowlist: ${proposal.action}`);
293
+ return false;
294
+ }
295
+
296
+ if ((this.#dailySpendUsd + (proposal.estimatedCostUsd || 0)) > (this.#config.budget_cap_usd || 5)) {
297
+ console.warn('[autonomous] Proposal would exceed daily budget');
298
+ return false;
299
+ }
300
+
301
+ return true;
302
+ }
303
+
304
+ /**
305
+ * Reset daily counters at midnight.
306
+ */
307
+ #resetDailyCountersIfNeeded() {
308
+ const today = new Date().toISOString().slice(0, 10);
309
+ if (this.#lastResetDate !== today) {
310
+ this.#dailyTaskCount = 0;
311
+ this.#dailySpendUsd = 0;
312
+ this.#lastResetDate = today;
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Get pending proposals.
318
+ *
319
+ * @returns {Proposal[]}
320
+ */
321
+ getPendingProposals() {
322
+ return [...this.#proposals.values()].filter(p => p.status === 'pending');
323
+ }
324
+
325
+ /**
326
+ * Get status summary.
327
+ *
328
+ * @returns {Object}
329
+ */
330
+ getStatus() {
331
+ return {
332
+ enabled: this.#config.enabled,
333
+ running: this.#running,
334
+ dailyTaskCount: this.#dailyTaskCount,
335
+ dailyTaskLimit: this.#config.max_daily_tasks || 10,
336
+ dailySpendUsd: this.#dailySpendUsd,
337
+ budgetCapUsd: this.#config.budget_cap_usd || 5,
338
+ pendingProposals: this.getPendingProposals().length,
339
+ allowedActions: this.#config.allowed_actions || [],
340
+ blockedActions: this.#config.blocked_actions || [],
341
+ requireApproval: this.#config.require_approval || false,
342
+ };
343
+ }
344
+ }
345
+
346
+ export default AutonomousEngine;
@@ -0,0 +1,316 @@
1
+ /**
2
+ * DaemonBehaviorLoader — discovers, loads, and activates daemon behaviors.
3
+ *
4
+ * Behaviors are BEHAVIOR.md (or .behavior.md) files with YAML frontmatter.
5
+ * The canonical shape (per #1025) nests behavior fields under `metadata:`:
6
+ *
7
+ * ---
8
+ * name: my-behavior
9
+ * module: tools/daemon/my-behavior/orchestrator.mjs
10
+ * metadata:
11
+ * scope: daemon
12
+ * triggers: [session-start, pre-response, on-error, chat-message]
13
+ * ---
14
+ *
15
+ * - `name` and `module` stay at top level.
16
+ * - `scope` and `triggers` (plural) live inside `metadata:` so they share
17
+ * shape with the validator (see src/plugin/metadata-validator.ts:604).
18
+ *
19
+ * The module must export a class with a standard interface:
20
+ * - constructor(options) — receives { supervisor, memoryManager, provider, config }
21
+ * - onSessionStart(ctx) — called on session-start trigger (optional)
22
+ * - handleMessage(msg, ctx) — called on chat-message trigger (optional)
23
+ * - translateResponse(raw) — called on pre-response trigger (optional)
24
+ * - onError(error, ctx) — called on on-error trigger (optional)
25
+ * - getStatus() — returns status object for IPC (optional)
26
+ *
27
+ * Discovery tiers (later overrides earlier):
28
+ * 1. agentic/code/addons/\*\/behaviors/ — addon-shipped
29
+ * 2. .aiwg/behaviors/ — project-local
30
+ *
31
+ * @issue #642
32
+ */
33
+
34
+ import { readdir, readFile } from 'node:fs/promises';
35
+ import { join, resolve } from 'node:path';
36
+ import yaml from 'js-yaml';
37
+
38
+ export class DaemonBehaviorLoader {
39
+ /**
40
+ * @param {Object} options
41
+ * @param {string} options.projectRoot Project root directory
42
+ * @param {Object} options.supervisor AgentSupervisor instance
43
+ * @param {Object} [options.memoryManager] MemoryManager instance
44
+ * @param {string} [options.provider] Current provider key
45
+ * @param {Object} [options.config] Daemon config accessor
46
+ */
47
+ constructor(options = {}) {
48
+ this.projectRoot = options.projectRoot || process.cwd();
49
+ this.supervisor = options.supervisor;
50
+ this.memoryManager = options.memoryManager || null;
51
+ this.provider = options.provider || null;
52
+ this.config = options.config || null;
53
+
54
+ /** @type {Map<string, LoadedBehavior>} */
55
+ this._active = new Map();
56
+ }
57
+
58
+ /**
59
+ * Discover all .behavior.md files across addon and project tiers.
60
+ * @returns {Promise<DiscoveredBehavior[]>}
61
+ */
62
+ async discover() {
63
+ const discovered = [];
64
+
65
+ // Tier 1: addon behaviors
66
+ const addonsDir = join(this.projectRoot, 'agentic', 'code', 'addons');
67
+ try {
68
+ const addons = await readdir(addonsDir);
69
+ for (const addon of addons) {
70
+ const behaviorsDir = join(addonsDir, addon, 'behaviors');
71
+ try {
72
+ const files = await readdir(behaviorsDir);
73
+ for (const file of files.filter(f => f.endsWith('.behavior.md'))) {
74
+ discovered.push({ tier: 'addon', addon, path: join(behaviorsDir, file), file });
75
+ }
76
+ } catch { /* no behaviors dir — skip */ }
77
+ }
78
+ } catch { /* no addons dir — skip */ }
79
+
80
+ // Tier 2: project-local behaviors (override addon)
81
+ const projectBehaviors = join(this.projectRoot, '.aiwg', 'behaviors');
82
+ try {
83
+ const files = await readdir(projectBehaviors);
84
+ for (const file of files.filter(f => f.endsWith('.behavior.md'))) {
85
+ discovered.push({ tier: 'project', addon: null, path: join(projectBehaviors, file), file });
86
+ }
87
+ } catch { /* no project behaviors — skip */ }
88
+
89
+ return discovered;
90
+ }
91
+
92
+ /**
93
+ * Parse YAML frontmatter from a BEHAVIOR.md file.
94
+ *
95
+ * Uses js-yaml for full YAML support, including nested mappings —
96
+ * required for the canonical metadata.* shape (#1025).
97
+ *
98
+ * @param {string} filePath
99
+ * @returns {Promise<Object|null>}
100
+ */
101
+ async parseFrontmatter(filePath) {
102
+ const content = await readFile(filePath, 'utf-8');
103
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
104
+ if (!match) return null;
105
+
106
+ let parsed;
107
+ try {
108
+ parsed = yaml.load(match[1]);
109
+ } catch {
110
+ return null;
111
+ }
112
+ return (parsed && typeof parsed === 'object') ? parsed : null;
113
+ }
114
+
115
+ /**
116
+ * Load and activate all discovered daemon-scoped behaviors.
117
+ * @returns {Promise<Map<string, LoadedBehavior>>}
118
+ */
119
+ async loadAll() {
120
+ const discovered = await this.discover();
121
+
122
+ // Group by name — later tiers override earlier
123
+ const byName = new Map();
124
+ for (const entry of discovered) {
125
+ try {
126
+ const meta = await this.parseFrontmatter(entry.path);
127
+ if (!meta || meta.metadata?.scope !== 'daemon') continue;
128
+ if (!meta.name) continue;
129
+ if (!meta.module) {
130
+ // No module = prompt-only behavior (no orchestrator to load)
131
+ continue;
132
+ }
133
+ byName.set(meta.name, { ...entry, meta });
134
+ } catch (err) {
135
+ // Skip unparseable behaviors
136
+ }
137
+ }
138
+
139
+ // Activate each behavior
140
+ for (const [name, entry] of byName) {
141
+ try {
142
+ const orchestrator = await this._activate(entry);
143
+ if (orchestrator) {
144
+ this._active.set(name, {
145
+ name,
146
+ meta: entry.meta,
147
+ orchestrator,
148
+ path: entry.path,
149
+ tier: entry.tier,
150
+ });
151
+ }
152
+ } catch (err) {
153
+ // Non-fatal — log but continue
154
+ console.warn(`Behavior '${name}' activation failed: ${err.message}`);
155
+ }
156
+ }
157
+
158
+ return this._active;
159
+ }
160
+
161
+ /**
162
+ * Dynamically import and instantiate a behavior's orchestrator module.
163
+ * @param {Object} entry Discovered behavior entry with meta
164
+ * @returns {Promise<Object|null>}
165
+ */
166
+ async _activate(entry) {
167
+ const modulePath = entry.meta.module;
168
+
169
+ // Resolve module path relative to project root
170
+ const resolved = resolve(this.projectRoot, modulePath);
171
+ const mod = await import(resolved);
172
+
173
+ // Find the exported class — look for default export or first class export
174
+ const OrchestratorClass = mod.default || Object.values(mod).find(v => typeof v === 'function');
175
+ if (!OrchestratorClass) {
176
+ throw new Error(`No class exported from ${modulePath}`);
177
+ }
178
+
179
+ return new OrchestratorClass({
180
+ supervisor: this.supervisor,
181
+ memoryManager: this.memoryManager,
182
+ provider: this.provider,
183
+ config: this.config,
184
+ behaviorMeta: entry.meta,
185
+ });
186
+ }
187
+
188
+ /**
189
+ * Hot-apply a behavior by name — discovers it on disk and activates it.
190
+ * If a behavior with the same name is already active, it is replaced.
191
+ *
192
+ * @param {string} name Behavior name to apply
193
+ * @returns {Promise<{applied: boolean, name: string}>}
194
+ * @throws {Error} If the behavior is not found in any discovery tier
195
+ */
196
+ async apply(name) {
197
+ // Discover all available behaviors
198
+ const discovered = await this.discover();
199
+
200
+ // Find matching entry by name
201
+ let matchedEntry = null;
202
+ for (const entry of discovered) {
203
+ try {
204
+ const meta = await this.parseFrontmatter(entry.path);
205
+ if (!meta || meta.metadata?.scope !== 'daemon') continue;
206
+ if (!meta.name || meta.name !== name) continue;
207
+ if (!meta.module) continue;
208
+ matchedEntry = { ...entry, meta };
209
+ break;
210
+ } catch { /* skip */ }
211
+ }
212
+
213
+ if (!matchedEntry) {
214
+ throw new Error(`Behavior '${name}' not found or is not a daemon-scoped behavior with a module`);
215
+ }
216
+
217
+ // Deactivate existing instance if present
218
+ this._active.delete(name);
219
+
220
+ // Activate the new instance
221
+ const orchestrator = await this._activate(matchedEntry);
222
+ if (!orchestrator) {
223
+ throw new Error(`Behavior '${name}' activation returned null`);
224
+ }
225
+
226
+ this._active.set(name, {
227
+ name,
228
+ meta: matchedEntry.meta,
229
+ orchestrator,
230
+ path: matchedEntry.path,
231
+ tier: matchedEntry.tier,
232
+ });
233
+
234
+ return { applied: true, name };
235
+ }
236
+
237
+ /**
238
+ * Remove an active behavior by name.
239
+ * If the orchestrator exposes a `deactivate()` method, it is called first.
240
+ *
241
+ * @param {string} name Behavior name to remove
242
+ * @returns {{ removed: boolean, name: string }}
243
+ */
244
+ remove(name) {
245
+ const loaded = this._active.get(name);
246
+ if (!loaded) {
247
+ return { removed: false, name };
248
+ }
249
+
250
+ // Call optional cleanup hook
251
+ try {
252
+ if (typeof loaded.orchestrator.deactivate === 'function') {
253
+ loaded.orchestrator.deactivate();
254
+ }
255
+ } catch { /* non-fatal */ }
256
+
257
+ this._active.delete(name);
258
+ return { removed: true, name };
259
+ }
260
+
261
+ /**
262
+ * Get the active behavior orchestrator for a given trigger type.
263
+ * Returns all behaviors that declare this trigger.
264
+ * @param {string} trigger e.g. 'chat-message', 'session-start', 'pre-response', 'on-error'
265
+ * @returns {Object[]} Array of orchestrator instances
266
+ */
267
+ getForTrigger(trigger) {
268
+ const result = [];
269
+ for (const [, loaded] of this._active) {
270
+ const triggers = loaded.meta.metadata?.triggers || [];
271
+ if (triggers.includes(trigger)) {
272
+ result.push(loaded.orchestrator);
273
+ }
274
+ }
275
+ return result;
276
+ }
277
+
278
+ /**
279
+ * Get a specific active behavior by name.
280
+ * @param {string} name
281
+ * @returns {Object|null}
282
+ */
283
+ get(name) {
284
+ return this._active.get(name)?.orchestrator || null;
285
+ }
286
+
287
+ /**
288
+ * Check if a behavior is active.
289
+ * @param {string} name
290
+ * @returns {boolean}
291
+ */
292
+ has(name) {
293
+ return this._active.has(name);
294
+ }
295
+
296
+ /** Get status summary for IPC/CLI. */
297
+ getStatus() {
298
+ return {
299
+ active: Object.fromEntries(
300
+ [...this._active].map(([name, loaded]) => [
301
+ name,
302
+ {
303
+ triggers: loaded.meta.metadata?.triggers || [],
304
+ module: loaded.meta.module,
305
+ tier: loaded.tier,
306
+ path: loaded.path,
307
+ hasStatus: typeof loaded.orchestrator.getStatus === 'function',
308
+ },
309
+ ])
310
+ ),
311
+ count: this._active.size,
312
+ };
313
+ }
314
+ }
315
+
316
+ export default DaemonBehaviorLoader;