@aiwg/cli 2026.10.14 → 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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Typed internal event bus for AIWG messaging subsystem.
3
+ *
4
+ * Connects AIWG lifecycle event producers (Ralph orchestrator, HITL gates,
5
+ * security auditor) to messaging consumers (platform adapters) without
6
+ * requiring an external message broker.
7
+ *
8
+ * @implements @.aiwg/architecture/adrs/ADR-messaging-bot-mode.md
9
+ */
10
+
11
+ import { EventEmitter } from 'events';
12
+
13
+ /**
14
+ * @typedef {Object} AiwgEvent
15
+ * @property {string} topic - Event topic (e.g., "ralph.completed")
16
+ * @property {string} timestamp - ISO-8601 timestamp
17
+ * @property {string} source - Event source (e.g., "ralph-orchestrator")
18
+ * @property {string} [loopId] - Ralph loop ID if applicable
19
+ * @property {string} [gateId] - Gate ID if applicable
20
+ * @property {'info'|'warning'|'critical'} severity
21
+ * @property {string} summary - One-line human-readable summary
22
+ * @property {Record<string, unknown>} details - Event-specific payload
23
+ * @property {string} project - Project root basename
24
+ */
25
+
26
+ export class EventBus {
27
+ /** @type {EventEmitter} */
28
+ #emitter;
29
+
30
+ /** @type {Map<string, Function[]>} */
31
+ #subscribers;
32
+
33
+ /** @type {Array<{event: AiwgEvent, error: Error, handler: string}>} */
34
+ #deadLetterQueue;
35
+
36
+ /** @type {number} */
37
+ #maxRetries;
38
+
39
+ /** @type {number} */
40
+ #maxDeadLetters;
41
+
42
+ constructor({ maxRetries = 3, maxDeadLetters = 100 } = {}) {
43
+ this.#emitter = new EventEmitter();
44
+ this.#emitter.setMaxListeners(50);
45
+ this.#subscribers = new Map();
46
+ this.#deadLetterQueue = [];
47
+ this.#maxRetries = maxRetries;
48
+ this.#maxDeadLetters = maxDeadLetters;
49
+ }
50
+
51
+ /**
52
+ * Subscribe to events matching a topic pattern.
53
+ * Supports exact match ("ralph.completed") and wildcard ("ralph.*").
54
+ *
55
+ * @param {string} pattern - Topic or wildcard pattern
56
+ * @param {(event: AiwgEvent) => Promise<void>} handler
57
+ * @param {string} [name] - Handler name for debugging
58
+ */
59
+ subscribe(pattern, handler, name) {
60
+ const handlerName = name || handler.name || 'anonymous';
61
+ const wrappedHandler = async (event) => {
62
+ if (!this.#matchesPattern(event.topic, pattern)) return;
63
+
64
+ let lastError;
65
+ for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {
66
+ try {
67
+ await handler(event);
68
+ return;
69
+ } catch (error) {
70
+ lastError = error;
71
+ if (attempt < this.#maxRetries) {
72
+ // Brief delay before retry
73
+ await new Promise(r => setTimeout(r, 100 * attempt));
74
+ }
75
+ }
76
+ }
77
+
78
+ // All retries exhausted — send to dead letter queue
79
+ this.#addToDeadLetter(event, lastError, handlerName);
80
+ };
81
+
82
+ if (!this.#subscribers.has(pattern)) {
83
+ this.#subscribers.set(pattern, []);
84
+ }
85
+ this.#subscribers.get(pattern).push(wrappedHandler);
86
+ this.#emitter.on('event', wrappedHandler);
87
+ }
88
+
89
+ /**
90
+ * Publish an event to all matching subscribers.
91
+ *
92
+ * @param {AiwgEvent} event
93
+ */
94
+ publish(event) {
95
+ if (!event.timestamp) {
96
+ event.timestamp = new Date().toISOString();
97
+ }
98
+ this.#emitter.emit('event', event);
99
+ }
100
+
101
+ /**
102
+ * Remove all subscribers for a pattern.
103
+ *
104
+ * @param {string} pattern
105
+ */
106
+ unsubscribe(pattern) {
107
+ const handlers = this.#subscribers.get(pattern);
108
+ if (handlers) {
109
+ for (const handler of handlers) {
110
+ this.#emitter.removeListener('event', handler);
111
+ }
112
+ this.#subscribers.delete(pattern);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Get the dead letter queue contents.
118
+ *
119
+ * @returns {Array<{event: AiwgEvent, error: Error, handler: string, timestamp: string}>}
120
+ */
121
+ getDeadLetters() {
122
+ return [...this.#deadLetterQueue];
123
+ }
124
+
125
+ /**
126
+ * Clear the dead letter queue.
127
+ */
128
+ clearDeadLetters() {
129
+ this.#deadLetterQueue.length = 0;
130
+ }
131
+
132
+ /**
133
+ * Get subscriber count.
134
+ *
135
+ * @returns {number}
136
+ */
137
+ get subscriberCount() {
138
+ let count = 0;
139
+ for (const handlers of this.#subscribers.values()) {
140
+ count += handlers.length;
141
+ }
142
+ return count;
143
+ }
144
+
145
+ /**
146
+ * Remove all subscribers and clear state.
147
+ */
148
+ destroy() {
149
+ this.#emitter.removeAllListeners();
150
+ this.#subscribers.clear();
151
+ this.#deadLetterQueue.length = 0;
152
+ }
153
+
154
+ /**
155
+ * Check if a topic matches a subscription pattern.
156
+ * Supports: exact match, single wildcard ("ralph.*"), double wildcard ("*")
157
+ *
158
+ * @param {string} topic
159
+ * @param {string} pattern
160
+ * @returns {boolean}
161
+ */
162
+ #matchesPattern(topic, pattern) {
163
+ if (pattern === '*') return true;
164
+ if (pattern === topic) return true;
165
+
166
+ if (pattern.endsWith('.*')) {
167
+ const prefix = pattern.slice(0, -2);
168
+ return topic.startsWith(prefix + '.');
169
+ }
170
+
171
+ return false;
172
+ }
173
+
174
+ /**
175
+ * Add a failed event to the dead letter queue.
176
+ *
177
+ * @param {AiwgEvent} event
178
+ * @param {Error} error
179
+ * @param {string} handlerName
180
+ */
181
+ #addToDeadLetter(event, error, handlerName) {
182
+ this.#deadLetterQueue.push({
183
+ event,
184
+ error: { message: error.message, stack: error.stack },
185
+ handler: handlerName,
186
+ timestamp: new Date().toISOString(),
187
+ });
188
+
189
+ // Evict oldest entries if over capacity
190
+ while (this.#deadLetterQueue.length > this.#maxDeadLetters) {
191
+ this.#deadLetterQueue.shift();
192
+ }
193
+
194
+ // Log but don't throw — messaging failures must not crash the daemon
195
+ console.error(
196
+ `[EventBus] Handler "${handlerName}" failed after ${this.#maxRetries} retries for topic "${event.topic}": ${error.message}`
197
+ );
198
+ }
199
+ }
@@ -0,0 +1,456 @@
1
+ /**
2
+ * AIWG Messaging Hub — main entry point.
3
+ *
4
+ * Wires together the EventBus, MessageFormatter, AdapterRegistry,
5
+ * and CommandRouter into a cohesive messaging subsystem that can be
6
+ * embedded in the daemon or used standalone.
7
+ *
8
+ * @implements @.aiwg/architecture/adrs/ADR-messaging-bot-mode.md
9
+ */
10
+
11
+ import path from 'path';
12
+ import { EventBus } from './event-bus.mjs';
13
+ import { formatEvent } from './message-formatter.mjs';
14
+ import {
15
+ initializeRegistry,
16
+ loadEnabledAdapters,
17
+ getRegistryStatus,
18
+ shutdownAll,
19
+ } from './adapter-registry.mjs';
20
+ import { CommandRouter } from './command-router.mjs';
21
+ import { ChatHandler } from './chat-handler.mjs';
22
+ import { COMMANDS, EventTopic } from './types.mjs';
23
+
24
+ /**
25
+ * @typedef {Object} MessagingHub
26
+ * @property {EventBus} bus - Internal event bus
27
+ * @property {CommandRouter} router - Command dispatcher
28
+ * @property {number} adapterCount - Number of loaded adapters
29
+ * @property {(event: import('./event-bus.mjs').AiwgEvent) => void} publish
30
+ * @property {() => Promise<void>} shutdown
31
+ * @property {() => Object} getStatus
32
+ */
33
+
34
+ /**
35
+ * Create and initialize the messaging hub.
36
+ *
37
+ * Discovers enabled adapters from environment variables, loads them,
38
+ * wires event subscriptions, and registers default command handlers.
39
+ *
40
+ * @param {Object} [options]
41
+ * @param {Object} [options.adapterConfigs] - Per-adapter config overrides
42
+ * @param {string[]} [options.writeUsers] - User IDs with write permission
43
+ * @param {import('./chat-handler.mjs').ChatHandlerOptions} [options.chatHandler] - Chat handler config (enables 2-way AI chat)
44
+ * @param {import('./room-manager.mjs').RoomManager} [options.roomManager] - Room manager for multi-room routing
45
+ * @param {Object} [options.messagingConfig] - Messaging config from daemon.yaml
46
+ * @param {Object} [options.environment] - Environment for chat workers, excluding daemon credentials
47
+ * @returns {Promise<MessagingHub|null>} null if no adapters enabled
48
+ */
49
+ export async function createMessagingHub(options = {}) {
50
+ const { adapterConfigs = {}, writeUsers = [], chatHandler: chatHandlerConfig, roomManager, messagingConfig } = options;
51
+
52
+ // Discover and load adapters
53
+ initializeRegistry();
54
+ const adapters = await loadEnabledAdapters(adapterConfigs);
55
+
56
+ if (adapters.size === 0) {
57
+ console.log('[messaging] No adapters enabled — messaging hub not started');
58
+ return null;
59
+ }
60
+
61
+ const projectName = path.basename(process.cwd());
62
+ const bus = new EventBus();
63
+ const router = new CommandRouter();
64
+
65
+ // Grant write permissions
66
+ for (const userId of writeUsers) {
67
+ router.grantPermission(userId, 'write');
68
+ }
69
+
70
+ // Register default command handlers
71
+ registerDefaultHandlers(router, bus, roomManager);
72
+
73
+ // Wire adapters: EventBus → format → send to all adapters
74
+ bus.subscribe('*', async (event) => {
75
+ const message = formatEvent(event);
76
+
77
+ for (const [name, adapter] of adapters) {
78
+ try {
79
+ await adapter.send(message);
80
+ } catch (error) {
81
+ console.error(`[messaging] Failed to send to ${name}: ${error.message}`);
82
+ }
83
+ }
84
+ }, 'messaging-hub-broadcaster');
85
+
86
+ // Wire inbound commands from adapters → router → response
87
+ for (const [name, adapter] of adapters) {
88
+ adapter.onCommand(async (command, args, context) => {
89
+ const rawInput = [command, ...args].join(' ');
90
+ const result = await router.dispatch(rawInput, context);
91
+
92
+ // Send response back to the originating platform
93
+ const responseMessage = {
94
+ title: result.success ? 'Command Result' : 'Command Failed',
95
+ body: result.message || result.error || 'No response',
96
+ severity: result.success ? 'info' : 'warning',
97
+ fields: [],
98
+ project: projectName,
99
+ timestamp: new Date().toISOString(),
100
+ };
101
+
102
+ try {
103
+ await adapter.send(responseMessage, context.channelId || context.chatId);
104
+ } catch (error) {
105
+ console.error(`[messaging] Failed to send command response to ${name}: ${error.message}`);
106
+ }
107
+ });
108
+ }
109
+
110
+ // Wire 2-way AI chat if chatHandler config is provided
111
+ let chatHandler = null;
112
+ if (chatHandlerConfig !== false) {
113
+ chatHandler = new ChatHandler({ ...(chatHandlerConfig || {}),
114
+ ...(options.environment ? { environment: options.environment } : {}) });
115
+
116
+ // Register /ask command → forwards to chat handler
117
+ router.registerHandler('ask', async (args, context) => {
118
+ const question = args.join(' ');
119
+ if (!question) {
120
+ return { success: false, error: 'Usage: /ask <question>' };
121
+ }
122
+
123
+ const result = await chatHandler.processMessage(question, {
124
+ chatId: context.chatId,
125
+ platform: context.platform,
126
+ from: context.from,
127
+ });
128
+
129
+ return { success: true, message: result.response };
130
+ });
131
+
132
+ // Wire free-text messages from adapters → chat handler → response
133
+ for (const [name, adapter] of adapters) {
134
+ adapter.onMessage(async (text, context) => {
135
+ bus.publish({
136
+ topic: EventTopic.CHAT_MESSAGE,
137
+ source: `${context.platform}-adapter`,
138
+ severity: 'info',
139
+ summary: `Chat message from ${context.from?.username || 'unknown'}`,
140
+ details: { text: text.slice(0, 100), platform: context.platform },
141
+ project: projectName,
142
+ timestamp: new Date().toISOString(),
143
+ });
144
+
145
+ const result = await chatHandler.processMessage(text, {
146
+ chatId: context.chatId,
147
+ platform: context.platform,
148
+ from: context.from,
149
+ });
150
+
151
+ // Send AI response back to the originating platform
152
+ const responseMessage = {
153
+ title: 'AI Response',
154
+ body: result.response,
155
+ severity: 'info',
156
+ fields: [],
157
+ project: projectName,
158
+ timestamp: new Date().toISOString(),
159
+ };
160
+
161
+ try {
162
+ await adapter.send(responseMessage, context.chatId);
163
+ } catch (error) {
164
+ console.error(`[messaging] Failed to send chat response to ${name}: ${error.message}`);
165
+ bus.publish({
166
+ topic: EventTopic.CHAT_ERROR,
167
+ source: 'messaging-hub',
168
+ severity: 'warning',
169
+ summary: `Failed to send chat response: ${error.message}`,
170
+ project: projectName,
171
+ timestamp: new Date().toISOString(),
172
+ });
173
+ }
174
+ });
175
+ }
176
+
177
+ console.log('[messaging] 2-way AI chat enabled');
178
+ }
179
+
180
+ console.log(`[messaging] Hub started with ${adapters.size} adapter(s): ${[...adapters.keys()].join(', ')}`);
181
+
182
+ return {
183
+ bus,
184
+ router,
185
+ chatHandler,
186
+ roomManager,
187
+ adapterCount: adapters.size,
188
+
189
+ /**
190
+ * Publish an event to all connected messaging platforms.
191
+ *
192
+ * @param {import('./event-bus.mjs').AiwgEvent} event
193
+ */
194
+ publish(event) {
195
+ if (!event.project) {
196
+ event.project = projectName;
197
+ }
198
+ bus.publish(event);
199
+ },
200
+
201
+ /**
202
+ * Shutdown all adapters and clean up the event bus.
203
+ *
204
+ * @returns {Promise<void>}
205
+ */
206
+ async shutdown() {
207
+ bus.destroy();
208
+ await shutdownAll();
209
+ console.log('[messaging] Hub shut down');
210
+ },
211
+
212
+ /**
213
+ * Get combined status of all components.
214
+ *
215
+ * @returns {Object}
216
+ */
217
+ getStatus() {
218
+ return {
219
+ adapters: getRegistryStatus(),
220
+ commands: router.handlerCount,
221
+ subscribers: bus.subscriberCount,
222
+ deadLetters: bus.getDeadLetters().length,
223
+ };
224
+ },
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Register built-in command handlers.
230
+ *
231
+ * @param {CommandRouter} router
232
+ * @param {EventBus} bus
233
+ * @param {import('./room-manager.mjs').RoomManager} [roomManager]
234
+ */
235
+ function registerDefaultHandlers(router, bus, roomManager) {
236
+ // /help — list available commands
237
+ router.registerHandler('help', async (_args, _context) => {
238
+ return {
239
+ success: true,
240
+ message: router.getHelpText(),
241
+ };
242
+ });
243
+
244
+ // /status — show project status
245
+ router.registerHandler('status', async (_args, _context) => {
246
+ const projectName = path.basename(process.cwd());
247
+ const statusParts = [`Project: ${projectName}`];
248
+
249
+ // Check for .aiwg directory
250
+ const fs = await import('fs');
251
+ if (fs.existsSync('.aiwg/planning/current-phase.txt')) {
252
+ const phase = fs.readFileSync('.aiwg/planning/current-phase.txt', 'utf8').trim();
253
+ statusParts.push(`Phase: ${phase}`);
254
+ }
255
+
256
+ // Check daemon state
257
+ if (fs.existsSync('.aiwg/daemon/state.json')) {
258
+ try {
259
+ const state = JSON.parse(fs.readFileSync('.aiwg/daemon/state.json', 'utf8'));
260
+ statusParts.push(`Daemon uptime: ${state.uptime_seconds}s`);
261
+ statusParts.push(`Health: ${state.health?.status || 'unknown'}`);
262
+ } catch {
263
+ statusParts.push('Daemon: state unreadable');
264
+ }
265
+ }
266
+
267
+ return {
268
+ success: true,
269
+ message: statusParts.join('\n'),
270
+ };
271
+ });
272
+
273
+ // /ralph-status — show Ralph loop status
274
+ router.registerHandler('ralph-status', async (_args, _context) => {
275
+ const fs = await import('fs');
276
+ const ralphDir = '.aiwg/ralph-external';
277
+
278
+ if (!fs.existsSync(ralphDir)) {
279
+ return { success: true, message: 'No Ralph loop active' };
280
+ }
281
+
282
+ try {
283
+ const files = fs.readdirSync(ralphDir).filter(f => f.endsWith('.json'));
284
+ if (files.length === 0) {
285
+ return { success: true, message: 'No Ralph loop state files found' };
286
+ }
287
+
288
+ // Read the most recent state file
289
+ const latest = files.sort().pop();
290
+ const state = JSON.parse(fs.readFileSync(path.join(ralphDir, latest), 'utf8'));
291
+
292
+ const parts = [
293
+ `Loop: ${state.id || latest}`,
294
+ `Status: ${state.status || 'unknown'}`,
295
+ `Iteration: ${state.iteration || 'N/A'}/${state.maxIterations || 'N/A'}`,
296
+ ];
297
+
298
+ if (state.objective) {
299
+ parts.push(`Objective: ${state.objective}`);
300
+ }
301
+
302
+ return { success: true, message: parts.join('\n') };
303
+ } catch (error) {
304
+ return { success: true, message: `Ralph state error: ${error.message}` };
305
+ }
306
+ });
307
+
308
+ // /health — run health check
309
+ router.registerHandler('health', async (_args, _context) => {
310
+ const checks = [];
311
+
312
+ const fs = await import('fs');
313
+
314
+ // Check daemon heartbeat
315
+ if (fs.existsSync('.aiwg/daemon/heartbeat')) {
316
+ try {
317
+ const hb = JSON.parse(fs.readFileSync('.aiwg/daemon/heartbeat', 'utf8'));
318
+ const age = (Date.now() - new Date(hb.timestamp).getTime()) / 1000;
319
+ checks.push(age < 120 ? 'Daemon: healthy' : `Daemon: stale heartbeat (${Math.round(age)}s ago)`);
320
+ } catch {
321
+ checks.push('Daemon: heartbeat unreadable');
322
+ }
323
+ } else {
324
+ checks.push('Daemon: not running');
325
+ }
326
+
327
+ // Check adapter status
328
+ const adapterStatuses = getRegistryStatus();
329
+ for (const adapter of adapterStatuses) {
330
+ const status = adapter.status === 'ready' ? 'connected' : adapter.status;
331
+ checks.push(`${adapter.name}: ${status}${adapter.error ? ` (${adapter.error})` : ''}`);
332
+ }
333
+
334
+ return {
335
+ success: true,
336
+ message: `Health Check\n${checks.join('\n')}`,
337
+ };
338
+ });
339
+
340
+ // /approve — approve a pending HITL gate
341
+ router.registerHandler('approve', async (args, context) => {
342
+ const gateId = args[0];
343
+ if (!gateId) {
344
+ return { success: false, error: 'Usage: /approve <gate-id>' };
345
+ }
346
+
347
+ bus.publish({
348
+ topic: EventTopic.GATE_APPROVED,
349
+ source: 'messaging-command',
350
+ gateId,
351
+ severity: 'info',
352
+ summary: `Gate ${gateId} approved via ${context.platform}`,
353
+ details: {
354
+ approvedBy: context.userId || context.from?.username || 'unknown',
355
+ platform: context.platform,
356
+ },
357
+ project: path.basename(process.cwd()),
358
+ timestamp: new Date().toISOString(),
359
+ });
360
+
361
+ return { success: true, message: `Gate ${gateId} approved` };
362
+ });
363
+
364
+ // /reject — reject a pending HITL gate
365
+ router.registerHandler('reject', async (args, context) => {
366
+ const gateId = args[0];
367
+ if (!gateId) {
368
+ return { success: false, error: 'Usage: /reject <gate-id> [reason]' };
369
+ }
370
+
371
+ const reason = args.slice(1).join(' ') || 'Rejected via messaging';
372
+
373
+ bus.publish({
374
+ topic: EventTopic.GATE_REJECTED,
375
+ source: 'messaging-command',
376
+ gateId,
377
+ severity: 'warning',
378
+ summary: `Gate ${gateId} rejected via ${context.platform}: ${reason}`,
379
+ details: {
380
+ rejectedBy: context.userId || context.from?.username || 'unknown',
381
+ reason,
382
+ platform: context.platform,
383
+ },
384
+ project: path.basename(process.cwd()),
385
+ timestamp: new Date().toISOString(),
386
+ });
387
+
388
+ return { success: true, message: `Gate ${gateId} rejected: ${reason}` };
389
+ });
390
+
391
+ // Room management commands (require roomManager)
392
+ if (roomManager) {
393
+ // /join — dynamically add this chat as a room
394
+ router.registerHandler('join', async (_args, context) => {
395
+ const chatId = context.chatId || context.channelId;
396
+ if (!chatId) {
397
+ return { success: false, error: 'Could not determine chat ID' };
398
+ }
399
+ const room = roomManager.addRoom(context.platform, chatId, {
400
+ label: context.chatTitle || chatId,
401
+ purpose: 'interactive',
402
+ isDefault: false,
403
+ source: 'dynamic',
404
+ });
405
+ return { success: true, message: `Room "${room.label}" joined (${room.id})` };
406
+ });
407
+
408
+ // /leave — remove this chat from rooms
409
+ router.registerHandler('leave', async (_args, context) => {
410
+ const chatId = context.chatId || context.channelId;
411
+ if (!chatId) {
412
+ return { success: false, error: 'Could not determine chat ID' };
413
+ }
414
+ const removed = roomManager.removeRoom(context.platform, chatId);
415
+ return { success: true, message: removed ? 'Left room' : 'Room not found' };
416
+ });
417
+
418
+ // /rooms — list all active rooms
419
+ router.registerHandler('rooms', async (_args, _context) => {
420
+ const allRooms = roomManager.getRooms();
421
+ if (allRooms.length === 0) {
422
+ return { success: true, message: 'No rooms configured' };
423
+ }
424
+ const lines = allRooms.map(r =>
425
+ `${r.platform}:${r.platformRoomId} — ${r.label} (${r.purpose}${r.isDefault ? ', default' : ''})`
426
+ );
427
+ return { success: true, message: `Rooms (${allRooms.length}):\n${lines.join('\n')}` };
428
+ });
429
+
430
+ // /subscribe — receive task updates in this room
431
+ router.registerHandler('subscribe', async (args, context) => {
432
+ const taskId = args[0];
433
+ if (!taskId) {
434
+ return { success: false, error: 'Usage: /subscribe <taskId>' };
435
+ }
436
+ const chatId = context.chatId || context.channelId;
437
+ if (!chatId) {
438
+ return { success: false, error: 'Could not determine chat ID' };
439
+ }
440
+ roomManager.bindTask(taskId, context.platform, chatId);
441
+ return { success: true, message: `Subscribed to task ${taskId}` };
442
+ });
443
+
444
+ // /unsubscribe — stop receiving task updates
445
+ router.registerHandler('unsubscribe', async (args, _context) => {
446
+ const taskId = args[0];
447
+ if (!taskId) {
448
+ return { success: false, error: 'Usage: /unsubscribe <taskId>' };
449
+ }
450
+ roomManager.unbindTask(taskId);
451
+ return { success: true, message: `Unsubscribed from task ${taskId}` };
452
+ });
453
+ }
454
+ }
455
+
456
+ export default createMessagingHub;