@aiwg/cli 2026.11.6 → 2026.11.8
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.
- package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +3 -2
- package/agentic/code/providers/model-capabilities.v1.json +22 -21
- package/agentic/code/providers/model-catalog.v1.json +11 -10
- package/dist/src/artifacts/browser-export.js +1 -0
- package/dist/src/artifacts/fortemi-core-query-adapter.js +2 -0
- package/dist/src/artifacts/index-builder.js +1 -0
- package/dist/src/artifacts/query-engine-discover-output.js +1 -0
- package/dist/src/artifacts/query-engine-discover.js +2 -2
- package/dist/src/artifacts/query-engine-scoring.js +7 -0
- package/dist/src/artifacts/template-output-kind.js +10 -0
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/cli/handlers/dataset.js +11 -2
- package/dist/src/cli/handlers/refresh-managed-deployment.js +13 -3
- package/dist/src/cli/handlers/refresh-user-hooks.js +102 -0
- package/dist/src/cli/handlers/refresh.js +2 -0
- package/dist/src/cli/handlers/update.js +26 -12
- package/dist/src/cli/handlers/use.js +4 -3
- package/dist/src/cli/handlers/writing.js +7 -1
- package/dist/src/config/worker-guidance-warning.js +8 -0
- package/dist/src/dataset/backend-selection.d.ts +3 -0
- package/dist/src/dataset/backend-selection.js +11 -0
- package/dist/src/dataset/contract-range.d.ts +7 -0
- package/dist/src/dataset/contract-range.js +55 -0
- package/dist/src/dataset/fortemi-execution-bridge.d.ts +2 -0
- package/dist/src/dataset/fortemi-execution-bridge.js +12 -1
- package/dist/src/dataset/index.d.ts +2 -0
- package/dist/src/dataset/index.js +2 -0
- package/dist/src/dataset/orchestration-service.d.ts +1 -1
- package/dist/src/dataset/orchestration-service.js +7 -8
- package/dist/src/dataset/orchestration-types.d.ts +2 -0
- package/dist/src/dataset/service-binding-checkpoints.d.ts +10 -0
- package/dist/src/dataset/service-binding-checkpoints.js +26 -0
- package/dist/src/dataset/service-binding-contract.d.ts +46 -0
- package/dist/src/dataset/service-binding-contract.js +25 -0
- package/dist/src/dataset/service-binding-registry.d.ts +12 -0
- package/dist/src/dataset/service-binding-registry.js +118 -0
- package/dist/src/extensions/manifest.js +23 -7
- package/dist/src/extensions/project-local-doctor.js +2 -1
- package/dist/src/extensions/project-quickref-discovery.js +11 -0
- package/dist/src/extensions/project-quickref.js +4 -7
- package/dist/src/extensions/user-hook-diagnostics.js +16 -1
- package/dist/src/extensions/verified-hook-command.js +7 -0
- package/dist/src/mcp/tools/worker-invoke.mjs +6 -4
- package/dist/src/mcp/tools/worker-launch-ledger.mjs +33 -0
- package/dist/src/mcp/tools/worker-verify-deliver-schema.mjs +22 -6
- package/dist/src/mcp/tools/worker-verify-deliver.mjs +4 -6
- package/dist/src/models/cursor-models.js +92 -0
- package/dist/src/models/model-capabilities.v1.json +22 -21
- package/dist/src/models/model-catalog.v1.json +11 -10
- package/dist/src/models/model-discovery.js +4 -3
- package/dist/src/models/provider-policy.js +1 -1
- package/dist/src/models/worker-health-readiness.js +4 -0
- package/dist/src/models/worker-installation.d.mts +2 -0
- package/dist/src/models/worker-installation.mjs +8 -2
- package/dist/src/models/worker-invocation-policy.js +21 -1
- package/dist/src/models/worker-plan.js +3 -1
- package/dist/src/models/worker-wiring-diagnostics.js +25 -0
- package/dist/src/providers/deployment-input-session.d.mts +2 -0
- package/dist/src/providers/deployment-input-session.mjs +38 -0
- package/dist/src/providers/provider-context-contracts.js +3 -0
- package/dist/src/providers/provider-seeds-1.js +1 -1
- package/dist/src/serve/worker-invocation-preparation.js +52 -33
- package/dist/src/serve/worker-invocation.js +4 -2
- package/dist/src/serve/worker-shell-prompt.d.mts +6 -0
- package/dist/src/serve/worker-shell-prompt.mjs +78 -0
- package/dist/src/smiths/context-pipeline/muse-bridge.js +7 -4
- package/dist/src/smiths/context-pipeline/workspace-audit.js +37 -6
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +3 -1
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +16 -4
- package/dist/src/smiths/context-pipeline/workspace-document.js +4 -2
- package/dist/src/smiths/hook-bridge/codex-trust.js +56 -7
- package/dist/src/smiths/hook-bridge/cursor-translator.js +89 -0
- package/dist/src/smiths/hook-bridge/index.js +4 -1
- package/dist/src/writing/campaign-patterns.js +96 -0
- package/dist/src/writing/campaign-report.js +41 -0
- package/dist/src/writing/contextual-diagnostics.js +30 -5
- package/dist/src/writing/current-patterns.catalogue.json +87 -0
- package/dist/src/writing/current-patterns.js +99 -0
- package/dist/src/writing/prose-mask.js +80 -0
- package/dist/src/writing/structural-patterns.js +126 -0
- package/dist/src/writing/validation-campaign.js +19 -0
- package/dist/src/writing/validation-engine.js +17 -10
- package/dist/src/writing/validation-rules.js +4 -3
- package/package.json +1 -1
- package/schemas/dataset/service-binding.v1.schema.json +70 -0
- package/tools/agents/providers/base-models-platforms.mjs +87 -48
- package/tools/agents/providers/cursor-prompt-discovery.mjs +13 -0
- package/tools/agents/providers/cursor.mjs +2 -0
- package/tools/agents/providers/openclaw-context.mjs +6 -0
- package/tools/agents/providers/openclaw.mjs +14 -12
- package/tools/agents/providers/rule-delivery-surface.mjs +1 -1
- package/tools/agents/providers/rule-deployment-corpus-inputs.mjs +19 -0
- package/tools/agents/providers/rule-deployment-input-session.mjs +40 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +16 -6
- package/tools/agents/providers/rule-presentation.mjs +1 -1
- package/tools/agents/providers/rule-startup.mjs +3 -1
- package/tools/plugin/package-plugins.mjs +2 -0
- package/tools/ralph-external/lib/typed-stop-delivery.mjs +10 -1
- package/tools/ralph-external/lib/worker-delivery-guards.mjs +47 -1
- package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +2 -1
- package/tools/ralph-external/lib/worker-verification-cli.mjs +1 -1
- package/vscode-extension/schemas/aiwg.config.v1.json +13 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Audit declared worker routes without granting qualification or launch authority.
|
|
2
|
+
import { expandWorkerGroupTemplates } from '../config/worker-group-templates.js';
|
|
3
|
+
export function workerWiringDiagnostics(parallelism, policy) {
|
|
4
|
+
const groups = expandWorkerGroupTemplates(parallelism).parallelism?.groups ?? {};
|
|
5
|
+
const diagnostics = [];
|
|
6
|
+
for (const [id, group] of Object.entries(groups)) {
|
|
7
|
+
const roles = new Set([...group.members.filter(member => member.enabled !== false
|
|
8
|
+
&& parallelism?.clis?.[member.cli]?.enabled !== false).flatMap(member => member.roles), ...group.requiredRoles ?? []]);
|
|
9
|
+
for (const role of roles) {
|
|
10
|
+
if (policy?.roleGuidance?.[role]?.groups.includes(id))
|
|
11
|
+
continue;
|
|
12
|
+
diagnostics.push({ code: 'OG_CONFIG_REFERENCE', pointer: `/defaults/workerSelection/roleGuidance/${role}/groups`,
|
|
13
|
+
message: `Group ${JSON.stringify(id)} is outside role guidance for ${role}. Edit models.json: add ${JSON.stringify(id)} to defaults.workerSelection.roleGuidance.${role}.groups.`,
|
|
14
|
+
roles: [role] });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
for (const cli of Object.keys(parallelism?.clis ?? {})) {
|
|
18
|
+
if (Object.values(groups).some(group => group.members.some(member => member.cli === cli)))
|
|
19
|
+
continue;
|
|
20
|
+
diagnostics.push({ code: 'OG_CONFIG_REFERENCE', pointer: `/parallelism/clis/${cli}`, blocking: false,
|
|
21
|
+
message: `Declared CLI ${JSON.stringify(cli)} is used by no group. Add a member with cli=${JSON.stringify(cli)} to parallelism.groups in .aiwg/aiwg.config, or remove parallelism.clis.${cli}.` });
|
|
22
|
+
}
|
|
23
|
+
return diagnostics;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=worker-wiring-diagnostics.js.map
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Own lazily created immutable inputs for one update, including nested redeploys.
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
|
|
4
|
+
const sessions = new AsyncLocalStorage();
|
|
5
|
+
|
|
6
|
+
export async function withDeploymentInputSession(work) {
|
|
7
|
+
const existing = sessions.getStore();
|
|
8
|
+
if (existing && !existing.closed) return work();
|
|
9
|
+
const session = { inputs: new Map(), closed: false };
|
|
10
|
+
return sessions.run(session, async () => {
|
|
11
|
+
let result, workError, failed = false;
|
|
12
|
+
try { result = await work(); }
|
|
13
|
+
catch (error) { workError = error; failed = true; }
|
|
14
|
+
session.closed = true;
|
|
15
|
+
const errors = [];
|
|
16
|
+
for (const { value, dispose } of session.inputs.values()) {
|
|
17
|
+
try { dispose(value); } catch (error) { errors.push(error); }
|
|
18
|
+
}
|
|
19
|
+
session.inputs.clear();
|
|
20
|
+
if (failed) {
|
|
21
|
+
if (errors.length) {
|
|
22
|
+
// Even a frozen or primitive thrown value must keep its identity.
|
|
23
|
+
try { Object.defineProperty(workError, 'disposeErrors', { value: errors, configurable: true }); } catch {}
|
|
24
|
+
}
|
|
25
|
+
throw workError;
|
|
26
|
+
}
|
|
27
|
+
if (errors.length) throw new AggregateError(errors, 'Failed to dispose deployment inputs');
|
|
28
|
+
return result;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Outside an update, keep the established standalone deployment lifecycle. */
|
|
33
|
+
export function deploymentSessionInput(key, create, dispose) {
|
|
34
|
+
const session = sessions.getStore();
|
|
35
|
+
if (!session || session.closed) return undefined;
|
|
36
|
+
if (!session.inputs.has(key)) session.inputs.set(key, { value: create(), dispose });
|
|
37
|
+
return session.inputs.get(key).value;
|
|
38
|
+
}
|
|
@@ -40,6 +40,9 @@ export const CONTEXT_CONTRACTS = {
|
|
|
40
40
|
verification: { method: 'official Copilot CLI custom-instruction imports', source: 'https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions', lastVerified: VERIFIED_ON },
|
|
41
41
|
},
|
|
42
42
|
cursor: {
|
|
43
|
+
promptDiscovery: { delivery: 'hook-bridge', event: 'beforeSubmitPrompt', files: [
|
|
44
|
+
'.cursor/hooks.json', '.cursor/hooks/aiwg-prompt-discovery.cjs',
|
|
45
|
+
] },
|
|
43
46
|
startupFiles: ['AGENTS.md', 'CLAUDE.md', '.cursor/rules/*.mdc'], precedence: ['provider/system', 'project rules', 'root AGENTS.md'],
|
|
44
47
|
loadMode: 'prose-directive', includeSyntax: null, configRegistration: null,
|
|
45
48
|
bootstrapTargets: ['AGENTS.md'], maxContextBytes: null, recommendedMaxLines: 500, nestedContext: false, support: 'supported',
|
|
@@ -4,8 +4,10 @@ import { findPackageRoot } from '../cli/find-package-root.js';
|
|
|
4
4
|
import { workerOutputPaths } from './worker-invocation-paths.js';
|
|
5
5
|
import { directWorkerEnvironment } from '../config/worker-attribution.mjs';
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
7
8
|
import { fileURLToPath } from 'node:url';
|
|
8
9
|
import { validateWorkerArtifacts } from './worker-artifacts.mjs';
|
|
10
|
+
import { shellWorkerPromptPath, shellWorkerArtifactsRefusal } from './worker-shell-prompt.mjs';
|
|
9
11
|
import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
|
|
10
12
|
import { qualificationDigest } from '../models/qualification-digest.mjs';
|
|
11
13
|
import { qualifyWorkerInvocationProfile, assertOperatorWorkerNativeArgv, assertWorkerSelectionAllowed, assertWorkerLaunchMode, requiresWorkerExternalBoundary, assertWorkerHealthQualification, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
|
|
@@ -21,6 +23,11 @@ import { qualifyWorkerInvocationProfile, assertOperatorWorkerNativeArgv, assertW
|
|
|
21
23
|
export function mcpToolSchemaDigest(schema) {
|
|
22
24
|
return `sha256:${createHash('sha256').update(JSON.stringify(schema)).digest('hex')}`;
|
|
23
25
|
}
|
|
26
|
+
/** JSON plans retain launcher/MCP support; only raw shell artifact delivery is refused. */
|
|
27
|
+
export class WorkerShellArtifactsError extends WorkerPolicyError {
|
|
28
|
+
pointer = '/request/format';
|
|
29
|
+
constructor() { super('OG_ADAPTER_UNQUALIFIED', shellWorkerArtifactsRefusal); }
|
|
30
|
+
}
|
|
24
31
|
export async function prepareWorkerInvocation(invocation, qualification) {
|
|
25
32
|
const result = structuredClone(invocation);
|
|
26
33
|
validateWorkerArtifacts(result);
|
|
@@ -110,42 +117,54 @@ export async function prepareWorkerInvocation(invocation, qualification) {
|
|
|
110
117
|
const deadline = qualification.ceilings?.wallSeconds === undefined ? ''
|
|
111
118
|
: `timeout --signal=KILL ${quote(`${Math.min(result.health?.hardTimeoutSeconds ?? Infinity, result.limits.wallSeconds)}s`)} `;
|
|
112
119
|
const markers = Object.entries(directWorkerEnvironment(result)).map(([name, value]) => `${name}=${quote(value)}`).join(' ');
|
|
113
|
-
const worker = `${deadline}env -i${environment ? ` ${environment}` : ''} ${markers} ${result.argv.map(quote).join(' ')}`;
|
|
114
|
-
const outputs = `> ${quote(result.stdoutPath)} 2> ${quote(result.stderrPath)}`;
|
|
115
|
-
if (result.stdin === 'brief-json') {
|
|
116
|
-
const framer = fileURLToPath(new URL('./worker-stdin-frame.mjs', import.meta.url));
|
|
117
|
-
const frame = [process.execPath, framer, result.briefPath, result.selected.model, result.cwd].map(quote).join(' ');
|
|
118
|
-
result.shellCommand = `cd ${quote(result.cwd)} && env -i ${frame} | ${worker} ${outputs}`;
|
|
119
|
-
}
|
|
120
|
-
else if (result.stdin === 'adapter-frame') {
|
|
121
|
-
const binding = qualification.stdinFramerBinding;
|
|
122
|
-
if (!binding || !absolute(binding.storePath) || !/^sha256:[a-f0-9]{64}$/.test(binding.storeDigest)) {
|
|
123
|
-
throw new Error('Adapter stdin framer requires a trusted installation binding');
|
|
124
|
-
}
|
|
125
|
-
const framer = fileURLToPath(new URL('./worker-stdin-frame.mjs', import.meta.url));
|
|
126
|
-
const frame = [process.execPath, framer, '--adapter-frame', result.briefPath, result.cwd,
|
|
127
|
-
result.selected.cli, qualification.adapterId, result.selected.qualificationDigest, result.briefDigest,
|
|
128
|
-
binding.storePath, binding.storeDigest, JSON.stringify(qualification.policy ?? null), result.selected.model].map(quote).join(' ');
|
|
129
|
-
result.shellCommand = `cd ${quote(result.cwd)} && env -i${environment ? ` ${environment}` : ''} ${frame} | ${worker} ${outputs}`;
|
|
130
|
-
}
|
|
131
|
-
else if (result.stdin === 'closed' || result.stdin === 'brief-text') {
|
|
132
|
-
const stdin = result.stdin === 'closed' ? '< /dev/null' : `< ${quote(result.briefPath)}`;
|
|
133
|
-
result.shellCommand = `cd ${quote(result.cwd)} && ${worker} ${stdin} ${outputs}`;
|
|
134
|
-
}
|
|
135
|
-
else {
|
|
136
|
-
throw new Error(`Unsupported worker stdin mode: ${result.stdin}`);
|
|
137
|
-
}
|
|
138
120
|
const root = findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
|
|
139
121
|
if (!root)
|
|
140
122
|
throw new Error('Worker shell handoff requires the installed AIWG package root');
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
123
|
+
const promptPath = shellWorkerPromptPath(result.finalPath);
|
|
124
|
+
// Saved plans must revalidate identically through source and compiled loaders.
|
|
125
|
+
const promptModule = 'src/serve/worker-shell-prompt.mjs';
|
|
126
|
+
const promptRuntime = path.join(root, existsSync(path.join(root, promptModule)) ? promptModule : `dist/${promptModule}`);
|
|
127
|
+
if (result.artifacts?.length) {
|
|
128
|
+
// Raw execution has no launcher-owned artifact cleanup or workspace lifecycle.
|
|
129
|
+
result.shellCommand = [process.execPath, promptRuntime, '--refuse-artifacts', root].map(quote).join(' ');
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
const argv = result.argv.map(token => token === result.briefPath ? promptPath : token);
|
|
133
|
+
const worker = `${deadline}env -i${environment ? ` ${environment}` : ''} ${markers} ${argv.map(quote).join(' ')}`;
|
|
134
|
+
const outputs = `> ${quote(result.stdoutPath)} 2> ${quote(result.stderrPath)}`;
|
|
135
|
+
if (result.stdin === 'brief-json') {
|
|
136
|
+
const frame = [process.execPath, promptRuntime, '--brief-json', root, result.briefPath, result.briefDigest ?? '', result.finalPath, result.selected.model, result.cwd].map(quote).join(' ');
|
|
137
|
+
result.shellCommand = `cd ${quote(result.cwd)} && env -i ${frame} | ${worker} ${outputs}`;
|
|
138
|
+
}
|
|
139
|
+
else if (result.stdin === 'adapter-frame') {
|
|
140
|
+
const binding = qualification.stdinFramerBinding;
|
|
141
|
+
if (!binding || !absolute(binding.storePath) || !/^sha256:[a-f0-9]{64}$/.test(binding.storeDigest)) {
|
|
142
|
+
throw new Error('Adapter stdin framer requires a trusted installation binding');
|
|
143
|
+
}
|
|
144
|
+
const frame = [process.execPath, promptRuntime, '--adapter-frame', root, result.briefPath, result.cwd,
|
|
145
|
+
result.selected.cli, qualification.adapterId, result.selected.qualificationDigest, result.briefDigest,
|
|
146
|
+
binding.storePath, binding.storeDigest, JSON.stringify(qualification.policy ?? null), result.selected.model, result.finalPath].map(quote).join(' ');
|
|
147
|
+
result.shellCommand = `cd ${quote(result.cwd)} && env -i${environment ? ` ${environment}` : ''} ${frame} | ${worker} ${outputs}`;
|
|
148
|
+
}
|
|
149
|
+
else if (result.stdin === 'closed' || result.stdin === 'brief-text') {
|
|
150
|
+
const stdin = result.stdin === 'closed' ? '< /dev/null' : `< ${quote(promptPath)}`;
|
|
151
|
+
result.shellCommand = `cd ${quote(result.cwd)} && ${worker} ${stdin} ${outputs}`;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
throw new Error(`Unsupported worker stdin mode: ${result.stdin}`);
|
|
155
|
+
}
|
|
156
|
+
const guard = path.join(root, 'tools/ralph-external/lib/worker-shell-capture.mjs');
|
|
157
|
+
// Closed probes with no task input need neither a brief file nor a derived prompt.
|
|
158
|
+
const needsPrompt = result.stdin !== 'closed' || result.argv.includes(result.briefPath);
|
|
159
|
+
const binding = { request: { role: qualification.role, task: qualification.task ?? null,
|
|
160
|
+
group: result.selected.group, workdir: result.cwd },
|
|
161
|
+
invocation: { cwd: result.cwd, briefPath: result.briefPath, briefDigest: result.briefDigest, stdin: result.stdin, selected: result.selected },
|
|
162
|
+
paths: { ...workerOutputPaths(result), ...(needsPrompt ? { workerBrief: promptPath } : {}) } };
|
|
163
|
+
// Reserve every output before shell redirection or vendor-owned final writes.
|
|
164
|
+
// Noclobber also protects stream files created between reservation and exec.
|
|
165
|
+
const stage = needsPrompt ? [process.execPath, promptRuntime, '--stage', root, result.briefPath, result.briefDigest ?? '', result.finalPath].map(quote).join(' ') + ' && ' : '';
|
|
166
|
+
result.shellCommand = `${[process.execPath, guard, JSON.stringify(binding)].map(quote).join(' ')} && ${stage}(set -C; ${result.shellCommand})`;
|
|
167
|
+
}
|
|
149
168
|
}
|
|
150
169
|
else {
|
|
151
170
|
const binding = result.mcp;
|
|
@@ -10,7 +10,7 @@ import { workerConfigDigest, validateWorkerHealthConfig } from '../config/aiwg-c
|
|
|
10
10
|
import { intersectWorkerCeilings } from '../models/worker-ceilings.js';
|
|
11
11
|
import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
|
|
12
12
|
import { qualificationDigest } from '../models/qualification-digest.mjs';
|
|
13
|
-
import { prepareWorkerInvocation } from './worker-invocation-preparation.js';
|
|
13
|
+
import { prepareWorkerInvocation, WorkerShellArtifactsError } from './worker-invocation-preparation.js';
|
|
14
14
|
export { prepareWorkerInvocation, mcpToolSchemaDigest } from './worker-invocation-preparation.js';
|
|
15
15
|
import { isOperatorQualifiedWorkerAdapter, assertOperatorWorkerNativeArgv, assertWorkerLaunchMode, WorkerRoleEffortError, WorkerQualificationPolicyError, requiredWorkerControls, isCanonicalWorkerModelKey, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
|
|
16
16
|
/** Frozen per-attempt windows; parent/transport ceilings include time already spent. */
|
|
@@ -367,6 +367,8 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
367
367
|
};
|
|
368
368
|
await driver.mcpRegistry.assertWorkerQualified(profile.mcp.serverRef, input);
|
|
369
369
|
}
|
|
370
|
+
if (request.format === 'shell' && prepared.transport === 'shell' && prepared.artifacts?.length)
|
|
371
|
+
throw new WorkerShellArtifactsError();
|
|
370
372
|
plan.invocation = prepared;
|
|
371
373
|
pointer = '/request/brief';
|
|
372
374
|
const rechecked = await readBrief(request.brief);
|
|
@@ -395,7 +397,7 @@ export function workerInvocationDiagnostic(error, pointer, fallback = 'OG_CONFIG
|
|
|
395
397
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
396
398
|
if (error instanceof WorkerRoleEffortError)
|
|
397
399
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
398
|
-
if (error instanceof WorkerPathScopeError || error instanceof WorkerRequestArgumentError) {
|
|
400
|
+
if (error instanceof WorkerPathScopeError || error instanceof WorkerRequestArgumentError || error instanceof WorkerShellArtifactsError) {
|
|
399
401
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
400
402
|
}
|
|
401
403
|
if (error instanceof WorkerInvocationCheckError)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Private prompt staging shared by shell rendering and its runtime envelope. */
|
|
2
|
+
export function shellWorkerPromptPath(finalPath: string): string;
|
|
3
|
+
export const shellWorkerArtifactsRefusal: string;
|
|
4
|
+
export function stageShellWorkerPrompt(root: string, briefPath: string, briefDigest: string, finalPath: string): Promise<string>;
|
|
5
|
+
export function frameShellWorkerPrompt(root: string, args: string[]): Promise<Buffer>;
|
|
6
|
+
export function frameShellWorkerJson(root: string, args: string[]): Promise<string>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Stage and frame the shared final-output contract for raw shell handoffs.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { workerStdinBytes, workerStdinDocument } from './worker-stdin-frame.mjs';
|
|
7
|
+
|
|
8
|
+
export const shellWorkerPromptPath = finalPath => `${finalPath}.worker-brief`;
|
|
9
|
+
export const shellWorkerArtifactsRefusal = 'Raw shell rendering does not support worker artifacts; use the launcher with a JSON plan or MCP worker-invoke for workspace materialization and cleanup.';
|
|
10
|
+
|
|
11
|
+
// The renderer supplies its own installed package root, never a task module path.
|
|
12
|
+
async function runtime(root) {
|
|
13
|
+
const loadRalphExternal = relative => import(pathToFileURL(path.join(root, 'tools/ralph-external', relative)).href);
|
|
14
|
+
const { importImpl } = await import(pathToFileURL(path.join(root, 'tools/_resolve-impl.mjs')).href);
|
|
15
|
+
const { inspectWorkerPath } = await importImpl(import.meta.url, 'serve/worker-invocation-paths.js');
|
|
16
|
+
const { boundedPrivateRead, withWorkerPath } = await loadRalphExternal('lib/worker-inputs.mjs');
|
|
17
|
+
const { workerPromptBrief } = await loadRalphExternal('lib/worker-prompt.mjs');
|
|
18
|
+
return { importImpl, withWorkerPath, workerPromptBrief,
|
|
19
|
+
read: (filename, limit) => boundedPrivateRead(filename, limit, inspectWorkerPath) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function stageShellWorkerPrompt(root, briefPath, briefDigest, finalPath) {
|
|
23
|
+
const api = await runtime(root);
|
|
24
|
+
const brief = await api.read(briefPath, 262144);
|
|
25
|
+
if (`sha256:${createHash('sha256').update(brief).digest('hex')}` !== briefDigest) {
|
|
26
|
+
throw new Error('Worker prompt digest changed; resolve again');
|
|
27
|
+
}
|
|
28
|
+
const filename = shellWorkerPromptPath(finalPath);
|
|
29
|
+
// Exclusive creation and pinned ancestors preserve existing files and symlinks.
|
|
30
|
+
await api.withWorkerPath(filename, target => writeFile(target, api.workerPromptBrief(brief, finalPath), { flag: 'wx', mode: 0o600 }));
|
|
31
|
+
return filename;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function frameShellWorkerPrompt(root, args) {
|
|
35
|
+
const [filename, workspace, cli, adapterId, scopeDigest, briefDigest, storePath, storeDigest, policyJson, model, finalPath] = args;
|
|
36
|
+
const api = await runtime(root);
|
|
37
|
+
const brief = await api.read(filename, 262144);
|
|
38
|
+
if (`sha256:${createHash('sha256').update(brief).digest('hex')}` !== briefDigest) throw new Error('Adapter stdin brief changed');
|
|
39
|
+
const prompt = await api.read(shellWorkerPromptPath(finalPath), 1048576);
|
|
40
|
+
if (!prompt.equals(api.workerPromptBrief(brief, finalPath))) throw new Error('Worker shell prompt changed');
|
|
41
|
+
// Reuse the host-bound installation loader and the existing adapter framer.
|
|
42
|
+
const { loadRecordedWorkerInstallations } = await api.importImpl(import.meta.url, 'models/worker-installation.mjs');
|
|
43
|
+
const { loadProviderModelCapabilities } = await api.importImpl(import.meta.url, 'models/provider-policy.js');
|
|
44
|
+
const { drivers } = await loadRecordedWorkerInstallations({ registry: loadProviderModelCapabilities(),
|
|
45
|
+
cwd: workspace, policy: JSON.parse(policyJson) ?? undefined, cli, storePath, storeDigest });
|
|
46
|
+
const driver = drivers[cli];
|
|
47
|
+
if (!driver || driver.qualification.adapterId !== adapterId
|
|
48
|
+
|| driver.qualification.adapter.invocation.stdin !== 'adapter-frame'
|
|
49
|
+
|| driver.qualification.installation?.evidence?.scopeDigest !== scopeDigest) throw new Error('Adapter stdin binding changed');
|
|
50
|
+
return workerStdinBytes({ stdin: 'adapter-frame', selected: { model } }, prompt, driver);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function frameShellWorkerJson(root, args) {
|
|
54
|
+
const [filename, briefDigest, finalPath, model, cwd] = args;
|
|
55
|
+
const api = await runtime(root);
|
|
56
|
+
const brief = await api.read(filename, 262144);
|
|
57
|
+
if (`sha256:${createHash('sha256').update(brief).digest('hex')}` !== briefDigest) throw new Error('Worker prompt digest changed');
|
|
58
|
+
const prompt = await api.read(shellWorkerPromptPath(finalPath), 1048576);
|
|
59
|
+
if (!prompt.equals(api.workerPromptBrief(brief, finalPath))) throw new Error('Worker shell prompt changed');
|
|
60
|
+
return workerStdinDocument({ brief: prompt, model, cwd });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
64
|
+
const [mode, root, ...args] = process.argv.slice(2);
|
|
65
|
+
try {
|
|
66
|
+
if (mode === '--stage' && args.length === 3) await stageShellWorkerPrompt(root, ...args);
|
|
67
|
+
else if (mode === '--refuse-artifacts' && args.length === 0) {
|
|
68
|
+
const api = await runtime(root);
|
|
69
|
+
const { WorkerPolicyError } = await api.importImpl(import.meta.url, 'models/provider-policy.js');
|
|
70
|
+
throw new WorkerPolicyError('OG_ADAPTER_UNQUALIFIED', shellWorkerArtifactsRefusal);
|
|
71
|
+
} else if (mode === '--brief-json' && args.length === 5) process.stdout.write(await frameShellWorkerJson(root, args));
|
|
72
|
+
else if (mode === '--adapter-frame' && args.length === 11) process.stdout.write(await frameShellWorkerPrompt(root, args));
|
|
73
|
+
else throw new Error('Invalid worker shell prompt request');
|
|
74
|
+
} catch (error) {
|
|
75
|
+
process.stderr.write(`Worker shell prompt refused: ${error.code ? `${error.code}: ` : ''}${error.message}\n`);
|
|
76
|
+
process.exitCode = 1;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Muse Code reads project AGENTS.md natively — but only after the workspace
|
|
6
6
|
* is explicitly trusted (first-run trust prompt). The bridge therefore leads
|
|
7
7
|
* with the trust-gated load, follows the Muse-native instruction order
|
|
8
|
-
* (this AGENTS.md first, then WORKSPACE.md
|
|
8
|
+
* (this AGENTS.md first, discovery, then WORKSPACE.md and AIWG.md), and states the
|
|
9
9
|
* discover-first protocol (`aiwg discover` / `aiwg show`) with no auto-load
|
|
10
10
|
* claims for other AIWG paths. Artifact references and one-sentence
|
|
11
11
|
* summaries only — never full bodies — per
|
|
@@ -30,14 +30,17 @@ export function buildMuseBridgeText() {
|
|
|
30
30
|
'file does not load: trust the workspace when prompted, then start a new',
|
|
31
31
|
'Muse session so the bridge is read.',
|
|
32
32
|
'',
|
|
33
|
-
'Instruction order: this AGENTS.md first
|
|
33
|
+
'Instruction order: this AGENTS.md first (native startup context).',
|
|
34
|
+
'On every new directive, run `aiwg discover "<intent>"` as the first information-gathering call,',
|
|
35
|
+
'before reading WORKSPACE.md, AIWG.md, the rules index, or quickrefs; this includes coding, decline, and bug-report requests.',
|
|
36
|
+
'After discovery, read and follow [WORKSPACE.md](./WORKSPACE.md)',
|
|
34
37
|
'for project/operator context, then [AIWG.md](./AIWG.md), the single generated',
|
|
35
38
|
'context for AIWG discovery, quickrefs, and framework routing.',
|
|
36
39
|
'Plain Markdown links are explicit reading instructions; AIWG does not',
|
|
37
40
|
'claim Muse auto-loads any other AIWG path on its own.',
|
|
38
41
|
'',
|
|
39
|
-
'
|
|
40
|
-
'
|
|
42
|
+
"For AIWG lookup, never open `.agents/skills/**` or `agentic/code/**`, including a discovered skill's mirror file or a template. After discover, use `aiwg show <type> <name>` and its drill-ins (`--section`, `--rules --with-rule-bodies`, `--body`); read required rules before governed work.",
|
|
43
|
+
'Prefer indexed',
|
|
41
44
|
'agents, skills, rules, and commands over guessing. Store artifact',
|
|
42
45
|
'references and one-sentence summaries only — never paste full artifact',
|
|
43
46
|
'bodies into context or memory.',
|
|
@@ -9,8 +9,23 @@ import { providerForPath } from './workspace-document.js';
|
|
|
9
9
|
import { extractExistingProjectContext } from './workspace-extraction.js';
|
|
10
10
|
import { projectOutputPath } from './workspace-migration.js';
|
|
11
11
|
export function directives(content) {
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
const lines = content.split('\n');
|
|
13
|
+
return [...new Set(lines
|
|
14
|
+
.filter((line, index) => {
|
|
15
|
+
const trimmed = line.trim();
|
|
16
|
+
// Markdown structure and canonical context bridges are not operator policy.
|
|
17
|
+
if (/^#{1,6}\s|^(?:[-*_]\s*){3,}$|^=+$/.test(trimmed))
|
|
18
|
+
return false;
|
|
19
|
+
if (/^\s*(?:=+|-+)\s*$/.test(lines[index + 1] ?? ''))
|
|
20
|
+
return false;
|
|
21
|
+
if (/^@(?:\.\/|\.aiwg\/)?(?:AIWG|WORKSPACE|AGENTS|CLAUDE|WARP)\.md\s*$/.test(trimmed))
|
|
22
|
+
return false;
|
|
23
|
+
if (/^Read and follow \[WORKSPACE\.md\]\(\.\/WORKSPACE\.md\) first\.$/.test(trimmed))
|
|
24
|
+
return false;
|
|
25
|
+
if (/^Then read \[AIWG\.md\]\(\.\/AIWG\.md\) for AIWG discovery, quickrefs, and framework routing\.$/.test(trimmed))
|
|
26
|
+
return false;
|
|
27
|
+
return true;
|
|
28
|
+
})
|
|
14
29
|
.map((line) => line.replace(/^\s*[-*+]\s+/, '').replace(/^#+\s+/, '').trim())
|
|
15
30
|
.filter((line) => line.length >= 8 && !line.startsWith('<!--') && !/^https?:\/\//i.test(line)))];
|
|
16
31
|
}
|
|
@@ -69,7 +84,9 @@ function operatorContext(relativePath, content, preserveLines = false) {
|
|
|
69
84
|
// content (#277, pre-existing) plus two reserved, self-identifying names
|
|
70
85
|
// that are never legitimately a real project directory.
|
|
71
86
|
export const CONTEXT_WALK_ALWAYS_IGNORED_DIR_NAMES = new Set([
|
|
72
|
-
'.git', 'node_modules', 'dist', 'build', 'coverage', '.aiwg',
|
|
87
|
+
'.git', 'node_modules', 'dist', 'build', 'coverage', '.aiwg', '.index',
|
|
88
|
+
// These files were already excluded after traversal; prune their entire trees.
|
|
89
|
+
'fixtures', 'templates',
|
|
73
90
|
]);
|
|
74
91
|
// Cache/registry directory names that are only skipped when the walk root
|
|
75
92
|
// is the home directory itself (#277 fix-round). A project subtree that
|
|
@@ -157,13 +174,22 @@ export async function nestedInstructionFiles(projectPath) {
|
|
|
157
174
|
const isHomeDirectory = path.resolve(projectPath) === path.resolve(homedir());
|
|
158
175
|
const maxDepth = isHomeDirectory ? 1 : CONTEXT_WALK_MAX_DEPTH;
|
|
159
176
|
let visitedDirectories = 0;
|
|
160
|
-
|
|
177
|
+
const bounds = new Map();
|
|
178
|
+
const subtreeVisits = new Map();
|
|
161
179
|
async function walk(directory, depth) {
|
|
162
180
|
if (depth > maxDepth || visitedDirectories >= CONTEXT_WALK_MAX_DIRECTORIES) {
|
|
163
|
-
|
|
181
|
+
const bound = depth > maxDepth ? 'depth' : 'directories';
|
|
182
|
+
if (!bounds.has(bound))
|
|
183
|
+
bounds.set(bound, {
|
|
184
|
+
limit: bound === 'depth' ? maxDepth : CONTEXT_WALK_MAX_DIRECTORIES,
|
|
185
|
+
path: path.relative(projectPath, directory).replace(/\\/g, '/'),
|
|
186
|
+
});
|
|
164
187
|
return;
|
|
165
188
|
}
|
|
166
189
|
visitedDirectories += 1;
|
|
190
|
+
const subtree = path.relative(projectPath, directory).split(path.sep)[0];
|
|
191
|
+
if (subtree)
|
|
192
|
+
subtreeVisits.set(subtree, (subtreeVisits.get(subtree) ?? 0) + 1);
|
|
167
193
|
let entries;
|
|
168
194
|
try {
|
|
169
195
|
entries = await fs.readdir(directory, { withFileTypes: true });
|
|
@@ -191,7 +217,11 @@ export async function nestedInstructionFiles(projectPath) {
|
|
|
191
217
|
}
|
|
192
218
|
}
|
|
193
219
|
await walk(projectPath, 1);
|
|
194
|
-
|
|
220
|
+
const busiest = [...subtreeVisits].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
|
|
221
|
+
const truncations = [...bounds].map(([bound, detail]) => ({
|
|
222
|
+
bound, ...detail, subtree: busiest?.[0] ?? '.', visitedDirectories: busiest?.[1] ?? visitedDirectories,
|
|
223
|
+
}));
|
|
224
|
+
return { files: found.sort((a, b) => a.localeCompare(b)), truncated: bounds.size > 0, truncations };
|
|
195
225
|
}
|
|
196
226
|
export async function migratedProviderFiles(projectPath) {
|
|
197
227
|
const directory = projectAiwgPath(projectPath, 'context', 'providers');
|
|
@@ -302,6 +332,7 @@ export async function auditWorkspaceContext(projectPath) {
|
|
|
302
332
|
conflicts,
|
|
303
333
|
sensitiveFindings,
|
|
304
334
|
contextWalkTruncated: nested.truncated,
|
|
335
|
+
contextWalkTruncations: nested.truncations,
|
|
305
336
|
plan: {
|
|
306
337
|
routing,
|
|
307
338
|
scopeReview,
|
|
@@ -18,6 +18,8 @@ const PROSE_LOADING = [
|
|
|
18
18
|
'Then read [AIWG.md](./AIWG.md) for AIWG discovery, quickrefs, and framework routing.',
|
|
19
19
|
'',
|
|
20
20
|
'These are explicit reading instructions. Plain Markdown links are not claimed to auto-load.',
|
|
21
|
+
'',
|
|
22
|
+
"For AIWG lookup, never open `.agents/skills/**` or `agentic/code/**`, including a discovered skill's mirror file or a template. After discover, use `aiwg show <type> <name>` and its drill-ins (`--section`, `--rules --with-rule-bodies`, `--body`); read required rules before governed work.",
|
|
21
23
|
];
|
|
22
24
|
function wrapProviderBootstrap(loading) {
|
|
23
25
|
return [
|
|
@@ -53,7 +55,7 @@ export function buildProviderBootstrapBlock(provider) {
|
|
|
53
55
|
// A session directive that arrives later cannot claim precedence it was never
|
|
54
56
|
// granted (#2512).
|
|
55
57
|
// #227: Muse gets its own discover-first bridge text — Muse-native
|
|
56
|
-
// instruction order (
|
|
58
|
+
// instruction order (discovery, then WORKSPACE.md, then AIWG.md)
|
|
57
59
|
// plus the trust-gated load caveat — instead of the generic prose-directive.
|
|
58
60
|
const loading = provider === 'muse'
|
|
59
61
|
? [buildMuseBridgeText()]
|
|
@@ -39,7 +39,7 @@ export async function workspaceLinkedFiles(projectPath) {
|
|
|
39
39
|
return [...new Set(files)].sort();
|
|
40
40
|
}
|
|
41
41
|
export async function diagnoseWorkspaceContext(projectPath) {
|
|
42
|
-
const diagnostics = await diagnoseUserHookCommands();
|
|
42
|
+
const diagnostics = await diagnoseUserHookCommands(projectPath);
|
|
43
43
|
const codexTrust = await diagnoseCodexHookTrust(projectPath);
|
|
44
44
|
if (codexTrust)
|
|
45
45
|
diagnostics.push(codexTrust);
|
|
@@ -95,7 +95,7 @@ export async function diagnoseWorkspaceContext(projectPath) {
|
|
|
95
95
|
diagnostics.push({
|
|
96
96
|
severity: 'info',
|
|
97
97
|
code: 'context-walk-truncated',
|
|
98
|
-
message:
|
|
98
|
+
message: `Nested-instruction-file walk stopped early: ${audit.contextWalkTruncations?.map((hit) => `${hit.bound}=${hit.limit} reached at ${hit.path}; busiest subtree ${hit.subtree} (${hit.visitedDirectories} visited directories)`).join('; ')}; the context graph may be incomplete.`,
|
|
99
99
|
});
|
|
100
100
|
}
|
|
101
101
|
const workspacePath = path.join(projectPath, 'WORKSPACE.md');
|
|
@@ -142,8 +142,20 @@ export async function diagnoseWorkspaceContext(projectPath) {
|
|
|
142
142
|
// and degrades the workspace over content that agrees with itself (#2558).
|
|
143
143
|
const duplicatesByPair = new Map();
|
|
144
144
|
for (const overlap of audit.identical) {
|
|
145
|
-
|
|
146
|
-
|
|
145
|
+
// Shared boilerplate in independent repositories is outside a single load scope.
|
|
146
|
+
const byScope = new Map();
|
|
147
|
+
for (const source of overlap.sources) {
|
|
148
|
+
const scope = await directoryScope(path.dirname(path.resolve(root, source)));
|
|
149
|
+
const paths = byScope.get(scope) ?? [];
|
|
150
|
+
paths.push(source);
|
|
151
|
+
byScope.set(scope, paths);
|
|
152
|
+
}
|
|
153
|
+
for (const paths of byScope.values()) {
|
|
154
|
+
if (paths.length < 2)
|
|
155
|
+
continue;
|
|
156
|
+
const key = paths.join(', ');
|
|
157
|
+
duplicatesByPair.set(key, (duplicatesByPair.get(key) ?? 0) + overlap.directives.length);
|
|
158
|
+
}
|
|
147
159
|
}
|
|
148
160
|
const operatorBodies = new Map(audit.sources.map((source) => [source.path, source.operatorContent.trim()]));
|
|
149
161
|
for (const [pair, count] of duplicatesByPair) {
|
|
@@ -103,8 +103,10 @@ export function buildWorkspaceManagedBlock(projectPath, providerFiles = [], resi
|
|
|
103
103
|
'## AIWG Context Graph',
|
|
104
104
|
'',
|
|
105
105
|
'This file is the canonical provider-neutral home for project and operator context.',
|
|
106
|
-
'Provider startup files are generated adapters
|
|
107
|
-
'
|
|
106
|
+
'Provider startup files are generated adapters and native startup context.',
|
|
107
|
+
'On every new directive, run `aiwg discover` before tool-based context reads;',
|
|
108
|
+
'then read WORKSPACE.md, then AIWG.md for framework discovery and routing.',
|
|
109
|
+
'This read order does not change the policy precedence below.',
|
|
108
110
|
'',
|
|
109
111
|
'### Precedence',
|
|
110
112
|
'',
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
// Read Codex project
|
|
1
|
+
// Read Codex trust and deduplicate trusted-project advice without granting hook approval.
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
2
4
|
import { promises as fs } from 'node:fs';
|
|
3
5
|
import { homedir } from 'node:os';
|
|
4
6
|
import * as path from 'node:path';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
5
8
|
import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
|
|
9
|
+
import { getUserStateDir } from '../../config/user-state.js';
|
|
10
|
+
import { workerVersionProbeEnvironment } from '../../models/worker-installation.mjs';
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
6
12
|
// Printed after deploy: one line that fits an 80-column terminal.
|
|
7
13
|
export const CODEX_HOOK_TRUST_NEXT_STEP = 'Trust this project in Codex and approve its AIWG hook; codex exec needs both.';
|
|
8
14
|
// Full explanation for doctor and docs (#4035).
|
|
9
|
-
export const CODEX_EXEC_HOOK_TRUST_DETAIL = 'Codex
|
|
15
|
+
export const CODEX_EXEC_HOOK_TRUST_DETAIL = 'Codex requires saved folder and hook trust for codex exec; a per-run -c project trust override '
|
|
10
16
|
+ 'does not enable project hooks, even with --dangerously-bypass-hook-trust. '
|
|
11
17
|
+ 'Review and save trust interactively for each worker worktree before automation; AIWG never grants trust.';
|
|
12
18
|
export function codexHookTrustNextStep(trust) {
|
|
@@ -28,7 +34,7 @@ export async function readCodexHookTrust(projectPath) {
|
|
|
28
34
|
// Missing/broken installations are handled by deployment drift checks.
|
|
29
35
|
return null;
|
|
30
36
|
}
|
|
31
|
-
//
|
|
37
|
+
// A notice marker is not evidence of Codex hook approval; keep that state unknown.
|
|
32
38
|
const trust = { project: 'unknown', hookReview: 'unknown' };
|
|
33
39
|
const codexHome = process.env.CODEX_HOME || path.join(process.env.HOME || homedir(), '.codex');
|
|
34
40
|
try {
|
|
@@ -42,14 +48,57 @@ export async function readCodexHookTrust(projectPath) {
|
|
|
42
48
|
}
|
|
43
49
|
return trust;
|
|
44
50
|
}
|
|
51
|
+
async function codexHookAdvisoryAlreadyShown(projectPath) {
|
|
52
|
+
const root = path.resolve(projectPath);
|
|
53
|
+
try {
|
|
54
|
+
const codexHome = path.resolve(process.env.CODEX_HOME || path.join(process.env.HOME || homedir(), '.codex'));
|
|
55
|
+
const registration = await fs.readFile(path.join(root, '.codex/hooks.json'));
|
|
56
|
+
const script = await fs.readFile(path.join(root, '.codex/hooks/aiwg-prompt-discovery.cjs'));
|
|
57
|
+
const digest = createHash('sha256').update(JSON.stringify([root, codexHome,
|
|
58
|
+
registration.toString('base64'), script.toString('base64')])).digest('hex');
|
|
59
|
+
// Empty host-local markers record only that advice was shown, never trust.
|
|
60
|
+
const directory = path.join(getUserStateDir(), 'codex-hook-advisories');
|
|
61
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
62
|
+
try {
|
|
63
|
+
await fs.writeFile(path.join(directory, digest), '', { flag: 'wx', mode: 0o600 });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === 'EEXIST')
|
|
67
|
+
return true;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// A missing/unwritable state directory must never silence the diagnostic.
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
async function detectedCodexVersion(projectPath) {
|
|
77
|
+
try {
|
|
78
|
+
// Cleared environment: the probe needs only PATH, never setup inputs or credentials.
|
|
79
|
+
const { stdout } = await execFileAsync('codex', ['--version'], {
|
|
80
|
+
cwd: path.resolve(projectPath), env: workerVersionProbeEnvironment(), timeout: 2000, maxBuffer: 4096, windowsHide: true,
|
|
81
|
+
});
|
|
82
|
+
return /^codex-cli (\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/.exec(stdout.trim())?.[1] ?? 'unknown';
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return 'unknown';
|
|
86
|
+
}
|
|
87
|
+
}
|
|
45
88
|
export async function diagnoseCodexHookTrust(projectPath) {
|
|
46
89
|
const trust = await readCodexHookTrust(projectPath);
|
|
47
90
|
const nextStep = codexHookTrustNextStep(trust);
|
|
48
|
-
|
|
49
|
-
|
|
91
|
+
if (!trust || !nextStep)
|
|
92
|
+
return null;
|
|
93
|
+
if (trust.project === 'trusted' && await codexHookAdvisoryAlreadyShown(projectPath))
|
|
94
|
+
return null;
|
|
95
|
+
const version = await detectedCodexVersion(projectPath);
|
|
96
|
+
return {
|
|
50
97
|
severity: trust.project === 'trusted' ? 'info' : 'warning', code: 'codex-prompt-discovery-trust', path: '.codex/hooks.json',
|
|
51
98
|
message: 'Codex prompt-discovery hook installed but inactive or unverified (untrusted project or unreviewed hook). '
|
|
52
|
-
+ `Project trust: ${trust.project}; hook review: ${trust.hookReview}. ${
|
|
53
|
-
|
|
99
|
+
+ `Project trust: ${trust.project}; hook review: ${trust.hookReview}. Detected Codex version: ${version}. `
|
|
100
|
+
+ `${nextStep} ${CODEX_EXEC_HOOK_TRUST_DETAIL} `
|
|
101
|
+
+ 'For trusted projects, this advisory is shown once per hook digest; changes to the script or registration re-raise it.',
|
|
102
|
+
};
|
|
54
103
|
}
|
|
55
104
|
//# sourceMappingURL=codex-trust.js.map
|