@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,124 @@
1
+ /**
2
+ * Profile scaffolding for daemon initialization.
3
+ *
4
+ * Reads YAML profile templates from agentic/code/daemon-profiles/ and
5
+ * generates .aiwg/daemon.yaml with the selected profile's defaults.
6
+ *
7
+ * @implements Plan: Daemon Starter — Profile System
8
+ */
9
+
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { fileURLToPath } from 'url';
13
+
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+
16
+ /** Default profile name when none specified */
17
+ const DEFAULT_PROFILE = 'manager';
18
+
19
+ /** Where profile templates live in the framework */
20
+ const PROFILES_DIR = path.resolve(__dirname, '../../agentic/code/daemon-profiles');
21
+
22
+ /** Where the generated config goes */
23
+ const OUTPUT_PATH = '.aiwg/daemon.yaml';
24
+
25
+ /** Environment variable template for .env.example */
26
+ const ENV_EXAMPLE = `# AIWG Daemon Environment Variables
27
+ # Copy to .env and fill in your values.
28
+
29
+ # Telegram Bot (get from @BotFather)
30
+ # AIWG_TELEGRAM_TOKEN=
31
+ # AIWG_TELEGRAM_CHAT_ID=
32
+
33
+ # Discord Bot (create at discord.com/developers)
34
+ # AIWG_DISCORD_TOKEN=
35
+ # AIWG_DISCORD_CHANNEL=
36
+
37
+ # Slack Webhook
38
+ # AIWG_SLACK_WEBHOOK_URL=
39
+
40
+ # Web UI auth token (optional)
41
+ # AIWG_WEB_TOKEN=
42
+
43
+ # Webhook secret (optional)
44
+ # AIWG_WEBHOOK_SECRET=
45
+ `;
46
+
47
+ /**
48
+ * List available profile names.
49
+ *
50
+ * @returns {string[]}
51
+ */
52
+ export function listProfiles() {
53
+ if (!fs.existsSync(PROFILES_DIR)) return [];
54
+
55
+ return fs.readdirSync(PROFILES_DIR)
56
+ .filter(f => f.endsWith('.yaml') || f.endsWith('.yml'))
57
+ .map(f => path.basename(f, path.extname(f)));
58
+ }
59
+
60
+ /**
61
+ * Read a profile template.
62
+ *
63
+ * @param {string} name - Profile name (without extension)
64
+ * @returns {string} Raw YAML content
65
+ */
66
+ export function readProfile(name) {
67
+ const yamlPath = path.join(PROFILES_DIR, `${name}.yaml`);
68
+ const ymlPath = path.join(PROFILES_DIR, `${name}.yml`);
69
+
70
+ if (fs.existsSync(yamlPath)) {
71
+ return fs.readFileSync(yamlPath, 'utf8');
72
+ }
73
+ if (fs.existsSync(ymlPath)) {
74
+ return fs.readFileSync(ymlPath, 'utf8');
75
+ }
76
+
77
+ throw new Error(`Profile "${name}" not found. Available: ${listProfiles().join(', ')}`);
78
+ }
79
+
80
+ /**
81
+ * Initialize a daemon config from a profile template.
82
+ *
83
+ * @param {Object} options
84
+ * @param {string} [options.profile] - Profile name (default: "manager")
85
+ * @param {string} [options.outputPath] - Override output path
86
+ * @param {boolean} [options.force] - Overwrite existing config
87
+ * @returns {{ configPath: string, envPath: string|null, profile: string }}
88
+ */
89
+ export function initProfile(options = {}) {
90
+ const profile = options.profile || DEFAULT_PROFILE;
91
+ const outputPath = options.outputPath || OUTPUT_PATH;
92
+ const force = options.force || false;
93
+
94
+ // Check for existing config
95
+ if (fs.existsSync(outputPath) && !force) {
96
+ throw new Error(
97
+ `Config already exists at ${outputPath}. Use --force to overwrite.`
98
+ );
99
+ }
100
+
101
+ // Read profile template
102
+ const content = readProfile(profile);
103
+
104
+ // Ensure output directory exists
105
+ const outputDir = path.dirname(outputPath);
106
+ if (!fs.existsSync(outputDir)) {
107
+ fs.mkdirSync(outputDir, { recursive: true });
108
+ }
109
+
110
+ // Write config
111
+ fs.writeFileSync(outputPath, content, 'utf8');
112
+
113
+ // Write .env.example if it doesn't exist
114
+ let envPath = null;
115
+ const envExamplePath = '.env.example';
116
+ if (!fs.existsSync(envExamplePath)) {
117
+ fs.writeFileSync(envExamplePath, ENV_EXAMPLE, 'utf8');
118
+ envPath = envExamplePath;
119
+ }
120
+
121
+ return { configPath: outputPath, envPath, profile };
122
+ }
123
+
124
+ export default initProfile;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * IPC Client - Unix domain socket client for JSON-RPC 2.0
3
+ *
4
+ * Provides typed RPC calls from CLI commands to the running daemon.
5
+ * Handles connection, timeouts, and reconnection.
6
+ *
7
+ * @implements @.aiwg/requirements/use-cases/UC-IPC-001.md
8
+ * @tests @test/unit/daemon/ipc-client.test.js
9
+ */
10
+
11
+ import net from 'node:net';
12
+ import { EventEmitter } from 'node:events';
13
+
14
+ export class IPCClient extends EventEmitter {
15
+ constructor(socketPath, options = {}) {
16
+ super();
17
+ this.socketPath = socketPath;
18
+ this.socket = null;
19
+ this.buffer = '';
20
+ this.requestId = 0;
21
+ this.pending = new Map(); // id -> { resolve, reject, timer }
22
+ this.connected = false;
23
+ this.defaultTimeout = options.timeout || 30000;
24
+ }
25
+
26
+ /**
27
+ * Connect to the daemon socket
28
+ */
29
+ async connect() {
30
+ if (this.connected) return;
31
+
32
+ return new Promise((resolve, reject) => {
33
+ this.socket = net.createConnection(this.socketPath);
34
+
35
+ const onConnect = () => {
36
+ this.connected = true;
37
+ this.socket.removeListener('error', onError);
38
+ this.emit('connected');
39
+ resolve();
40
+ };
41
+
42
+ const onError = (err) => {
43
+ this.socket.removeListener('connect', onConnect);
44
+ if (err.code === 'ENOENT') {
45
+ reject(new Error('Daemon is not running (socket not found)'));
46
+ } else if (err.code === 'ECONNREFUSED') {
47
+ reject(new Error('Daemon is not accepting connections'));
48
+ } else {
49
+ reject(err);
50
+ }
51
+ };
52
+
53
+ this.socket.once('connect', onConnect);
54
+ this.socket.once('error', onError);
55
+
56
+ this.socket.on('data', (chunk) => {
57
+ this.buffer += chunk.toString();
58
+ this._processBuffer();
59
+ });
60
+
61
+ this.socket.on('close', () => {
62
+ this.connected = false;
63
+ // Reject all pending requests
64
+ for (const [id, entry] of this.pending) {
65
+ clearTimeout(entry.timer);
66
+ entry.reject(new Error('Connection closed'));
67
+ }
68
+ this.pending.clear();
69
+ this.emit('disconnected');
70
+ });
71
+
72
+ this.socket.on('error', (err) => {
73
+ if (this.connected) {
74
+ this.emit('error', err);
75
+ }
76
+ });
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Send a JSON-RPC request and wait for response
82
+ */
83
+ async request(method, params = {}, timeout) {
84
+ if (!this.connected) {
85
+ throw new Error('Not connected to daemon');
86
+ }
87
+
88
+ const timeoutMs = timeout || this.defaultTimeout;
89
+ const id = ++this.requestId;
90
+
91
+ return new Promise((resolve, reject) => {
92
+ const timer = setTimeout(() => {
93
+ this.pending.delete(id);
94
+ reject(new Error(`Request timeout: ${method} (${timeoutMs}ms)`));
95
+ }, timeoutMs);
96
+
97
+ this.pending.set(id, { resolve, reject, timer });
98
+
99
+ const message = JSON.stringify({
100
+ jsonrpc: '2.0',
101
+ method,
102
+ params,
103
+ id,
104
+ }) + '\n';
105
+
106
+ this.socket.write(message);
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Send a notification (no response expected)
112
+ */
113
+ notify(method, params = {}) {
114
+ if (!this.connected) {
115
+ throw new Error('Not connected to daemon');
116
+ }
117
+
118
+ const message = JSON.stringify({
119
+ jsonrpc: '2.0',
120
+ method,
121
+ params,
122
+ }) + '\n';
123
+
124
+ this.socket.write(message);
125
+ }
126
+
127
+ /**
128
+ * Disconnect from the daemon
129
+ */
130
+ disconnect() {
131
+ if (this.socket) {
132
+ this.socket.end();
133
+ this.socket = null;
134
+ this.connected = false;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Check if client is connected
140
+ */
141
+ get isConnected() {
142
+ return this.connected;
143
+ }
144
+
145
+ // --- Private methods ---
146
+
147
+ _processBuffer() {
148
+ let newlineIndex;
149
+ while ((newlineIndex = this.buffer.indexOf('\n')) !== -1) {
150
+ const line = this.buffer.slice(0, newlineIndex);
151
+ this.buffer = this.buffer.slice(newlineIndex + 1);
152
+
153
+ if (!line.trim()) continue;
154
+
155
+ try {
156
+ const message = JSON.parse(line);
157
+ this._handleMessage(message);
158
+ } catch {
159
+ this.emit('error', new Error('Invalid JSON from daemon'));
160
+ }
161
+ }
162
+ }
163
+
164
+ _handleMessage(message) {
165
+ // Check if this is a notification (no id)
166
+ if (message.id === undefined || message.id === null) {
167
+ if (message.method) {
168
+ this.emit('notification', message.method, message.params);
169
+ }
170
+ return;
171
+ }
172
+
173
+ // This is a response to a pending request
174
+ const entry = this.pending.get(message.id);
175
+ if (!entry) return; // Orphaned response, ignore
176
+
177
+ clearTimeout(entry.timer);
178
+ this.pending.delete(message.id);
179
+
180
+ if (message.error) {
181
+ const err = new Error(message.error.message);
182
+ err.code = message.error.code;
183
+ entry.reject(err);
184
+ } else {
185
+ entry.resolve(message.result);
186
+ }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Create a connected client (convenience function)
192
+ */
193
+ export async function createClient(socketPath, options = {}) {
194
+ const client = new IPCClient(socketPath, options);
195
+ await client.connect();
196
+ return client;
197
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * IPC method handlers for ops-toolset tools
3
+ *
4
+ * Registers 7 JSON-RPC methods on the daemon IPC server that expose
5
+ * DaemonSupervisor governance as callable tools:
6
+ * daemon.process.list — Running/queued loops with PID, status, timing
7
+ * daemon.process.kill — Kill a loop's process group (-pid)
8
+ * daemon.resource.snapshot — System CPU, memory, load, uptime
9
+ * daemon.circuit.status — Circuit breaker state and failure count
10
+ * daemon.queue.inspect — Queue depth, oldest entry, priority distribution
11
+ * daemon.loop.history — Completed/failed loop summaries
12
+ * daemon.budget.remaining — Daily budget status
13
+ *
14
+ * @implements #518
15
+ * @tests @test/integration/daemon-ipc-ops.test.mjs
16
+ */
17
+
18
+ import os from 'node:os';
19
+
20
+ /**
21
+ * Register ops-toolset IPC methods on an IPCServer.
22
+ *
23
+ * @param {import('./ipc-server.mjs').IPCServer} ipcServer
24
+ * @param {import('../ralph-external/daemon-supervisor.mjs').DaemonSupervisor} daemonSupervisor
25
+ * @param {object} [options]
26
+ * @param {number} [options.historyLimit=200] - Max completed loop entries to retain
27
+ * @returns {{ getHistory: () => Array }} accessor for test inspection
28
+ */
29
+ export function registerOpsHandlers(ipcServer, daemonSupervisor, options = {}) {
30
+ const historyLimit = options.historyLimit ?? 200;
31
+ const completedHistory = [];
32
+ const startTime = Date.now();
33
+
34
+ // Track completed and failed loops for history
35
+ daemonSupervisor.on('loop:completed', ({ loopId, taskId }) => {
36
+ _pushHistory({
37
+ loopId,
38
+ taskId,
39
+ outcome: 'completed',
40
+ completedAt: new Date().toISOString(),
41
+ });
42
+ });
43
+
44
+ daemonSupervisor.on('loop:failed', ({ loopId, error, permanent, reason }) => {
45
+ _pushHistory({
46
+ loopId,
47
+ outcome: permanent ? 'permanently-failed' : 'failed',
48
+ error: typeof error === 'string' ? error : error?.message || String(error),
49
+ reason: reason || null,
50
+ completedAt: new Date().toISOString(),
51
+ });
52
+ });
53
+
54
+ function _pushHistory(entry) {
55
+ completedHistory.push(entry);
56
+ if (completedHistory.length > historyLimit) {
57
+ completedHistory.shift();
58
+ }
59
+ }
60
+
61
+ ipcServer.registerMethods({
62
+ /**
63
+ * List running and queued loops with PID, status, timing, iteration info.
64
+ */
65
+ 'daemon.process.list': (params) => {
66
+ const status = daemonSupervisor.status();
67
+ const filter = params?.filter || 'all';
68
+
69
+ const running = status.running.map((r) => ({
70
+ loopId: r.loopId,
71
+ pid: r.pid,
72
+ status: 'running',
73
+ startedAt: r.startedAt,
74
+ elapsed: r.startedAt
75
+ ? Date.now() - new Date(r.startedAt).getTime()
76
+ : 0,
77
+ taskId: r.taskId,
78
+ }));
79
+
80
+ const queued = status.queued.map((q) => ({
81
+ loopId: q.loopId,
82
+ status: 'queued',
83
+ position: q.position,
84
+ priority: q.priority,
85
+ enqueuedAt: q.enqueuedAt,
86
+ }));
87
+
88
+ const failed = status.permanentlyFailed.map((id) => ({
89
+ loopId: id,
90
+ status: 'permanently-failed',
91
+ }));
92
+
93
+ if (filter === 'running') return running;
94
+ if (filter === 'queued') return queued;
95
+ if (filter === 'failed') return failed;
96
+ return [...running, ...queued, ...failed];
97
+ },
98
+
99
+ /**
100
+ * Kill a loop's entire process group.
101
+ */
102
+ 'daemon.process.kill': (params) => {
103
+ if (!params?.loopId) {
104
+ const err = new Error('Missing required parameter: loopId');
105
+ err.code = 'INVALID_PARAMS';
106
+ throw err;
107
+ }
108
+
109
+ const signal = params.signal || 'SIGTERM';
110
+ const validSignals = ['SIGTERM', 'SIGKILL', 'SIGINT'];
111
+ if (!validSignals.includes(signal)) {
112
+ const err = new Error(`Invalid signal: ${signal}. Must be one of: ${validSignals.join(', ')}`);
113
+ err.code = 'INVALID_PARAMS';
114
+ throw err;
115
+ }
116
+
117
+ const killed = daemonSupervisor.killProcessGroup(params.loopId, signal);
118
+ return { killed, loopId: params.loopId, signal };
119
+ },
120
+
121
+ /**
122
+ * System resource snapshot: CPU, memory, load average, queue depth, uptime.
123
+ */
124
+ 'daemon.resource.snapshot': () => {
125
+ const totalMem = os.totalmem();
126
+ const freeMem = os.freemem();
127
+ const loadAvg = os.loadavg();
128
+ const cpus = os.cpus();
129
+
130
+ // Calculate CPU usage from all cores
131
+ let totalIdle = 0;
132
+ let totalTick = 0;
133
+ for (const cpu of cpus) {
134
+ const { user, nice, sys, idle, irq } = cpu.times;
135
+ totalTick += user + nice + sys + idle + irq;
136
+ totalIdle += idle;
137
+ }
138
+ const cpuPercent = cpus.length > 0
139
+ ? ((1 - totalIdle / totalTick) * 100).toFixed(1)
140
+ : '0.0';
141
+
142
+ const status = daemonSupervisor.status();
143
+
144
+ return {
145
+ cpu: {
146
+ percent: parseFloat(cpuPercent),
147
+ cores: cpus.length,
148
+ },
149
+ memory: {
150
+ totalMb: Math.round(totalMem / 1024 / 1024),
151
+ usedMb: Math.round((totalMem - freeMem) / 1024 / 1024),
152
+ freeMb: Math.round(freeMem / 1024 / 1024),
153
+ percentUsed: parseFloat(((1 - freeMem / totalMem) * 100).toFixed(1)),
154
+ },
155
+ loadAvg: {
156
+ '1m': loadAvg[0],
157
+ '5m': loadAvg[1],
158
+ '15m': loadAvg[2],
159
+ },
160
+ queueDepth: status.queueDepth,
161
+ uptime: Math.floor((Date.now() - startTime) / 1000),
162
+ };
163
+ },
164
+
165
+ /**
166
+ * Circuit breaker state: closed/open/half-open, failure count, cooldown.
167
+ */
168
+ 'daemon.circuit.status': () => {
169
+ return daemonSupervisor.circuitBreaker.getState();
170
+ },
171
+
172
+ /**
173
+ * Queue inspection: depth, oldest entry, priority distribution.
174
+ */
175
+ 'daemon.queue.inspect': () => {
176
+ const status = daemonSupervisor.status();
177
+
178
+ let oldest = null;
179
+ const priorityDistribution = {};
180
+
181
+ for (const entry of status.queued) {
182
+ // Track oldest
183
+ if (!oldest || entry.enqueuedAt < oldest) {
184
+ oldest = entry.enqueuedAt;
185
+ }
186
+ // Priority distribution
187
+ const pKey = String(entry.priority);
188
+ priorityDistribution[pKey] = (priorityDistribution[pKey] || 0) + 1;
189
+ }
190
+
191
+ return {
192
+ depth: status.queueDepth,
193
+ maxDepth: status.queueMax,
194
+ oldest,
195
+ priorityDistribution,
196
+ estimatedWaitMs: null, // No reliable estimate without historical throughput
197
+ };
198
+ },
199
+
200
+ /**
201
+ * Completed loop history: summaries with outcome, timing, cost.
202
+ */
203
+ 'daemon.loop.history': (params) => {
204
+ const limit = params?.limit ?? 20;
205
+ // Return most recent first
206
+ return completedHistory.slice(-limit).reverse();
207
+ },
208
+
209
+ /**
210
+ * Daily budget status: limit, spent, remaining, percent used.
211
+ */
212
+ 'daemon.budget.remaining': () => {
213
+ const status = daemonSupervisor.status();
214
+
215
+ const dailyLimit = status.budgetLimit;
216
+ const spent = status.budgetUsed;
217
+ const remaining = dailyLimit > 0 ? Math.max(0, dailyLimit - spent) : Infinity;
218
+ const percentUsed = dailyLimit > 0
219
+ ? parseFloat(((spent / dailyLimit) * 100).toFixed(1))
220
+ : 0;
221
+
222
+ return {
223
+ dailyLimit,
224
+ spent: parseFloat(spent.toFixed(4)),
225
+ remaining: dailyLimit > 0 ? parseFloat(remaining.toFixed(4)) : 'unlimited',
226
+ percentUsed,
227
+ currency: 'USD',
228
+ };
229
+ },
230
+ });
231
+
232
+ // Return accessor for testing
233
+ return {
234
+ getHistory: () => completedHistory,
235
+ };
236
+ }