@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,84 @@
1
+ /**
2
+ * ChannelAdapter — base class for all delivery channel adapters
3
+ *
4
+ * Channel adapters bridge the MessageRouter to external delivery mechanisms
5
+ * (webhooks, websockets, SSE, etc.). Subclasses implement send() and may
6
+ * override start()/stop() for lifecycle management.
7
+ *
8
+ * @implements #521
9
+ */
10
+
11
+ export class ChannelAdapter {
12
+ /**
13
+ * @param {Object} options
14
+ * @param {string} options.id - Unique adapter identifier within the router
15
+ * @param {string} options.type - Adapter type label (e.g. 'webhook', 'sse')
16
+ */
17
+ constructor({ id, type }) {
18
+ if (!id) throw new Error('ChannelAdapter requires an id');
19
+ if (!type) throw new Error('ChannelAdapter requires a type');
20
+
21
+ this.id = id;
22
+ this.type = type;
23
+ this.status = 'stopped';
24
+ this._commandHandler = null;
25
+ this._connectedAt = null;
26
+ }
27
+
28
+ /**
29
+ * Register a handler that will be called when the adapter receives an
30
+ * inbound command (e.g. over a bidirectional channel like WebSocket).
31
+ *
32
+ * @param {Function} handler - Called with ({ source, command, args, replyTo })
33
+ */
34
+ onCommand(handler) {
35
+ this._commandHandler = handler;
36
+ }
37
+
38
+ /**
39
+ * Send an event/message through this channel.
40
+ * Must be implemented by subclasses.
41
+ *
42
+ * @param {Object} message - Event object (shape: { type, data, timestamp })
43
+ * @param {Object} [options]
44
+ * @returns {Promise<void>}
45
+ */
46
+ async send(message, options) {
47
+ throw new Error(`${this.constructor.name}.send() must be implemented`);
48
+ }
49
+
50
+ /**
51
+ * Start the adapter (open connections, begin listening, etc.).
52
+ * Subclasses may override but should call super.start() to set state.
53
+ *
54
+ * @returns {Promise<void>}
55
+ */
56
+ async start() {
57
+ this.status = 'running';
58
+ this._connectedAt = new Date().toISOString();
59
+ }
60
+
61
+ /**
62
+ * Stop the adapter (close connections, release resources, etc.).
63
+ * Subclasses may override but should call super.stop() to set state.
64
+ *
65
+ * @returns {Promise<void>}
66
+ */
67
+ async stop() {
68
+ this.status = 'stopped';
69
+ }
70
+
71
+ /**
72
+ * Return a plain-object snapshot of this adapter's identity and state.
73
+ *
74
+ * @returns {{ id: string, type: string, status: string, connectedAt: string|null }}
75
+ */
76
+ getInfo() {
77
+ return {
78
+ id: this.id,
79
+ type: this.type,
80
+ status: this.status,
81
+ connectedAt: this._connectedAt,
82
+ };
83
+ }
84
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * WebhookAdapter — sends daemon events as HTTP POST with optional HMAC signature
3
+ *
4
+ * Each call to send() POSTs the event as JSON to the configured URL.
5
+ * When a secret is provided the request includes an X-AIWG-Signature header
6
+ * computed as HMAC-SHA256 over the serialised body (same convention as
7
+ * GitHub webhooks). An event-type filter can be supplied so the adapter
8
+ * only forwards events the consumer cares about.
9
+ *
10
+ * @implements #521
11
+ */
12
+
13
+ import { ChannelAdapter } from './base-adapter.mjs';
14
+ import http from 'node:http';
15
+ import https from 'node:https';
16
+ import crypto from 'node:crypto';
17
+
18
+ export class WebhookAdapter extends ChannelAdapter {
19
+ /**
20
+ * @param {Object} options
21
+ * @param {string} [options.id='webhook'] - Adapter identifier
22
+ * @param {string} options.url - Destination URL (http or https)
23
+ * @param {string} [options.secret] - HMAC secret; omit to skip signing
24
+ * @param {string[]|null} [options.events] - Allowlist of event types; null = all
25
+ */
26
+ constructor({ id, url, secret, events } = {}) {
27
+ super({ id: id || 'webhook', type: 'webhook' });
28
+
29
+ if (!url) throw new Error('WebhookAdapter requires a url');
30
+
31
+ this.url = new URL(url);
32
+ this.secret = secret || null;
33
+ this.events = events || null; // null means accept every event type
34
+ }
35
+
36
+ /**
37
+ * POST an event to the webhook URL.
38
+ *
39
+ * Skipped silently when an events allowlist is configured and the
40
+ * message type is not in that list.
41
+ *
42
+ * @param {Object} message - Event object
43
+ * @param {string} message.type - Event type used for filtering and headers
44
+ * @param {*} [message.data] - Arbitrary event payload
45
+ * @param {string} [message.timestamp]
46
+ * @returns {Promise<{ statusCode: number, body: string }>}
47
+ */
48
+ async send(message) {
49
+ // Apply event-type filter
50
+ if (this.events !== null && !this.events.includes(message.type)) {
51
+ return;
52
+ }
53
+
54
+ const body = JSON.stringify(message);
55
+
56
+ const headers = {
57
+ 'Content-Type': 'application/json',
58
+ 'Content-Length': Buffer.byteLength(body),
59
+ 'X-AIWG-Event': message.type || 'unknown',
60
+ };
61
+
62
+ if (this.secret) {
63
+ const sig = crypto
64
+ .createHmac('sha256', this.secret)
65
+ .update(body)
66
+ .digest('hex');
67
+ headers['X-AIWG-Signature'] = `sha256=${sig}`;
68
+ }
69
+
70
+ return this._post(body, headers);
71
+ }
72
+
73
+ // --- Private helpers ---
74
+
75
+ /**
76
+ * Perform the HTTP(S) POST and return a promise that resolves to
77
+ * { statusCode, body } or rejects on a network error.
78
+ *
79
+ * @param {string} body
80
+ * @param {Object} headers
81
+ * @returns {Promise<{ statusCode: number, body: string }>}
82
+ */
83
+ _post(body, headers) {
84
+ const transport = this.url.protocol === 'https:' ? https : http;
85
+
86
+ const options = {
87
+ hostname: this.url.hostname,
88
+ port: this.url.port || (this.url.protocol === 'https:' ? 443 : 80),
89
+ path: this.url.pathname + this.url.search,
90
+ method: 'POST',
91
+ headers,
92
+ };
93
+
94
+ return new Promise((resolve, reject) => {
95
+ const req = transport.request(options, (res) => {
96
+ let responseBody = '';
97
+ res.on('data', (chunk) => { responseBody += chunk; });
98
+ res.on('end', () => resolve({ statusCode: res.statusCode, body: responseBody }));
99
+ });
100
+
101
+ req.on('error', reject);
102
+
103
+ req.write(body);
104
+ req.end();
105
+ });
106
+ }
107
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Agent Supervisor - Task queue and process management for claude -p spawning
3
+ *
4
+ * Manages a pool of concurrent agent subprocesses, tracking their lifecycle,
5
+ * streaming output, and reporting results through the event system.
6
+ *
7
+ * @implements @.aiwg/requirements/use-cases/UC-AGENT-001.md
8
+ * @tests @test/unit/daemon/agent-supervisor.test.js
9
+ */
10
+
11
+ import { importImpl } from '../_resolve-impl.mjs';
12
+ import { spawn } from 'node:child_process';
13
+ import { EventEmitter } from 'node:events';
14
+ const { signalChild } = await importImpl(import.meta.url, 'process/signal-child.mjs');
15
+
16
+ export class AgentSupervisor extends EventEmitter {
17
+ constructor(options = {}) {
18
+ super();
19
+ this.maxConcurrency = options.maxConcurrency ?? 3;
20
+ this.taskStore = options.taskStore || null;
21
+ this.queue = [];
22
+ this.running = new Map(); // taskId -> { process, task }
23
+ this.shutdownInProgress = false;
24
+ this.agentCommand = options.agentCommand || 'claude';
25
+ this.agentArgs = options.agentArgs || [];
26
+ this.environment = options.environment;
27
+ this.taskTimeout = options.taskTimeout || 120 * 60 * 1000; // 2 hours default
28
+ }
29
+
30
+ /**
31
+ * Submit a task to the queue
32
+ * Returns the task object with assigned ID
33
+ */
34
+ submit(prompt, options = {}) {
35
+ if (this.shutdownInProgress) {
36
+ throw new Error('Supervisor is shutting down');
37
+ }
38
+
39
+ // Create task in store if available
40
+ const task = this.taskStore
41
+ ? this.taskStore.createTask({ prompt, agent: options.agent, priority: options.priority || 0, metadata: options.metadata })
42
+ : {
43
+ id: `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
44
+ prompt,
45
+ agent: options.agent || null,
46
+ priority: options.priority || 0,
47
+ state: 'queued',
48
+ createdAt: new Date().toISOString(),
49
+ };
50
+
51
+ this.queue.push(task);
52
+ this.queue.sort((a, b) => (b.priority || 0) - (a.priority || 0));
53
+
54
+ this.emit('task:queued', { taskId: task.id, prompt: prompt.slice(0, 80), queueSize: this.queue.length });
55
+
56
+ this._processQueue();
57
+ return task;
58
+ }
59
+
60
+ /**
61
+ * Cancel a task (queued or running)
62
+ */
63
+ cancel(taskId) {
64
+ // Check queue first
65
+ const queueIdx = this.queue.findIndex(t => t.id === taskId);
66
+ if (queueIdx !== -1) {
67
+ this.queue.splice(queueIdx, 1);
68
+ if (this.taskStore) {
69
+ this.taskStore.cancelTask(taskId);
70
+ }
71
+ this.emit('task:cancelled', { taskId });
72
+ return true;
73
+ }
74
+
75
+ // Check running
76
+ const entry = this.running.get(taskId);
77
+ if (entry) {
78
+ try {
79
+ // Cleanup happens in the exit handler; refusal is not delivery.
80
+ return signalChild(entry.process, 'SIGTERM');
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ return false;
87
+ }
88
+
89
+ /**
90
+ * Get status of all tasks
91
+ */
92
+ getStatus() {
93
+ return {
94
+ running: this.running.size,
95
+ queued: this.queue.length,
96
+ maxConcurrency: this.maxConcurrency,
97
+ tasks: {
98
+ running: Array.from(this.running.entries()).map(([id, entry]) => ({
99
+ id,
100
+ prompt: entry.task.prompt.slice(0, 80),
101
+ agent: entry.task.agent,
102
+ startedAt: entry.task.startedAt,
103
+ pid: entry.process.pid,
104
+ })),
105
+ queued: this.queue.map(t => ({
106
+ id: t.id,
107
+ prompt: t.prompt.slice(0, 80),
108
+ agent: t.agent,
109
+ priority: t.priority,
110
+ })),
111
+ },
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Graceful shutdown - drain queue and wait for running tasks
117
+ */
118
+ async shutdown(timeoutMs = 30000) {
119
+ this.shutdownInProgress = true;
120
+
121
+ // Reject queued tasks
122
+ while (this.queue.length > 0) {
123
+ const task = this.queue.shift();
124
+ if (this.taskStore) {
125
+ this.taskStore.cancelTask(task.id);
126
+ }
127
+ this.emit('task:cancelled', { taskId: task.id, reason: 'shutdown' });
128
+ }
129
+
130
+ // Wait for running tasks to complete or timeout
131
+ if (this.running.size === 0) {
132
+ this.shutdownInProgress = false;
133
+ return;
134
+ }
135
+
136
+ const waitForCompletion = new Promise((resolve) => {
137
+ const checkInterval = setInterval(() => {
138
+ if (this.running.size === 0) {
139
+ clearInterval(checkInterval);
140
+ resolve();
141
+ }
142
+ }, 100);
143
+ });
144
+
145
+ const timeout = new Promise((resolve) => {
146
+ setTimeout(() => {
147
+ // Force kill remaining
148
+ for (const [taskId, entry] of this.running) {
149
+ try {
150
+ signalChild(entry.process, 'SIGKILL');
151
+ } catch {
152
+ // Already dead
153
+ }
154
+ if (this.taskStore) {
155
+ this.taskStore.failTask(taskId, 'Killed during shutdown');
156
+ }
157
+ }
158
+ this.running.clear();
159
+ resolve();
160
+ }, timeoutMs);
161
+ });
162
+
163
+ await Promise.race([waitForCompletion, timeout]);
164
+ this.shutdownInProgress = false;
165
+ }
166
+
167
+ /**
168
+ * Get running task count
169
+ */
170
+ get runningCount() {
171
+ return this.running.size;
172
+ }
173
+
174
+ /**
175
+ * Get queued task count
176
+ */
177
+ get queuedCount() {
178
+ return this.queue.length;
179
+ }
180
+
181
+ // --- Private methods ---
182
+
183
+ _processQueue() {
184
+ while (
185
+ this.running.size < this.maxConcurrency &&
186
+ this.queue.length > 0 &&
187
+ !this.shutdownInProgress
188
+ ) {
189
+ const task = this.queue.shift();
190
+ this._runTask(task);
191
+ }
192
+ }
193
+
194
+ _runTask(task) {
195
+ const args = [...this.agentArgs, '-p', task.prompt];
196
+
197
+ if (task.agent) {
198
+ args.push('--agent', task.agent);
199
+ }
200
+
201
+ const proc = spawn(this.agentCommand, args, {
202
+ stdio: ['ignore', 'pipe', 'pipe'],
203
+ env: { ...(this.environment ?? process.env) },
204
+ });
205
+
206
+ // Track start time
207
+ task.startedAt = new Date().toISOString();
208
+ task.state = 'running';
209
+
210
+ if (this.taskStore) {
211
+ this.taskStore.startTask(task.id, proc.pid);
212
+ }
213
+
214
+ let stdout = '';
215
+ let stderr = '';
216
+
217
+ proc.stdout.on('data', (chunk) => {
218
+ const text = chunk.toString();
219
+ stdout += text;
220
+ if (this.taskStore) {
221
+ this.taskStore.appendOutput(task.id, text);
222
+ }
223
+ this.emit('task:output', { taskId: task.id, chunk: text, stream: 'stdout' });
224
+ });
225
+
226
+ proc.stderr.on('data', (chunk) => {
227
+ const text = chunk.toString();
228
+ stderr += text;
229
+ this.emit('task:output', { taskId: task.id, chunk: text, stream: 'stderr' });
230
+ });
231
+
232
+ // Timeout handler
233
+ const timeoutTimer = setTimeout(() => {
234
+ try {
235
+ signalChild(proc, 'SIGTERM');
236
+ } catch {
237
+ // Already dead
238
+ }
239
+ if (this.taskStore) {
240
+ this.taskStore.failTask(task.id, `Task timed out after ${this.taskTimeout}ms`);
241
+ }
242
+ this.running.delete(task.id);
243
+ this.emit('task:timeout', { taskId: task.id });
244
+ this._processQueue();
245
+ }, this.taskTimeout);
246
+
247
+ proc.on('exit', (code, signal) => {
248
+ clearTimeout(timeoutTimer);
249
+ this.running.delete(task.id);
250
+
251
+ if (signal === 'SIGTERM' || signal === 'SIGKILL') {
252
+ // Cancelled or killed
253
+ if (this.taskStore && this.taskStore.getTask(task.id)?.state === 'running') {
254
+ this.taskStore.cancelTask(task.id);
255
+ }
256
+ this.emit('task:cancelled', { taskId: task.id, signal });
257
+ } else if (code === 0) {
258
+ if (this.taskStore) {
259
+ this.taskStore.completeTask(task.id, stdout);
260
+ }
261
+ this.emit('task:completed', {
262
+ taskId: task.id,
263
+ result: stdout,
264
+ duration: Date.now() - new Date(task.startedAt).getTime(),
265
+ });
266
+ } else {
267
+ const errorMsg = stderr || `Process exited with code ${code}`;
268
+ if (this.taskStore) {
269
+ this.taskStore.failTask(task.id, errorMsg);
270
+ }
271
+ this.emit('task:failed', {
272
+ taskId: task.id,
273
+ error: errorMsg,
274
+ exitCode: code,
275
+ });
276
+ }
277
+
278
+ this._processQueue();
279
+ });
280
+
281
+ proc.on('error', (err) => {
282
+ clearTimeout(timeoutTimer);
283
+ this.running.delete(task.id);
284
+
285
+ if (this.taskStore) {
286
+ this.taskStore.failTask(task.id, err.message);
287
+ }
288
+ this.emit('task:failed', {
289
+ taskId: task.id,
290
+ error: err.message,
291
+ });
292
+
293
+ this._processQueue();
294
+ });
295
+
296
+ this.running.set(task.id, { process: proc, task });
297
+ this.emit('task:started', { taskId: task.id, pid: proc.pid });
298
+ }
299
+ }