@aiwg/cli 2026.10.19 → 2026.11.1

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 (143) hide show
  1. package/README.md +1 -0
  2. package/agentic/code/providers/flue/README.md +2 -1
  3. package/dist/src/artifacts/cli.js +3 -2
  4. package/dist/src/artifacts/discover-facets.js +2 -0
  5. package/dist/src/artifacts/discover-session-facets.js +14 -0
  6. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  7. package/dist/src/artifacts/framework-capabilities.js +7 -3
  8. package/dist/src/artifacts/index-builder.js +2 -3
  9. package/dist/src/artifacts/query-engine-discover-output.js +3 -3
  10. package/dist/src/artifacts/query-engine-discover.js +61 -14
  11. package/dist/src/artifacts/query-engine-entries.js +52 -9
  12. package/dist/src/artifacts/query-engine-installation.js +27 -0
  13. package/dist/src/artifacts/query-engine-rules.js +1 -2
  14. package/dist/src/artifacts/query-engine-scoring.js +33 -31
  15. package/dist/src/artifacts/query-engine-show-card.js +6 -2
  16. package/dist/src/artifacts/query-engine-show.js +2 -2
  17. package/dist/src/artifacts/relations.js +17 -10
  18. package/dist/src/cli/handlers/bundle-declaration.js +55 -0
  19. package/dist/src/cli/handlers/bundle-deployment-mode.js +71 -0
  20. package/dist/src/cli/handlers/bundle-hash-prune.js +37 -0
  21. package/dist/src/cli/handlers/bundle-reconciliation.js +140 -0
  22. package/dist/src/cli/handlers/checkpoint.js +143 -0
  23. package/dist/src/cli/handlers/help.js +1 -0
  24. package/dist/src/cli/handlers/index.js +4 -2
  25. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  26. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  27. package/dist/src/cli/handlers/refresh-bundles.js +35 -0
  28. package/dist/src/cli/handlers/refresh-rule-inventory.js +10 -0
  29. package/dist/src/cli/handlers/refresh.js +15 -52
  30. package/dist/src/cli/handlers/remove-bundled.js +7 -4
  31. package/dist/src/cli/handlers/remove-flue-modules.js +19 -0
  32. package/dist/src/cli/handlers/remove-historical-bundle.js +18 -0
  33. package/dist/src/cli/handlers/remove.js +8 -0
  34. package/dist/src/cli/handlers/script-runner.js +12 -1
  35. package/dist/src/cli/handlers/steward-signing.js +44 -0
  36. package/dist/src/cli/handlers/steward.js +5 -0
  37. package/dist/src/cli/handlers/subcommands-list-format.js +4 -4
  38. package/dist/src/cli/handlers/update.js +18 -8
  39. package/dist/src/cli/handlers/use-additive-bundles.js +87 -0
  40. package/dist/src/cli/handlers/use-bundle-counts.js +5 -1
  41. package/dist/src/cli/handlers/use-owned-counts.js +75 -0
  42. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  43. package/dist/src/cli/handlers/use.js +53 -114
  44. package/dist/src/cli/router.js +12 -2
  45. package/dist/src/cli/services/deployment-verification.js +2 -1
  46. package/dist/src/cli/user-scope-mirror.js +3 -1
  47. package/dist/src/config/aiwg-config.js +15 -6
  48. package/dist/src/config/cli.js +1 -0
  49. package/dist/src/config/delivery-validation.js +21 -0
  50. package/dist/src/config/framework-aliases.js +14 -0
  51. package/dist/src/config/host-resource-report.d.mts +1 -1
  52. package/dist/src/config/host-resource-report.mjs +23 -4
  53. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  54. package/dist/src/config/host-resource-runtime.mjs +67 -24
  55. package/dist/src/config/index-graph-overrides.js +4 -0
  56. package/dist/src/config/installed-selection.js +9 -1
  57. package/dist/src/config/installed-validation.js +35 -0
  58. package/dist/src/config/worker-attribution.d.mts +7 -0
  59. package/dist/src/config/worker-attribution.mjs +44 -0
  60. package/dist/src/delivery/git.js +62 -0
  61. package/dist/src/delivery/pr.js +149 -0
  62. package/dist/src/delivery/tracker.js +33 -0
  63. package/dist/src/discovery/interview.js +1 -1
  64. package/dist/src/extensions/claude-hooks-installer.js +1 -0
  65. package/dist/src/extensions/loader.js +2 -1
  66. package/dist/src/extensions/project-local-doctor.js +1 -1
  67. package/dist/src/extensions/project-local-remove.js +3 -3
  68. package/dist/src/issues/cli.js +12 -3
  69. package/dist/src/issues/external-cli.js +76 -0
  70. package/dist/src/issues/live.js +18 -1
  71. package/dist/src/issues/tracker-policy.js +17 -0
  72. package/dist/src/mcp/cli.mjs +12 -7
  73. package/dist/src/mcp/helpers.mjs +5 -1
  74. package/dist/src/mcp/http-options.mjs +101 -0
  75. package/dist/src/mcp/http-tools.mjs +51 -0
  76. package/dist/src/mcp/http-transport.mjs +201 -0
  77. package/dist/src/mcp/server.mjs +9 -7
  78. package/dist/src/mcp/tool-context.mjs +25 -0
  79. package/dist/src/mcp/tools/orchestration.mjs +2 -1
  80. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  81. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  82. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  83. package/dist/src/models/conductor-data-policy.mjs +94 -5
  84. package/dist/src/models/worker-plan.js +3 -3
  85. package/dist/src/models/worker-selection-policy.js +2 -1
  86. package/dist/src/providers/deployment-lock.js +77 -0
  87. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  88. package/dist/src/providers/deployment-ownership.mjs +127 -19
  89. package/dist/src/providers/deployment-preservation.d.mts +6 -0
  90. package/dist/src/providers/deployment-preservation.mjs +113 -0
  91. package/dist/src/providers/deployment-removal.js +4 -2
  92. package/dist/src/providers/flue-package-mode.js +19 -0
  93. package/dist/src/providers/provider-definitions.js +4 -0
  94. package/dist/src/providers/skill-ownership.mjs +1 -0
  95. package/dist/src/research/reference-match.js +4 -0
  96. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  97. package/dist/src/serve/worker-invocation.js +2 -0
  98. package/dist/src/skills/run.js +5 -0
  99. package/dist/src/smiths/hook-bridge/codex-translator.js +3 -1
  100. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  101. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +6 -0
  102. package/package.json +5 -2
  103. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  104. package/tools/agents/deploy-agents.mjs +21 -1
  105. package/tools/agents/deploy-options.mjs +2 -0
  106. package/tools/agents/providers/base-contract.mjs +7 -1
  107. package/tools/agents/providers/base-inventory.mjs +41 -14
  108. package/tools/agents/providers/base-kernel-skills.mjs +9 -5
  109. package/tools/agents/providers/base-migrations.mjs +1 -0
  110. package/tools/agents/providers/base-skill-copy.mjs +9 -1
  111. package/tools/agents/providers/base.mjs +1 -1
  112. package/tools/agents/providers/claude.mjs +2 -1
  113. package/tools/agents/providers/codex.mjs +5 -1
  114. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  115. package/tools/agents/providers/flue-bundles.mjs +42 -0
  116. package/tools/agents/providers/flue-cloudflare.mjs +20 -0
  117. package/tools/agents/providers/flue-project.mjs +45 -6
  118. package/tools/agents/providers/flue-skill-copy.mjs +25 -0
  119. package/tools/agents/providers/flue-skills.mjs +45 -0
  120. package/tools/agents/providers/flue-specialists.mjs +36 -18
  121. package/tools/agents/providers/flue-validation.mjs +14 -0
  122. package/tools/agents/providers/flue.mjs +12 -8
  123. package/tools/agents/providers/hermes-skill-lifecycle.mjs +1 -0
  124. package/tools/agents/providers/muse-hooks.mjs +4 -0
  125. package/tools/agents/providers/muse-prompt-discovery.mjs +22 -0
  126. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  127. package/tools/agents/providers/rule-delivery-surface.mjs +18 -1
  128. package/tools/agents/providers/rule-deployment-commit.mjs +24 -0
  129. package/tools/agents/providers/rule-deployment-prepare.mjs +4 -0
  130. package/tools/agents/providers/skill-copy-prune.mjs +49 -0
  131. package/tools/agents/providers/stale-artifact-prune.mjs +10 -8
  132. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  133. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  134. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  135. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  136. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  137. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  138. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  139. package/tools/ralph-external/process-monitor.mjs +12 -18
  140. package/tools/ralph-external/session-launcher.mjs +43 -29
  141. package/tools/skills/codex-skill-metadata.mjs +22 -0
  142. package/tools/skills/deploy-skills-codex.mjs +8 -7
  143. package/vscode-extension/schemas/aiwg.config.v1.json +59 -19
@@ -0,0 +1,201 @@
1
+ // Dedicated authenticated Streamable HTTP listener; one SDK server per session.
2
+ import http from 'node:http';
3
+ import fs from 'node:fs/promises';
4
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
5
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
7
+ import { createServer } from './server.mjs';
8
+ import { resolveProjectAiwgDir } from './helpers.mjs';
9
+ import { pinContainedRoot } from '../utils/contained-filesystem.mjs';
10
+ import { remoteToolPolicy } from './http-tools.mjs';
11
+ import { parseHttpOptions, boundedInteger, tokenSource, hostPolicy } from './http-options.mjs';
12
+
13
+ const BODY_LIMIT = 1024 * 1024;
14
+
15
+ function reply(response, status, message) {
16
+ if (response.headersSent || response.destroyed) return;
17
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
18
+ response.end(JSON.stringify({ error: message }));
19
+ }
20
+
21
+ async function readBody(request, response) {
22
+ let size = 0;
23
+ const chunks = [];
24
+ for await (const chunk of request) {
25
+ size += chunk.length;
26
+ if (size > BODY_LIMIT) {
27
+ // Close this connection after the response, rather than drain an unlimited body.
28
+ response.setHeader('Connection', 'close');
29
+ reply(response, 413, 'Request body exceeds 1 MiB');
30
+ return undefined;
31
+ }
32
+ chunks.push(chunk);
33
+ }
34
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
35
+ catch { reply(response, 400, 'Invalid JSON'); }
36
+ }
37
+
38
+ export async function startHttpServer(options) {
39
+ const host = options.host === '[::1]' ? '::1' : options.host ?? '127.0.0.1';
40
+ const loopback = host === '127.0.0.1' || host === '::1' || host === 'localhost';
41
+ if (!loopback && !options.allowRemoteBind) {
42
+ throw new Error('A non-loopback --host requires --allow-remote-bind');
43
+ }
44
+ const port = boundedInteger(options.port ?? 3100, '--port', 0, 65535);
45
+ const maxSessions = boundedInteger(options.maxSessions ?? 8, '--max-sessions', 1, 65535);
46
+ if (!options.projectDir) throw new Error('HTTP requires --project <dir>');
47
+ const projectDir = await fs.realpath(options.projectDir);
48
+ const projectIdentity = await fs.stat(projectDir);
49
+ if (!projectIdentity.isDirectory()) throw new Error('--project must be a directory');
50
+ const authenticate = await tokenSource(options);
51
+ const permittedHost = hostPolicy(host, options.allowedHosts);
52
+ const artifactStore = await pinContainedRoot(await resolveProjectAiwgDir(projectDir), projectDir);
53
+ if (artifactStore.error) throw new Error('Project artifact root is unavailable');
54
+ const policies = new WeakMap();
55
+ const sessions = new Map();
56
+ const entries = new Set(); // Includes pending initializes, so concurrent admission is bounded.
57
+ const idleMs = options.idleTimeoutMs ?? 300_000;
58
+ let closing = false;
59
+ let stopPromise;
60
+ const buildServer = async () => {
61
+ const policy = remoteToolPolicy(projectDir, options.tools);
62
+ const mcp = await createServer({ projectDir, artifactStore, toolsets: options.toolsets ?? '', configureTool: policy.configureTool });
63
+ try { policy.validate(); } catch (error) { await mcp.close(); throw error; }
64
+ policies.set(mcp, policy);
65
+ return mcp;
66
+ };
67
+ // Validate tool selection and registration before binding the listener.
68
+ let warmServer = await buildServer();
69
+ function touch(entry) {
70
+ clearTimeout(entry.timer);
71
+ entry.timer = setTimeout(() => {
72
+ if (policies.get(entry.mcp)?.busy()) touch(entry);
73
+ else void dispose(entry);
74
+ }, idleMs);
75
+ entry.timer.unref();
76
+ }
77
+ async function dispose(entry) {
78
+ if (entry.disposing) return entry.disposing;
79
+ sessions.delete(entry.transport?.sessionId);
80
+ clearTimeout(entry.timer);
81
+ entry.disposing = (async () => {
82
+ try {
83
+ await entry.ready?.catch(() => {});
84
+ await entry.mcp?.close();
85
+ await policies.get(entry.mcp)?.drain();
86
+ }
87
+ finally { entries.delete(entry); }
88
+ })();
89
+ return entry.disposing;
90
+ }
91
+ async function newSession(token) {
92
+ const entry = { token };
93
+ entries.add(entry);
94
+ try {
95
+ entry.mcp = warmServer;
96
+ warmServer = undefined;
97
+ entry.ready = entry.mcp ? Promise.resolve(entry.mcp) : buildServer();
98
+ entry.mcp = await entry.ready;
99
+ if (closing) throw new Error('Listener is draining');
100
+ entry.transport = new StreamableHTTPServerTransport({
101
+ sessionIdGenerator: () => randomUUID(),
102
+ onsessioninitialized: id => { sessions.set(id, entry); touch(entry); },
103
+ onsessionclosed: () => { void dispose(entry); },
104
+ });
105
+ await entry.mcp.connect(entry.transport);
106
+ const sdkClose = entry.transport.onclose;
107
+ entry.transport.onclose = () => {
108
+ sdkClose?.();
109
+ sessions.delete(entry.transport?.sessionId);
110
+ clearTimeout(entry.timer);
111
+ entries.delete(entry);
112
+ };
113
+ return entry;
114
+ } catch (error) {
115
+ entries.delete(entry);
116
+ await entry.mcp?.close();
117
+ throw error;
118
+ }
119
+ }
120
+ const listener = http.createServer(async (request, response) => {
121
+ let created;
122
+ try {
123
+ if (closing) return reply(response, 503, 'Listener is draining');
124
+ const token = await authenticate(request.headers.authorization);
125
+ if (!token) return reply(response, 401, 'Unauthorized');
126
+ if (!permittedHost(request.headers)) return reply(response, 403, 'Host or Origin is not allowed');
127
+ if (request.url !== '/mcp') return reply(response, 404, 'Not found');
128
+ if (!['POST', 'GET', 'DELETE'].includes(request.method)) return reply(response, 405, 'Method not allowed');
129
+ const identity = await fs.stat(projectDir);
130
+ if (await fs.realpath(projectDir) !== projectDir || identity.dev !== projectIdentity.dev || identity.ino !== projectIdentity.ino) {
131
+ return reply(response, 503, 'Pinned project changed; restart the listener');
132
+ }
133
+ const id = request.headers['mcp-session-id'];
134
+ let entry = id && sessions.get(id);
135
+ if (id && (!entry || !timingSafeEqual(entry.token, token) || entry.disposing)) {
136
+ return reply(response, 404, 'Unknown session; initialize again');
137
+ }
138
+ if (Number(request.headers['content-length']) > BODY_LIMIT) {
139
+ response.setHeader('Connection', 'close');
140
+ return reply(response, 413, 'Request body exceeds 1 MiB');
141
+ }
142
+ if (request.method !== 'POST' && (request.headers['transfer-encoding'] || Number(request.headers['content-length']) > 0)) {
143
+ response.setHeader('Connection', 'close');
144
+ return reply(response, 400, 'Only POST requests may carry a body');
145
+ }
146
+ const body = request.method === 'POST' ? await readBody(request, response) : undefined;
147
+ if (response.writableEnded || response.destroyed) return;
148
+ if (closing) return reply(response, 503, 'Listener is draining');
149
+ if (entry?.disposing) return reply(response, 404, 'Unknown session; initialize again');
150
+ if (entry && isInitializeRequest(body)) return reply(response, 404, 'Session ID cannot be reused for initialization');
151
+ if (!entry) {
152
+ if (request.method !== 'POST' || !isInitializeRequest(body)) return reply(response, 400, 'Initialize a new session first');
153
+ if (entries.size >= maxSessions) return reply(response, 503, 'Maximum sessions reached');
154
+ entry = created = await newSession(token);
155
+ }
156
+ touch(entry);
157
+ await entry.transport.handleRequest(request, response, body);
158
+ if (created && !entry.transport.sessionId) await dispose(entry);
159
+ } catch {
160
+ if (created) await dispose(created);
161
+ reply(response, 500, 'MCP transport failed'); // Never log credentials, inputs or SDK errors containing them.
162
+ }
163
+ });
164
+ listener.requestTimeout = 30_000;
165
+ listener.headersTimeout = 10_000;
166
+ try {
167
+ await new Promise((resolve, reject) => {
168
+ listener.once('error', reject);
169
+ listener.listen(port, host, resolve);
170
+ });
171
+ } catch (error) { await warmServer?.close(); throw error; }
172
+ if (!loopback) console.error('WARNING: remote MCP bind enabled; use a trusted TLS proxy and firewall.');
173
+ const closed = new Promise(resolve => listener.once('close', resolve));
174
+ function close() {
175
+ stopPromise ??= (async () => {
176
+ closing = true;
177
+ listener.close();
178
+ await Promise.allSettled([...entries].map(dispose));
179
+ await warmServer?.close();
180
+ listener.closeAllConnections();
181
+ await closed;
182
+ })();
183
+ return stopPromise;
184
+ }
185
+ return { listener, close, closed, projectDir, sessionCount: () => entries.size };
186
+ }
187
+
188
+ export async function serveHttp(args) {
189
+ const service = await startHttpServer(parseHttpOptions(args));
190
+ const address = service.listener.address();
191
+ console.error(`AIWG MCP HTTP listening on ${address.address}:${address.port}/mcp`);
192
+ const stop = () => { void service.close(); };
193
+ process.once('SIGTERM', stop);
194
+ process.once('SIGINT', stop);
195
+ try { await service.closed; }
196
+ finally {
197
+ process.removeListener('SIGTERM', stop);
198
+ process.removeListener('SIGINT', stop);
199
+ await service.close();
200
+ }
201
+ }
@@ -58,7 +58,7 @@ function retainToolJsonSchema(schema, seen = new Set()) {
58
58
  /**
59
59
  * Create and configure the AIWG MCP Server
60
60
  */
61
- export async function createServer() {
61
+ export async function createServer(options = {}) {
62
62
  const server = new McpServer({
63
63
  name: 'aiwg',
64
64
  version: '1.0.0'
@@ -73,7 +73,9 @@ export async function createServer() {
73
73
  retainToolJsonSchema(schema);
74
74
  schemas[key] = schema;
75
75
  }
76
- return registerTool(name, { ...config, ...schemas }, handler);
76
+ const projected = options.configureTool?.(name, { ...config, ...schemas }, handler);
77
+ if (options.configureTool && !projected) return;
78
+ return registerTool(name, projected?.config ?? { ...config, ...schemas }, projected?.handler ?? handler);
77
79
  };
78
80
 
79
81
  // ============================================
@@ -107,7 +109,7 @@ export async function createServer() {
107
109
  };
108
110
  });
109
111
  }
110
- registerWriterProfileResources(server);
112
+ registerWriterProfileResources(server, { projectRoot: options.projectDir });
111
113
 
112
114
  // ============================================
113
115
  // Command-run dispatch (#1312) — registers:
@@ -130,7 +132,7 @@ export async function createServer() {
130
132
  // `all` deliberately does not reach it (src/mcp/tools/subsystems.mjs).
131
133
  // Default: none (core only — discovery + command-run)
132
134
  // ============================================
133
- const requested = parseToolsets(process.env.AIWG_MCP_TOOLSETS || '');
135
+ const requested = parseToolsets(options.toolsets ?? process.env.AIWG_MCP_TOOLSETS ?? '');
134
136
  // #2892 B1: the `workers` toolset's served project root is resolved ONCE,
135
137
  // here, at registration time — never lazily from `process.cwd()` inside
136
138
  // the tool handler on first request. A project root that cannot be found
@@ -139,7 +141,7 @@ export async function createServer() {
139
141
  // back to an implicit cwd.
140
142
  let projectRoot;
141
143
  try {
142
- projectRoot = await findProjectRoot();
144
+ projectRoot = options.projectDir ?? await findProjectRoot();
143
145
  } catch {
144
146
  projectRoot = undefined;
145
147
  }
@@ -152,9 +154,9 @@ export async function createServer() {
152
154
  // must pin its own missing default at startup, never adopt the ancestor's
153
155
  // store. Callers select other projects explicitly via `project_dir`.
154
156
  const artifactEnv = { ...process.env };
155
- const trustedProjectRoot = await fs.realpath(process.cwd());
157
+ const trustedProjectRoot = await fs.realpath(options.projectDir ?? process.cwd());
156
158
  const trustedArtifactRoot = await resolveProjectAiwgDir(trustedProjectRoot, { env: artifactEnv });
157
- const startupStore = await pinArtifactRoot(trustedArtifactRoot, trustedProjectRoot);
159
+ const startupStore = options.artifactStore ?? await pinArtifactRoot(trustedArtifactRoot, trustedProjectRoot);
158
160
  const trustedStore = startupStore.root;
159
161
  const projects = new Map();
160
162
  async function trustProject(requested, store) {
@@ -0,0 +1,25 @@
1
+ // Carry trusted project scope and cancellation through existing CLI-backed tools.
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+
4
+ export const toolContext = new AsyncLocalStorage();
5
+
6
+ export function cliExecutionOptions(options) {
7
+ const context = toolContext.getStore();
8
+ return context ? { ...options, cwd: context.projectDir, signal: context.signal } : options;
9
+ }
10
+
11
+ export function bindCliCancellation(child, signal, terminate) {
12
+ if (!signal) return;
13
+ const children = toolContext.getStore()?.children;
14
+ let release;
15
+ const closed = new Promise(resolve => { release = resolve; });
16
+ children?.add(closed);
17
+ const abort = () => terminate(new Error('MCP tool cancelled'));
18
+ signal.addEventListener('abort', abort, { once: true });
19
+ child.once('close', () => {
20
+ signal.removeEventListener('abort', abort);
21
+ children?.delete(closed);
22
+ release();
23
+ });
24
+ if (signal.aborted) abort();
25
+ }
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { z } from 'zod';
12
+ import { toolContext } from '../tool-context.mjs';
12
13
  import { integer } from '../../schema/zod-validation.mjs';
13
14
  import { showDrillInSchema, showDrillInArgs } from './discovery.mjs';
14
15
  import { parse as parseYaml } from 'yaml';
@@ -19,7 +20,7 @@ import { AIWG_ROOT, mcpError, mcpJson, runAiwgCli } from '../helpers.mjs';
19
20
  function candidateAiwgRoots() {
20
21
  const roots = [
21
22
  AIWG_ROOT,
22
- process.cwd(),
23
+ toolContext.getStore()?.projectDir ?? process.cwd(),
23
24
  ];
24
25
  return [...new Set(roots.map((r) => path.resolve(r)).filter(Boolean))];
25
26
  }
@@ -177,7 +177,7 @@ import path from 'node:path';
177
177
  import { fileURLToPath, pathToFileURL } from 'node:url';
178
178
  import { mcpError, mcpJson } from '../helpers.mjs';
179
179
  import { buildShellStopControl, waitForUnitTermination } from './worker-shell-control.mjs';
180
- import { launchPreparedShellWorker, sweepWorkerStdin } from './worker-stdin-runtime.mjs';
180
+ import { launchPreparedShellWorker, sweepWorkerStdin, markWorkerServer } from './worker-stdin-runtime.mjs';
181
181
  // NOTE: no static import of ../../config/worker-context.js here. That
182
182
  // module is TypeScript: a literal relative import resolves under vitest
183
183
  // but throws ERR_MODULE_NOT_FOUND under raw node (e.g. `node
@@ -1032,6 +1032,7 @@ async function defaultLaunchMcpWorkerProcessBaseline(server, { allowDegraded, co
1032
1032
  }
1033
1033
 
1034
1034
  async function defaultLaunchMcpWorkerProcess(server, { allowDegraded, config, name, cwd, memoryMaxGb = DEFAULT_MCP_WORKER_MEMORY_MAX_GB, live, readers, thresholdOverlay, admission, invocation, invocationId, dispatchGuard }) {
1035
+ server = markWorkerServer(server, invocation, invocationId);
1035
1036
  // #2915 round 8 (D6): see `defaultLaunchShellWorker`'s identical guard —
1036
1037
  // `admission` is only ever present when this attempt is actually gated.
1037
1038
  if (admission === undefined) {
@@ -1,8 +1,16 @@
1
+ // Prepare worker stdin and internal attribution for shell and spawned MCP transports.
2
+ import { directWorkerEnvironment } from '../../config/worker-attribution.mjs';
1
3
  import { createHash } from 'node:crypto';
2
4
  import { mkdtemp, mkdir, writeFile, rm, readdir, lstat } from 'node:fs/promises';
3
5
  import { tmpdir } from 'node:os';
4
6
  import path from 'node:path';
5
7
 
8
+ export function markWorkerServer(server, invocation, invocationId) {
9
+ if (!invocation?.cwd || !invocation?.selected?.group) return server;
10
+ return { ...server, env: { ...server.env,
11
+ ...directWorkerEnvironment({ ...invocation, ...(invocationId ? { invocationId } : {}) }) } };
12
+ }
13
+
6
14
  /** Sweep old private directories only for dead conductors; PID reuse retains
7
15
  * them. Runtime files keep prompts out of git, but cannot isolate same-user workers. */
8
16
  export async function sweepWorkerStdin(root = tmpdir(), { staleMs = 86400000, now = Date.now(),
@@ -57,7 +65,11 @@ export async function launchPreparedShellWorker(invocation, { allowDegraded, con
57
65
  if (bytes !== null) {
58
66
  ({ stdinPath, cleanup } = await prepareWorkerStdin(bytes, stdinRuntimeRoot));
59
67
  }
68
+ const markers = directWorkerEnvironment({ ...invocation, ...(invocationId ? { invocationId } : {}) });
60
69
  const launch = await planDirectWorkerLaunch({ invocation, config, allowDegraded, name, live, readers,
70
+ env: { ...Object.fromEntries((invocation.envNames ?? []).filter(name => process.env[name] !== undefined)
71
+ .map(name => [name, process.env[name]])), ...markers },
72
+ envNames: [...new Set([...(invocation.envNames ?? []), ...Object.keys(markers)])],
61
73
  thresholdOverlay, memoryMaxGb, stdinPath, ownedGroup: true, isolation, admission, invocationId, dispatchGuard,
62
74
  spawn, spawnAsync, onSpawnAttempt: value => {
63
75
  attempt = value;
@@ -4,5 +4,6 @@ import type { ParallelismConfig } from '../config/aiwg-config.js';
4
4
  export const LOCAL_ONLY_PATH_PATTERN: string;
5
5
  export function validLocalOnlyPath(value: unknown): boolean;
6
6
  export function collectLocalOnlyPaths(policy?: WorkerSelectionPolicy, parallelism?: ParallelismConfig): string[];
7
- export function conductorToolDenial(event: { tool_name?: string; tool_input?: Record<string, unknown>; cwd?: string }, root: string, paths: string[]): string | null;
8
- export function runConductorDataHook(root: string, paths: string[]): void;
7
+ export function conductorWorkerTrees(root: string): string[];
8
+ export function conductorToolDenial(event: { tool_name?: string; tool_input?: Record<string, unknown>; cwd?: string }, root: string, paths: string[], workerTrees?: string[]): string | null;
9
+ export function runConductorDataHook(root: string, paths: string[], denyWorkerExecution?: boolean): void;
@@ -1,5 +1,5 @@
1
- // Refuse conductor references, glob reads and ancestor searches of declared local-only inputs.
2
- import { realpathSync, readFileSync, statSync } from 'node:fs';
1
+ // Refuse local-only reads and direct execution of worker output by the conductor.
2
+ import { realpathSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
3
  import { resolve, dirname, relative, isAbsolute, sep, matchesGlob, basename } from 'node:path';
4
4
 
5
5
  // Literal project-relative files or directory subtrees; no globs, traversal or rule syntax.
@@ -144,7 +144,95 @@ function recursiveRoots(words) {
144
144
  return roots.length ? roots : ['.'];
145
145
  }
146
146
 
147
- export function conductorToolDenial(event, root, paths) {
147
+ // Read Git's existing worktree metadata, never invoke Git or a worker-owned helper.
148
+ // Retained worktrees stay untrusted after the worker stops, until integration.
149
+ export function conductorWorkerTrees(root) {
150
+ const trees = [resolve(root, '.aiwg/working/worktrees')];
151
+ try {
152
+ let git = resolve(root, '.git');
153
+ if (!statSync(git).isDirectory()) {
154
+ git = resolve(root, readFileSync(git, 'utf8').trim().replace(/^gitdir: /, ''));
155
+ }
156
+ try { git = resolve(git, readFileSync(resolve(git, 'commondir'), 'utf8').trim()); } catch { /* Main checkout. */ }
157
+ for (const entry of readdirSync(resolve(git, 'worktrees'))) {
158
+ try {
159
+ const metadata = resolve(git, 'worktrees', entry);
160
+ const tree = dirname(resolve(metadata, readFileSync(resolve(metadata, 'gitdir'), 'utf8').trim()));
161
+ if (canonical(tree) !== canonical(root)) trees.push(tree);
162
+ } catch { /* A stale entry must not hide other registered workers. */ }
163
+ }
164
+ } catch { /* Projects without Git metadata still protect the standard worker directory. */ }
165
+ return [...new Set(trees)];
166
+ }
167
+
168
+ const workerExecutionDenial = 'AIWG: conductor must not execute or import worker-written code; use aiwg ralph-external --verify-worker instead';
169
+ const runtime = /^(?:node(?:js)?|python(?:\d+(?:\.\d+)*)?|npm|npx|pnpm|yarn|bun|deno|vitest|jest|pytest|py\.test|mocha|ava|tap|tsx|ts-node|make|cmake|ctest|cargo|go|ruby|perl|php|java)$/;
170
+ const shells = new Set(['sh', 'bash', 'dash', 'zsh']);
171
+ const wrappers = new Set(['env', 'nice', 'timeout', 'systemd-run', 'sudo', 'command', 'exec', 'nohup']);
172
+ const wrapperValues = new Set(['-n', '--adjustment', '-p', '--property', '-u', '--user', '-g', '--group',
173
+ '-C', '--chdir', '--working-directory', '--unit', '--description', '--slice', '--kill-after', '-k', '-s', '--signal']);
174
+
175
+ function workerExecution(command, initialCwd, trees, depth = 0) {
176
+ if (depth > 4) return true;
177
+ const protectedTrees = trees.flatMap(tree => [resolve(tree), canonical(resolve(tree))]);
178
+ const copies = [];
179
+ let cwd = initialCwd;
180
+ const untrusted = candidate => {
181
+ const file = resolve(cwd, candidate.replace(/^file:\/\//, ''));
182
+ return [...protectedTrees, ...copies].some(base => contains(base, file) || contains(base, canonical(file)));
183
+ };
184
+ const references = value => (value.match(/[^\s"'`;&|<>()\[\]{},]+/g) ?? [])
185
+ .some(token => untrusted(token.split('=').at(-1)));
186
+ for (const words of shellCommands(command)) {
187
+ let index = 0;
188
+ while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index]?.value ?? '')) index++;
189
+ let name = basename(words[index]?.value ?? '');
190
+ while (wrappers.has(name)) {
191
+ // Common resource/process wrappers confer no verification authority.
192
+ const wrapper = name;
193
+ index++;
194
+ while (index < words.length) {
195
+ const arg = words[index].value;
196
+ if (arg === '--') { index++; break; }
197
+ if (wrapper === 'env' && /^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) { index++; continue; }
198
+ if (!arg.startsWith('-')) break;
199
+ const [option, assigned] = arg.split('=');
200
+ const takesValue = wrapperValues.has(option) && !(wrapper === 'systemd-run' && option === '--user');
201
+ const value = assigned ?? (takesValue ? words[index + 1]?.value : undefined);
202
+ if (['-C', '--chdir', '--working-directory'].includes(option) && value) cwd = resolve(cwd, value);
203
+ index += takesValue && assigned === undefined ? 2 : 1;
204
+ }
205
+ if (wrapper === 'timeout') index++; // Duration follows timeout's options.
206
+ name = basename(words[index]?.value ?? '');
207
+ }
208
+ const args = words.slice(index + 1).map(word => word.value);
209
+ if (name === 'cd') {
210
+ const target = args.find(arg => arg !== '--' && arg !== '-P' && arg !== '-L');
211
+ if (target) cwd = resolve(cwd, target);
212
+ continue;
213
+ }
214
+ if (['cp', 'mv', 'install'].includes(name)) {
215
+ const operands = args.filter(arg => !arg.startsWith('-'));
216
+ const destination = operands.at(-1);
217
+ for (const source of operands.slice(0, -1)) if (destination && untrusted(source)) {
218
+ copies.push(resolve(cwd, destination), resolve(cwd, destination, basename(source)));
219
+ }
220
+ continue;
221
+ }
222
+ if (words[index]?.value.includes('/') && untrusted(words[index].value)) return true;
223
+ if (shells.has(name)) {
224
+ const inline = args.findIndex(arg => /^-[^-]*c/.test(arg));
225
+ if (inline >= 0 && args[inline + 1] !== undefined) {
226
+ if (workerExecution(args[inline + 1], cwd, [...protectedTrees, ...copies], depth + 1)) return true;
227
+ continue;
228
+ }
229
+ }
230
+ if ((runtime.test(name) || shells.has(name)) && (untrusted('.') || words.some(word => references(word.value)))) return true;
231
+ }
232
+ return false;
233
+ }
234
+
235
+ export function conductorToolDenial(event, root, paths, workerTrees = conductorWorkerTrees(root)) {
148
236
  const input = event.tool_input ?? {};
149
237
  const cwd = typeof event.cwd === 'string' && isAbsolute(event.cwd) ? event.cwd : root;
150
238
  const protectedPaths = paths.flatMap(file => [resolve(root, file), canonical(resolve(root, file))]);
@@ -155,6 +243,7 @@ export function conductorToolDenial(event, root, paths) {
155
243
  };
156
244
  if ([input.file_path, input.path].some(denied)) return 'AIWG: local-only task input is unavailable to this conductor';
157
245
  if (typeof input.command === 'string') {
246
+ if (workerTrees.length && workerExecution(input.command, cwd, workerTrees)) return workerExecutionDenial;
158
247
  // Covers literal/quoted paths, compound commands and common redirections. This is
159
248
  // deliberately conservative, not a shell interpreter or a filesystem sandbox.
160
249
  const command = input.command;
@@ -172,14 +261,14 @@ export function conductorToolDenial(event, root, paths) {
172
261
  return null;
173
262
  }
174
263
 
175
- export function runConductorDataHook(root, paths) {
264
+ export function runConductorDataHook(root, paths, denyWorkerExecution = false) {
176
265
  try {
177
266
  const raw = readFileSync(0, 'utf8');
178
267
  if (Buffer.byteLength(raw) > 1024 * 1024) throw new Error('oversized event');
179
268
  const event = JSON.parse(raw);
180
269
  if (!event || typeof event !== 'object' || typeof event.tool_name !== 'string'
181
270
  || !event.tool_input || typeof event.tool_input !== 'object') throw new Error('invalid event');
182
- const reason = conductorToolDenial(event, root, paths);
271
+ const reason = conductorToolDenial(event, root, paths, denyWorkerExecution ? conductorWorkerTrees(root) : []);
183
272
  if (reason) process.stdout.write(JSON.stringify({ hookSpecificOutput: {
184
273
  hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason,
185
274
  } }) + '\n');
@@ -295,11 +295,11 @@ export function resolveWorkerPlan(snapshot, request, ceilingDefaults = {}) {
295
295
  plan.slots = resources.slots;
296
296
  }
297
297
  if (!resources.ok)
298
- deny('OG_ADAPTER_UNQUALIFIED', '/parallelism/admission/hostResources', resources.failures.map(failure => `${failure.signal}: ${failure.reason}`).join('; '));
298
+ deny(resources.failures.some(failure => failure.code === 'OG_HOST_ATTRIBUTION') ? 'OG_HOST_ATTRIBUTION' : 'OG_HOST_CAPACITY', '/parallelism/admission/hostResources', resources.failures.map(failure => `${failure.signal}: ${failure.reason}`).join('; '));
299
299
  }
300
300
  const effectiveMaxParallel = caps.length ? Math.min(...caps) : null;
301
301
  if (effectiveMaxParallel === 0)
302
- deny('OG_ADAPTER_UNQUALIFIED', '/constraints/maxParallel', 'Current capacity ceiling is zero');
302
+ deny('OG_HOST_CAPACITY', '/constraints/maxParallel', 'Current capacity ceiling is zero');
303
303
  if (!reasons.some(reason => reason.blocking !== false))
304
304
  plan.eligible.push({ ...tuple, cli: member.cli,
305
305
  inferenceProvider: row.llmProvider, modelKey: key, family: observation.family, identityEvidence: binding.identityEvidence,
@@ -336,7 +336,7 @@ export function resolveWorkerPlan(snapshot, request, ceilingDefaults = {}) {
336
336
  ...(request.substitution && matchesChoice(plan.selected, request.substitution) ? { substitution: structuredClone(request.substitution) } : {}) };
337
337
  }
338
338
  if (!plan.selected && plan.resources?.slots === 0) {
339
- block('OG_ADAPTER_UNQUALIFIED', '/parallelism/admission/hostResources', plan.resources.failures.map(failure => `${failure.signal}: ${failure.reason}`).join('; '));
339
+ block(plan.resources.failures.some(failure => failure.code === 'OG_HOST_ATTRIBUTION') ? 'OG_HOST_ATTRIBUTION' : 'OG_HOST_CAPACITY', '/parallelism/admission/hostResources', plan.resources.failures.map(failure => `${failure.signal}: ${failure.reason}`).join('; '));
340
340
  }
341
341
  plan.alternatives = plan.eligible.filter(tuple => tuple !== plan.selected);
342
342
  return plan;
@@ -41,6 +41,7 @@ export const WorkerSelectionPolicySchema = z.strictObject({
41
41
  deniedEfforts: uniqueStrings.optional(),
42
42
  deniedModels: uniqueStrings.optional(),
43
43
  denySelfDelegation: z.boolean().optional(),
44
+ denyConductorWorkerExecution: z.boolean().optional(),
44
45
  requireExactModel: z.boolean().optional(),
45
46
  allowedVisibility: z.array(z.enum(['listed', 'hidden'])).refine(v => new Set(v).size === v.length).optional(),
46
47
  allowedLifecycle: z.array(z.enum(['active', 'deprecated'])).refine(v => new Set(v).size === v.length).optional(),
@@ -150,7 +151,7 @@ export function mergeWorkerSelection(layers) {
150
151
  relaxation = value.some((v) => !previous.includes(v));
151
152
  effective = previous.filter((v) => value.includes(v));
152
153
  }
153
- else if (['denySelfDelegation', 'requireExactModel'].includes(key)) {
154
+ else if (['denySelfDelegation', 'denyConductorWorkerExecution', 'requireExactModel'].includes(key)) {
154
155
  relaxation = previous === true && value === false;
155
156
  effective = previous || value;
156
157
  }
@@ -0,0 +1,77 @@
1
+ // Serialize provider snapshots and writes that share user-home deployment state.
2
+ import path from 'node:path';
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { acquireDirectoryLock, DirectoryLockContentionError } from '../artifacts/prebuilt-build-lock.js';
6
+ import { getUserStateDir } from '../config/user-state.js';
7
+ const ownerVariable = 'AIWG_PROVIDER_DEPLOYMENT_LOCK_OWNER';
8
+ const held = new AsyncLocalStorage();
9
+ /** Forward ownership only to children launched from the owning async operation. */
10
+ export function providerDeploymentLockEnvironment() {
11
+ const owner = held.getStore();
12
+ return owner ? { [ownerVariable]: owner.token } : {};
13
+ }
14
+ export async function acquireProviderDeploymentLock() {
15
+ const lockPath = path.join(getUserStateDir(), 'provider-deployment.lock');
16
+ const local = held.getStore();
17
+ const inherited = local?.lockPath === lockPath ? local.token : process.env[ownerVariable];
18
+ const readOwner = () => readFile(path.join(lockPath, 'owner'), 'utf8').then(value => value.trim());
19
+ let release;
20
+ let token;
21
+ // A stale or forged marker cannot bypass the on-disk lease. Borrowers never
22
+ // remove the parent's lock; only the original acquisition may release it.
23
+ if (inherited && await readOwner().catch(() => undefined) === inherited) {
24
+ token = inherited;
25
+ }
26
+ else {
27
+ release = await acquireSharedLock(lockPath);
28
+ try {
29
+ token = await readOwner();
30
+ }
31
+ catch (error) {
32
+ await release();
33
+ throw error;
34
+ }
35
+ }
36
+ let active = true;
37
+ return Object.assign(async () => {
38
+ if (!active)
39
+ return;
40
+ active = false;
41
+ await release?.();
42
+ }, {
43
+ async run(work) {
44
+ if (!active)
45
+ throw new Error('Provider deployment lock is released');
46
+ return held.run({ lockPath, token }, work);
47
+ },
48
+ });
49
+ }
50
+ async function acquireSharedLock(lockPath) {
51
+ try {
52
+ return await acquireDirectoryLock(lockPath, { timeoutMs: 0, reclaimDeadOwner: true });
53
+ }
54
+ catch (error) {
55
+ if (!(error instanceof DirectoryLockContentionError))
56
+ throw error;
57
+ }
58
+ console.warn(`Waiting for shared user-home provider deployment lock: ${lockPath}`);
59
+ try {
60
+ return await acquireDirectoryLock(lockPath, { timeoutMs: 120_000, reclaimDeadOwner: true });
61
+ }
62
+ catch (error) {
63
+ if (!(error instanceof DirectoryLockContentionError))
64
+ throw error;
65
+ throw new Error(`Timed out waiting for shared user-home provider deployment lock: ${lockPath}`);
66
+ }
67
+ }
68
+ export async function withProviderDeploymentLock(work) {
69
+ const release = await acquireProviderDeploymentLock();
70
+ try {
71
+ return await release.run(work);
72
+ }
73
+ finally {
74
+ await release();
75
+ }
76
+ }
77
+ //# sourceMappingURL=deployment-lock.js.map
@@ -13,8 +13,18 @@ export interface DeploymentOwnershipOptions {
13
13
  logicalInputPath?: (file: string) => string;
14
14
  }
15
15
  export function deploymentOutputRoots(provider: { name: string; paths?: Record<string, string>; kernelSkillsPath?: string; deploymentFiles?: (target: string) => string[] }, target: string): string[];
16
- export function captureDeploymentOutputs(roots: PathLike[]): Map<string, Buffer>;
17
- export function recordDeploymentOutputs(before: Map<string, Buffer>, roots: PathLike[], opts?: DeploymentOwnershipOptions): void;
16
+ /** A file recorded without its bytes: stat signature, plus a digest when it was read. */
17
+ export class DeploymentOutputState {
18
+ constructor(signature: string, digest?: string);
19
+ readonly signature: string;
20
+ readonly hash: string | undefined;
21
+ }
22
+ /** Receipts, settings and receipt-claimed files are Buffers; other files are states. */
23
+ export type DeploymentOutputSnapshot = Map<string, Buffer | DeploymentOutputState>;
24
+ export function outputDigest(entry: Buffer | DeploymentOutputState | undefined): string | undefined;
25
+ export function sameOutput(a: Buffer | DeploymentOutputState | undefined, b: Buffer | DeploymentOutputState | undefined): boolean;
26
+ export function captureDeploymentOutputs(roots: PathLike[], options?: { previous?: DeploymentOutputSnapshot }): DeploymentOutputSnapshot;
27
+ export function recordDeploymentOutputs(before: DeploymentOutputSnapshot, roots: PathLike[], opts?: DeploymentOwnershipOptions): void;
18
28
  export function refreshSettingsDigests(record: { settings?: Record<string, unknown> }): void;
19
29
 
20
30
  export function deploymentOwner(opts: DeploymentOwnershipOptions): string | undefined;