@aiwg/cli 2026.11.4 → 2026.11.5
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/providers/capability-matrix.yaml +75 -5
- package/agentic/code/providers/model-capabilities.v1.json +35 -27
- package/dist/src/artifacts/index-builder.js +4 -2
- package/dist/src/artifacts/query-engine-rules.js +2 -2
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/cli/handlers/script-runner.js +7 -4
- package/dist/src/cli/handlers/steward-format.js +12 -0
- package/dist/src/cli/handlers/use.js +13 -4
- package/dist/src/cli/handlers/utility-doctor.js +4 -0
- package/dist/src/extensions/manifest.js +6 -0
- package/dist/src/extensions/project-local-discovery.js +21 -1
- package/dist/src/extensions/project-local-scaffold.js +19 -7
- package/dist/src/models/factory-models.js +144 -0
- package/dist/src/models/model-capabilities.v1.json +35 -27
- package/dist/src/models/model-discovery.js +7 -3
- package/dist/src/models/worker-installation.d.mts +2 -0
- package/dist/src/models/worker-installation.mjs +11 -2
- package/dist/src/models/worker-invocation-policy.js +25 -1
- package/dist/src/models/wrapper-enforcement.js +1 -1
- package/dist/src/policy/repo-access.js +3 -1
- package/dist/src/providers/capability-matrix.yaml +75 -5
- package/dist/src/providers/deployment-ownership.mjs +8 -1
- package/dist/src/providers/deployment-preservation.mjs +44 -3
- package/dist/src/providers/grok-build-acp.js +13 -5
- package/dist/src/providers/grok-build-dispatch.js +35 -2
- package/dist/src/providers/grok-build-headless.js +2 -1
- package/dist/src/serve/worker-stdin-frame.mjs +1 -1
- package/dist/src/sessions/adapters/grok-build-native-records.js +77 -7
- package/dist/src/sessions/adapters/grok-build-native.js +148 -1
- package/dist/src/sessions/adapters/grok-build.js +36 -14
- package/dist/src/sessions/normalization.js +1 -1
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +4 -0
- package/dist/src/smiths/hook-bridge/factory-trust.js +2 -2
- package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +10 -7
- package/dist/src/smiths/hook-bridge/hermes-trust.js +65 -0
- package/package.json +1 -1
- package/tools/agents/deploy-agents.mjs +4 -2
- package/tools/agents/deploy-options.mjs +2 -0
- package/tools/agents/providers/base-inventory.mjs +3 -1
- package/tools/agents/providers/base-kernel-skills.mjs +11 -5
- package/tools/agents/providers/grok-build.mjs +31 -40
- package/tools/agents/providers/model-wrapper.mjs +2 -5
- package/tools/agents/providers/rule-deployment-commit.mjs +3 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +2 -2
- package/tools/agents/providers/rule-projection.mjs +39 -4
- package/tools/agents/providers/skill-copy-prune.mjs +12 -0
- package/tools/agents/providers/stale-artifact-prune.mjs +24 -10
- package/tools/ralph-external/lib/claude-adapter.mjs +2 -0
- package/tools/ralph-external/lib/factory-adapter.mjs +6 -2
- package/tools/ralph-external/lib/worker-inputs.mjs +20 -1
- package/tools/ralph-external/lib/worker-isolation.mjs +1 -0
- package/tools/ralph-external/lib/worker-termination.mjs +21 -12
- package/tools/ralph-external/session-launcher.mjs +22 -17
|
@@ -4,8 +4,8 @@ import { withModelWrapper } from './model-wrapper.mjs';
|
|
|
4
4
|
* Project skills under `.grok/skills`; user home via $GROK_HOME (default ~/.grok).
|
|
5
5
|
* Distinct from grokbot. No bare `grok` alias.
|
|
6
6
|
*
|
|
7
|
-
* Native
|
|
8
|
-
*
|
|
7
|
+
* Native agents use captured name/description frontmatter and a body prompt.
|
|
8
|
+
* Grok 1.0.77 ignores model frontmatter; worker CLI -m controls model selection.
|
|
9
9
|
* Rules are written to .grok/rules and loaded by Grok alongside AGENTS.md.
|
|
10
10
|
*
|
|
11
11
|
* @issue #2575
|
|
@@ -24,6 +24,10 @@ import {
|
|
|
24
24
|
createAgentsMdFromTemplate,
|
|
25
25
|
deploySkillsWithKernelRouting,
|
|
26
26
|
collectFrameworkArtifacts,
|
|
27
|
+
getAddonAgentFiles,
|
|
28
|
+
filterAgentFiles,
|
|
29
|
+
listMdFiles,
|
|
30
|
+
toKebabCase,
|
|
27
31
|
getAddonSkillDirs,
|
|
28
32
|
injectPlatformInContent,
|
|
29
33
|
isKernelSkill,
|
|
@@ -138,9 +142,7 @@ export function deploySkills(skillDirs, targetDir, opts = {}) {
|
|
|
138
142
|
});
|
|
139
143
|
}
|
|
140
144
|
|
|
141
|
-
const WORKER_ROLES = new Set(['reasoning', 'coding', 'efficiency']);
|
|
142
145
|
const ROLE_FROM_ALIAS = { opus: 'reasoning', sonnet: 'coding', haiku: 'efficiency' };
|
|
143
|
-
const GROK_TOOLS = new Set(['Bash', 'Read', 'Write', 'Edit', 'Grep', 'Glob']);
|
|
144
146
|
|
|
145
147
|
/** Grok agent files accept a small YAML frontmatter subset, not AIWG metadata. */
|
|
146
148
|
export const compileGrokAgent = withModelWrapper('grok-build', translateAgent);
|
|
@@ -151,42 +153,34 @@ function translateAgent(source, content, opts = {}) {
|
|
|
151
153
|
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
|
|
152
154
|
throw new Error(`${source}: invalid agent frontmatter`);
|
|
153
155
|
}
|
|
154
|
-
const name = metadata.name;
|
|
156
|
+
const name = toKebabCase(metadata.name || path.basename(source, '.md'));
|
|
155
157
|
const role = metadata['model-role'] || ROLE_FROM_ALIAS[metadata.model];
|
|
156
|
-
if (!/^aiwg-model-((reasoning|coding|efficiency)-worker|explorer|verifier)$/.test(String(name)) || !WORKER_ROLES.has(role)) {
|
|
157
|
-
throw new Error(`${source}: Grok Build native compilation currently supports only the five AIWG model wrappers; use aiwg show agent for other roles`);
|
|
158
|
-
}
|
|
159
158
|
if (typeof metadata.description !== 'string' || !metadata.description.trim()) {
|
|
160
159
|
throw new Error(`${source}: agent description is required`);
|
|
161
160
|
}
|
|
162
|
-
|
|
163
|
-
if (!Array.isArray(tools) || tools.some(tool => !GROK_TOOLS.has(tool))) {
|
|
164
|
-
throw new Error(`${source}: unsupported Grok Build tool mapping; supported tools: ${[...GROK_TOOLS].join(', ')}`);
|
|
165
|
-
}
|
|
161
|
+
// Portable tier aliases are intent. Exact pins cannot be honored in Grok agents.
|
|
166
162
|
const sourceModel = String(metadata.model || '').trim();
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (configuredModel && (typeof configuredModel !== 'string' || /^(configured\/|inherit$)/.test(configuredModel))) {
|
|
172
|
-
throw new Error(`${source}: unresolved Grok Build ${role} model; configure --${role}-model with a discovered selector`);
|
|
163
|
+
const configuredModel = metadata['model-override'] || opts[`${role}Model`]
|
|
164
|
+
|| opts.modelsConfig?.['grok-build']?.[role]?.model;
|
|
165
|
+
if (configuredModel || (sourceModel && !ROLE_FROM_ALIAS[sourceModel] && sourceModel !== 'inherit')) {
|
|
166
|
+
throw new Error(`${source}: exact model pin is unsupported in Grok Build agents: frontmatter model is ignored. Select a model with -m in the worker CLI invocation instead.`);
|
|
173
167
|
}
|
|
174
168
|
const header = [
|
|
175
169
|
'---',
|
|
176
170
|
`name: ${name}`,
|
|
177
171
|
`description: ${JSON.stringify(metadata.description)}`,
|
|
178
|
-
`tools: ${tools.join(', ')}`,
|
|
179
|
-
...(configuredModel ? [`model: ${JSON.stringify(configuredModel)}`] : []),
|
|
180
172
|
'---',
|
|
181
173
|
];
|
|
182
|
-
const intent =
|
|
183
|
-
? `AIWG model role: ${role}
|
|
184
|
-
|
|
174
|
+
const intent = [
|
|
175
|
+
...(role ? [`AIWG model role: ${role}.`] : []),
|
|
176
|
+
...(metadata['model-tier'] ? [`AIWG model tier intent: ${metadata['model-tier']}.`] : []),
|
|
177
|
+
'Grok Build frontmatter model is ignored; this agent inherits the session model. Role and tier intent do not pin a model. Select the worker model with -m in the CLI invocation.',
|
|
178
|
+
].join(' ');
|
|
185
179
|
return `${header.join('\n')}\n\n${intent}\n\n${match[2].trim()}\n`;
|
|
186
180
|
}
|
|
187
181
|
|
|
188
182
|
export function deployAgents(agentFiles, targetDir, opts = {}) {
|
|
189
|
-
const selected = agentFiles
|
|
183
|
+
const selected = filterAgentFiles(agentFiles, opts);
|
|
190
184
|
const dir = assertSafeNativeDirectory(targetDir, paths.agents);
|
|
191
185
|
for (const source of selected) {
|
|
192
186
|
const dest = path.join(dir, path.basename(source));
|
|
@@ -298,7 +292,7 @@ export function uninstall(target, opts = {}) {
|
|
|
298
292
|
}
|
|
299
293
|
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
300
294
|
for (const [name, record] of Object.entries(manifest.managed ?? {})) {
|
|
301
|
-
if (path.basename(name) !== name ||
|
|
295
|
+
if (path.basename(name) !== name || !name.endsWith('.md')) continue;
|
|
302
296
|
const file = path.join(agentsDir, name);
|
|
303
297
|
const relative = path.relative(root, file);
|
|
304
298
|
if (!fs.existsSync(file) || fs.lstatSync(file).isSymbolicLink() || !fs.lstatSync(file).isFile()) {
|
|
@@ -352,7 +346,7 @@ export async function postDeploy(target, opts = {}) {
|
|
|
352
346
|
console.log(
|
|
353
347
|
`Grok Build (experimental): kernel skills → ${kernelSkillsPath}; ` +
|
|
354
348
|
`standard skills index-driven (opt-in mirror → ${standardSkillsPath} with --copy-all); ` +
|
|
355
|
-
`
|
|
349
|
+
`agents → ${paths.agents}; rules → ${paths.rules}; user home → ${home || '(unresolved GROK_HOME)'}. ` +
|
|
356
350
|
'Distinct from grokbot.',
|
|
357
351
|
);
|
|
358
352
|
}
|
|
@@ -371,23 +365,20 @@ async function deploySelected(opts) {
|
|
|
371
365
|
if (opts.createAgentsMd || (!opts.commandsOnly && !opts.skillsOnly && !opts.rulesOnly)) {
|
|
372
366
|
assertSafeAgentsMd(opts.target);
|
|
373
367
|
}
|
|
374
|
-
const aiwgRoot = resolveAiwgRoot(opts.srcRoot) || opts.srcRoot;
|
|
375
368
|
const skillDirs = [...getAddonSkillDirs(opts.srcRoot)];
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
);
|
|
369
|
+
const artifacts = collectFrameworkArtifacts(opts.srcRoot, mode, {
|
|
370
|
+
includeAgents: true,
|
|
371
|
+
includeCommands: false,
|
|
372
|
+
includeSkills: true,
|
|
373
|
+
includeRules: false,
|
|
374
|
+
});
|
|
375
|
+
skillDirs.push(...artifacts.skills);
|
|
384
376
|
let count = 0;
|
|
385
377
|
if (!opts.commandsOnly && !opts.skillsOnly && !opts.rulesOnly) {
|
|
386
|
-
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
count += deployAgents(workers, opts.target, opts).filter(action => action.type === 'deploy').length;
|
|
378
|
+
// Use the same frozen source root as skills/frameworks, including direct bundles.
|
|
379
|
+
const agents = [...getAddonAgentFiles(opts.srcRoot), ...artifacts.agents,
|
|
380
|
+
...listMdFiles(path.join(opts.srcRoot, 'agents'))];
|
|
381
|
+
count += deployAgents(agents, opts.target, opts).filter(action => action.type === 'deploy').length;
|
|
391
382
|
}
|
|
392
383
|
if (!opts.commandsOnly && !opts.rulesOnly) {
|
|
393
384
|
const result = deploySkills(skillDirs, opts.target, opts);
|
|
@@ -47,8 +47,7 @@ export function withModelWrapper(provider, translate) {
|
|
|
47
47
|
const mapped = translate(source, normalized, opts);
|
|
48
48
|
const notice = `AIWG wrapper tier: ${tier}; catalog role: ${role}. `
|
|
49
49
|
+ `Tier enforcement: ${enforcement}; effort: ${nativeEffort ? `pinned (${nativeEffort})` : 'not enforced per wrapper'}. `
|
|
50
|
-
+ (pin ? `Model selector: ${pin}.` : 'The automatic selector is not a model pin. Model control is inherited or informational; stop unless the conductor confirms the required non-flagship session.')
|
|
51
|
-
+ (provider === 'grok-build' ? ' Native-agent tier enforcement remains gated by #2577; not enforced.' : '');
|
|
50
|
+
+ (pin ? `Model selector: ${pin}.` : 'The automatic selector is not a model pin. Model control is inherited or informational; stop unless the conductor confirms the required non-flagship session.');
|
|
52
51
|
if (provider === 'codex') {
|
|
53
52
|
let output = mapped.replace(/^model = .*$/m, `model = ${JSON.stringify(pin)}`);
|
|
54
53
|
if (!pin) throw new Error(`${source}: Codex wrapper needs a catalog model pin`);
|
|
@@ -62,7 +61,7 @@ export function withModelWrapper(provider, translate) {
|
|
|
62
61
|
if (!target) return `${mapped.trim()}\n\n${notice}\n`;
|
|
63
62
|
const metadata = target.metadata;
|
|
64
63
|
if (pin) metadata[controls.model] = pin;
|
|
65
|
-
else
|
|
64
|
+
else delete metadata.model;
|
|
66
65
|
// Portable input aliases are not provider controls. Emit only the resolved native field.
|
|
67
66
|
for (const key of ['effort', 'model-effort', 'model_reasoning_effort', 'reasoningEffort', 'thinkingLevel']) {
|
|
68
67
|
if (key !== controls.effort || !nativeEffort) delete metadata[key];
|
|
@@ -83,8 +82,6 @@ export function withModelWrapper(provider, translate) {
|
|
|
83
82
|
const nativeHeader = mapped.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/)?.[1] ?? '';
|
|
84
83
|
const nativeTools = nativeHeader.match(/^tools:[^\n]*(?:\n[ \t]+- [^\n]*)*/m)?.[0];
|
|
85
84
|
if (nativeTools) header = header.replace(/^tools:[^\n]*(?:\n[ \t]+- [^\n]*)*/m, () => nativeTools);
|
|
86
|
-
// Keep Grok's quoted native model selector, including operator-supplied IDs.
|
|
87
|
-
if (provider === 'grok-build' && metadata.model) header = header.replace(/^model: .*$/m, `model: ${JSON.stringify(metadata.model)}`);
|
|
88
85
|
return `---\n${header}---\n\n${notice}\n\n${target.body.trim()}\n`;
|
|
89
86
|
};
|
|
90
87
|
}
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
walk,
|
|
23
23
|
} from './rule-delivery-surface.mjs';
|
|
24
24
|
import { prepareRuleDeployment } from './rule-deployment-prepare.mjs';
|
|
25
|
+
import { ruleRemovalReason } from './rule-projection.mjs';
|
|
25
26
|
import {
|
|
26
27
|
captureAnchors,
|
|
27
28
|
capturePreimage,
|
|
@@ -82,6 +83,8 @@ export function commitRuleDeploymentPlan(plan) {
|
|
|
82
83
|
promoteDirectories(to, from, rel => delegated(from, rel));
|
|
83
84
|
const after = new Set(walk(to).map(file => path.relative(to, file)).filter(rel => !delegated(from, rel)));
|
|
84
85
|
for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) {
|
|
86
|
+
const reason = ruleRemovalReason(path.join(from, rel));
|
|
87
|
+
if (reason) console.warn(`Removing ${path.join(from, rel)}${reason}`);
|
|
85
88
|
fs.rmSync(path.join(from, rel), { force: true });
|
|
86
89
|
// A pruned managed skill must disappear as a directory too. Remove
|
|
87
90
|
// only empty parents absent from the staged result; preserve siblings.
|
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
stagedCleanups,
|
|
45
45
|
verifyInputPool,
|
|
46
46
|
} from './rule-deployment-state.mjs';
|
|
47
|
-
import { inlineStartup, projectRules } from './rule-projection.mjs';
|
|
47
|
+
import { ruleRemovalReason, inlineStartup, projectRules } from './rule-projection.mjs';
|
|
48
48
|
const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
|
|
49
49
|
const { preserveDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-preservation.mjs');
|
|
50
50
|
import { retireInlineStartup } from './rule-startup.mjs';
|
|
@@ -427,7 +427,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
|
|
|
427
427
|
const file = path.join(to, rel);
|
|
428
428
|
if (before.get(rel) !== fileDigest(file)) console.log(`[dry-run] Would write ${normalize(file)}`);
|
|
429
429
|
}
|
|
430
|
-
for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) console.log(`[dry-run] Would remove ${path.join(from, rel)}`);
|
|
430
|
+
for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) console.log(`[dry-run] Would remove ${path.join(from, rel)}${ruleRemovalReason(path.join(from, rel))}`);
|
|
431
431
|
}
|
|
432
432
|
for (const name of rootNames) {
|
|
433
433
|
const file = path.join(stage, name);
|
|
@@ -10,9 +10,17 @@ import { writeContextFileSync } from './context-write.mjs';
|
|
|
10
10
|
export { inlineStartup } from './rule-startup.mjs';
|
|
11
11
|
const { parseRuleFrontmatter } = await importImpl(import.meta.url, 'rules/activation.mjs');
|
|
12
12
|
const { renderCoreStartup } = await importImpl(import.meta.url, 'rules/core-startup.mjs');
|
|
13
|
+
const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
|
|
13
14
|
const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
14
15
|
const walk = dir => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
|
|
15
16
|
entry.isDirectory() ? walk(path.join(dir, entry.name)) : [path.join(dir, entry.name)]) : [];
|
|
17
|
+
const deployedRule = file => parseRuleFrontmatter(read(file).replace(/^<!-- aiwg:managed[^\n]*-->\r?\n/, ''));
|
|
18
|
+
export function ruleRemovalReason(file) {
|
|
19
|
+
if (!/[/\\](?:rules|rule|instructions)[/\\].*\.(?:md|mdc)$/.test(file)) return '';
|
|
20
|
+
const parsed = deployedRule(file);
|
|
21
|
+
const level = parsed.data?.enforcement === 'critical' ? 'critical rule' : 'rule';
|
|
22
|
+
return ` (${level} retired because the selected deployment no longer projects its source at this path)`;
|
|
23
|
+
}
|
|
16
24
|
const put = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); };
|
|
17
25
|
export const nativeRuleLoader = name => ['claude', 'cursor', 'grok-build', 'windsurf', 'opencode'].includes(name);
|
|
18
26
|
export const nativePathLoader = name => ['claude', 'cursor', 'windsurf'].includes(name);
|
|
@@ -57,18 +65,44 @@ export function projectRules(opts, provider) {
|
|
|
57
65
|
const extension = provider.name === 'cursor' ? '.mdc' : '.md';
|
|
58
66
|
const managed = content => addManagedMarker(content, opts.deployVersion, opts.deploySource || 'bundled');
|
|
59
67
|
const deployedSources = new Map();
|
|
68
|
+
const owner = deploymentOwner(opts);
|
|
69
|
+
const selectedSource = rule => !opts.bundleOnly || rule.file.startsWith(`${opts.srcRoot}${path.sep}`);
|
|
70
|
+
const manifestPath = path.join(rulesDir, '.aiwg-manifest.json');
|
|
71
|
+
const manifest = fs.existsSync(manifestPath) ? JSON.parse(read(manifestPath)) : { managed: {} };
|
|
72
|
+
const previousManaged = opts.ownershipBefore
|
|
73
|
+
? JSON.parse(opts.ownershipBefore.get(manifestPath)?.toString() || '{}').managed || {} : { ...manifest.managed };
|
|
74
|
+
const owned = file => {
|
|
75
|
+
const name = path.relative(rulesDir, file);
|
|
76
|
+
const record = previousManaged[name];
|
|
77
|
+
const owners = record?.owners || (record?.frameworkSlug ? [record.frameworkSlug] : []);
|
|
78
|
+
const newSource = opts.ownershipBefore?.has(file) ? undefined : manifest.managed?.[name]?.sourcePath;
|
|
79
|
+
return owners.length === 1 && owners[0] === owner || Boolean(newSource?.startsWith(`${opts.srcRoot}${path.sep}`));
|
|
80
|
+
};
|
|
81
|
+
// Retained native contracts also stay reachable through non-native loaders.
|
|
82
|
+
// Older deployments can carry kernel rules whose original source has moved.
|
|
83
|
+
if (opts.bundleOnly) for (const file of walk(rulesDir)) {
|
|
84
|
+
if (!/\.(md|mdc)$/.test(file) || owned(file)) continue;
|
|
85
|
+
const parsed = deployedRule(file);
|
|
86
|
+
if (!parsed.valid || !parsed.rule?.tagged) continue;
|
|
87
|
+
const name = parsed.data.name || path.basename(file, path.extname(file));
|
|
88
|
+
if (['kernel', 'paths'].includes(parsed.rule.activation)
|
|
89
|
+
&& !rules.some(rule => rule.name === name)) rules.push({ ...parsed.rule, name, file, content: read(file), body: parsed.body });
|
|
90
|
+
}
|
|
60
91
|
const writeRule = (rule, content) => {
|
|
92
|
+
if (!selectedSource(rule)) return;
|
|
61
93
|
const name = `${ruleName(rule, provider)}${extension}`;
|
|
94
|
+
if (opts.bundleOnly && opts.ownershipBefore?.has(path.join(rulesDir, name)) && !owned(path.join(rulesDir, name)) && !opts.force) return;
|
|
62
95
|
put(path.join(rulesDir, name), managed(content));
|
|
63
96
|
// Keep the source before reference rewriting, pinning, and native transforms.
|
|
64
97
|
deployedSources.set(name, opts.ruleDelivery.rules.find(original => original.file === rule.file));
|
|
65
98
|
};
|
|
66
99
|
for (const file of walk(rulesDir)) {
|
|
67
|
-
if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file))) fs.rmSync(file);
|
|
100
|
+
if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)) && (!opts.bundleOnly || owned(file))) fs.rmSync(file);
|
|
68
101
|
}
|
|
69
102
|
const cores = [...new Map(tagged.filter(rule => rule.activation === 'core').map(rule => [rule.name, rule])).values()];
|
|
70
103
|
if (['claude', 'cursor'].includes(provider.name)) {
|
|
71
104
|
for (const rule of cores) {
|
|
105
|
+
if (!selectedSource(rule)) continue;
|
|
72
106
|
const dest = path.join(rulesDir, `core-${path.basename(rule.file, '.md')}${extension}`);
|
|
73
107
|
if (fs.existsSync(dest) && !/aiwg:managed/.test(read(dest)) && !opts.force) {
|
|
74
108
|
console.warn(`Unmanaged core rule left in place: ${dest}. Re-run with --force to replace it.`);
|
|
@@ -110,9 +144,7 @@ export function projectRules(opts, provider) {
|
|
|
110
144
|
const startups = projectStartup(opts, provider, coreSection, indexFile);
|
|
111
145
|
registerOpenCode(opts, provider, rulesDir);
|
|
112
146
|
fs.rmSync(path.join(rulesDir, '.aiwg-rules-budget.json'), { force: true });
|
|
113
|
-
|
|
114
|
-
const manifest = fs.existsSync(manifestPath) ? JSON.parse(read(manifestPath)) : { managed: {} };
|
|
115
|
-
manifest.ruleSources = rules.map(rule => rule.file);
|
|
147
|
+
manifest.ruleSources = opts.ruleDelivery.rules.map(rule => rule.file);
|
|
116
148
|
const logical = opts.logicalOutputPath || (file => file);
|
|
117
149
|
const relative = file => path.relative(logical(opts.target), logical(file)).replaceAll('\\', '/');
|
|
118
150
|
manifest.delivery = { projectFromRules: path.relative(logical(rulesDir), logical(opts.target)),
|
|
@@ -122,9 +154,12 @@ export function projectRules(opts, provider) {
|
|
|
122
154
|
for (const file of walk(rulesDir).filter(file => /\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)))) {
|
|
123
155
|
const name = path.relative(rulesDir, file);
|
|
124
156
|
const source = deployedSources.get(name);
|
|
157
|
+
if (opts.bundleOnly && !source && !/^(?:RULES-INDEX|RULES-ONDEMAND)\./.test(name)) continue;
|
|
125
158
|
manifest.managed[name] = { ...manifest.managed[name], hash: `sha256:${contentHash(read(file))}`,
|
|
126
159
|
...(source ? { sourceHash: `sha256:${contentHash(source.content)}` } : {}) };
|
|
127
160
|
}
|
|
128
161
|
for (const name of Object.keys(manifest.managed)) if (!fs.existsSync(path.join(rulesDir, name))) delete manifest.managed[name];
|
|
162
|
+
if (opts.bundleOnly) opts.retiredRuleFiles = new Set([...(opts.ownershipBefore?.keys() || [])].filter(file =>
|
|
163
|
+
file.startsWith(`${rulesDir}${path.sep}`) && owned(file) && !fs.existsSync(file)));
|
|
129
164
|
put(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
130
165
|
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
|
+
import { importImpl } from '../../_resolve-impl.mjs';
|
|
6
|
+
const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
|
|
5
7
|
export function removeSkillCopy(dir, opts = {}) {
|
|
6
8
|
const copyMode = opts.copyMode ?? opts.copyStandardSkills;
|
|
7
9
|
if (copyMode && !opts.tierMove) return false;
|
|
@@ -17,6 +19,7 @@ export function removeSkillCopy(dir, opts = {}) {
|
|
|
17
19
|
let receipt;
|
|
18
20
|
try { receipt = JSON.parse(fs.readFileSync(path.join(dir, '.aiwg-manifest.json'), 'utf8')); }
|
|
19
21
|
catch (error) {
|
|
22
|
+
if (opts.bundleOnly) return false;
|
|
20
23
|
// Only a missing receipt may use legacy ownership. An invalid receipt must
|
|
21
24
|
// not turn an edited copy into a marker-only deletion candidate.
|
|
22
25
|
if (error.code !== 'ENOENT') return keep('unverifiable ownership');
|
|
@@ -24,6 +27,15 @@ export function removeSkillCopy(dir, opts = {}) {
|
|
|
24
27
|
if (!opts.dryRun) fs.rmSync(dir, { recursive: true, force: true });
|
|
25
28
|
return true;
|
|
26
29
|
}
|
|
30
|
+
if (opts.bundleOnly) {
|
|
31
|
+
const record = receipt?.managed?.['SKILL.md'];
|
|
32
|
+
const owners = record?.owners || (record?.frameworkSlug ? [record.frameworkSlug] : []);
|
|
33
|
+
const logical = opts.logicalInputPath || (file => file);
|
|
34
|
+
const selectedRoot = path.resolve(logical(opts.srcRoot));
|
|
35
|
+
const source = receipt?.skillSource && path.resolve(logical(receipt.skillSource));
|
|
36
|
+
const ownSource = source && source.startsWith(`${selectedRoot}${path.sep}`);
|
|
37
|
+
if (owners.length ? owners.some(owner => owner !== deploymentOwner(opts)) : !ownSource) return false;
|
|
38
|
+
}
|
|
27
39
|
if (!receipt?.managed?.['SKILL.md']?.hash) return keep('unverifiable ownership');
|
|
28
40
|
const walk = root => fs.readdirSync(root, { withFileTypes: true }).flatMap(entry => {
|
|
29
41
|
const file = path.join(root, entry.name);
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/** Preserve projector-owned rules while pruning stale legacy flat artifacts. */
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { computeArtifactInventory, computeAllSkillNames, pruneStaleAiwgFiles, resolveAiwgRoot } from './base.mjs';
|
|
4
|
+
import { artifactStem, computeArtifactInventory, computeAllSkillNames, listMdFiles, listSkillDirs, pruneStaleAiwgFiles, resolveAiwgRoot } from './base.mjs';
|
|
5
|
+
import { importImpl } from '../../_resolve-impl.mjs';
|
|
6
|
+
const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* After a deploy, prune AIWG-managed flat artifacts (agents/commands/rules)
|
|
@@ -9,9 +11,9 @@ import { computeArtifactInventory, computeAllSkillNames, pruneStaleAiwgFiles, re
|
|
|
9
11
|
*
|
|
10
12
|
* Safety boundaries:
|
|
11
13
|
* - Runs ONLY for AIWG framework/addon deploys (default source = AIWG root,
|
|
12
|
-
* or `--source` under `<aiwgRoot>/agentic/code`).
|
|
13
|
-
*
|
|
14
|
-
*
|
|
14
|
+
* or `--source` under `<aiwgRoot>/agentic/code`). A named bundle pass
|
|
15
|
+
* instead compares only its own recorded outputs with its source tree,
|
|
16
|
+
* including project-local sources.
|
|
15
17
|
* - `pruneStaleAiwgFiles` itself only removes files whose AIWG
|
|
16
18
|
* receipt hash matches their bytes AND whose recorded owners no longer
|
|
17
19
|
* ship the stem. Without bundle identity, it uses the global source set.
|
|
@@ -49,22 +51,24 @@ export function bulkInstallOwnsFlatArtifacts(target) {
|
|
|
49
51
|
|
|
50
52
|
export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explicitSource) {
|
|
51
53
|
if (opts.copyMode ?? opts.copyStandardSkills) return;
|
|
52
|
-
if (opts.skillsOnly && !opts.kernelOnly) return; // skills run their own prune in the provider
|
|
54
|
+
if (opts.skillsOnly && (!opts.kernelOnly || provider.name === 'grok-build')) return; // skills run their own prune in the provider
|
|
53
55
|
|
|
54
56
|
const aiwgRoot = resolveAiwgRoot(srcRoot);
|
|
55
|
-
if (!aiwgRoot) return; //
|
|
57
|
+
if (!aiwgRoot && !opts.bundleOnly) return; // standalone deploy without an ownership scope
|
|
56
58
|
|
|
57
59
|
// Gate: only framework/addon deploys are eligible. A default deploy (no
|
|
58
60
|
// --source) sources from the AIWG root. An explicit --source is eligible
|
|
59
61
|
// only when it lives under <aiwgRoot>/agentic/code (bundled fw/addon).
|
|
60
|
-
if (explicitSource) {
|
|
62
|
+
if (explicitSource && !opts.bundleOnly) {
|
|
61
63
|
const codeRoot = path.join(aiwgRoot, 'agentic', 'code');
|
|
62
64
|
const rel = path.relative(codeRoot, path.resolve(explicitSource));
|
|
63
65
|
const underCode = !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
64
66
|
if (!underCode) return; // project-local bundle / external source → skip
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
|
|
69
|
+
// Grok bulk mode writes native agents; reconcile against the corpus below,
|
|
70
|
+
// rather than treating its newly deployed agents as obsolete bulk output.
|
|
71
|
+
if (opts.kernelOnly && provider.name !== 'grok-build') {
|
|
68
72
|
// Kernel-only delivers skills and rules. The empty desired set below
|
|
69
73
|
// applies only to bulk agents/commands left by
|
|
70
74
|
// the pre-#152 bulk default, when the bulk install is the only thing this
|
|
@@ -103,7 +107,10 @@ export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explici
|
|
|
103
107
|
if (!relPath) continue; // type not file-deployed by provider
|
|
104
108
|
if (relPath.endsWith('.md')) continue; // aggregate file (e.g. AGENTS.md)
|
|
105
109
|
|
|
106
|
-
const
|
|
110
|
+
const onlyOwner = opts.bundleOnly ? deploymentOwner(opts) : undefined;
|
|
111
|
+
const selectedStems = onlyOwner && new Set(listMdFiles(path.join(srcRoot, type)).map(file => artifactStem(path.basename(file))));
|
|
112
|
+
const inventory = onlyOwner ? { stems: selectedStems, ownerStems: new Map([[onlyOwner, selectedStems]]) }
|
|
113
|
+
: computeArtifactInventory(srcRoot, type);
|
|
107
114
|
if (!inventory) continue; // no global desired set → skip
|
|
108
115
|
|
|
109
116
|
const destDir = path.isAbsolute(relPath) ? relPath : path.join(target, relPath);
|
|
@@ -113,14 +120,21 @@ export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explici
|
|
|
113
120
|
const receipt = path.join(destDir, '.aiwg-manifest.json');
|
|
114
121
|
if (fs.existsSync(receipt) && JSON.parse(fs.readFileSync(receipt, 'utf8')).delivery) continue;
|
|
115
122
|
}
|
|
123
|
+
let skillCommandStems = null;
|
|
124
|
+
if (type === 'commands') {
|
|
125
|
+
skillCommandStems = onlyOwner
|
|
126
|
+
? new Set(listSkillDirs(path.join(srcRoot, 'skills')).map(file => path.basename(file)))
|
|
127
|
+
: computeAllSkillNames(srcRoot);
|
|
128
|
+
}
|
|
116
129
|
const removed = pruneStaleAiwgFiles(destDir, inventory.stems, {
|
|
117
130
|
ownerStems: inventory.ownerStems,
|
|
131
|
+
onlyOwner,
|
|
118
132
|
dryRun: opts.dryRun,
|
|
119
133
|
verbose: opts.verbose,
|
|
120
134
|
// Retire wrappers whose source skill no longer ships (#2511). Only the
|
|
121
135
|
// command directory holds them; the kernel-only branch returns earlier,
|
|
122
136
|
// so a bulk install still cannot touch wrappers it did not write.
|
|
123
|
-
skillCommandStems
|
|
137
|
+
skillCommandStems,
|
|
124
138
|
});
|
|
125
139
|
if (removed.length > 0 && !opts.quiet) {
|
|
126
140
|
console.log(` Pruned: ${removed.length} stale AIWG ${type} file${removed.length === 1 ? '' : 's'}`);
|
|
@@ -341,6 +341,8 @@ export class ClaudeAdapter extends ProviderAdapter {
|
|
|
341
341
|
* inherited from ProviderAdapter.
|
|
342
342
|
*/
|
|
343
343
|
export class ClaudeDirectAdapter extends ClaudeAdapter {
|
|
344
|
+
getName() { return 'claude-direct'; }
|
|
345
|
+
|
|
344
346
|
async parseWorkerFinal(output, options = {}) {
|
|
345
347
|
// MCP envelopes retain the shared strict parser. Every other input must be
|
|
346
348
|
// Claude's own stream-json transcript with a validated terminal result: the
|
|
@@ -202,8 +202,12 @@ export class FactoryAdapter extends ProviderAdapter {
|
|
|
202
202
|
if (FACTORY_RESERVED_MODEL_VALUES.includes(model.toLowerCase())) {
|
|
203
203
|
throw new Error(`Factory worker requires an explicit observed model, not the CLI's own auto-selection '${model}'`);
|
|
204
204
|
}
|
|
205
|
+
if (model.startsWith('custom:') && (model.trim() !== model || !/^custom:[^\s\x00-\x1f\x7f]+-\d+$/.test(model))) {
|
|
206
|
+
throw new Error('Factory custom model selector requires a safe normalized name and numeric suffix');
|
|
207
|
+
}
|
|
205
208
|
const effort = invocation?.selected?.effort?.value ?? null;
|
|
206
|
-
|
|
209
|
+
const customNoEffort = model.startsWith('custom:') && invocation?.selected?.effort?.support === 'not-applicable' && effort === null;
|
|
210
|
+
if (!customNoEffort && (effort === null || !FACTORY_DIRECT_EFFORT_VALUES.includes(effort))) {
|
|
207
211
|
throw new Error('Factory worker requires an explicit qualified reasoning effort (never a CLI default)');
|
|
208
212
|
}
|
|
209
213
|
const sandbox = permissions?.sandbox ?? 'workspace-write';
|
|
@@ -225,7 +229,7 @@ export class FactoryAdapter extends ProviderAdapter {
|
|
|
225
229
|
const auto = FACTORY_SANDBOX_TO_AUTO[sandbox];
|
|
226
230
|
const args = ['exec'];
|
|
227
231
|
if (auto) args.push('--auto', auto);
|
|
228
|
-
args.push('-m', model, '-r', effort, '--cwd', cwd, '--output-format', 'stream-json');
|
|
232
|
+
args.push('-m', model, ...(customNoEffort ? [] : ['-r', effort]), '--cwd', cwd, '--output-format', 'stream-json');
|
|
229
233
|
return args;
|
|
230
234
|
}
|
|
231
235
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Read bounded worker inputs through pinned, no-follow directory handles.
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
3
|
import { open } from 'node:fs/promises';
|
|
4
|
-
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { basename, dirname, isAbsolute } from 'node:path';
|
|
5
5
|
|
|
6
6
|
// Linux directory handles pin each ancestor. O_NOFOLLOW on a pathname alone
|
|
7
7
|
// cannot protect an ancestor that the worker replaces after inspection.
|
|
@@ -19,6 +19,25 @@ export async function withWorkerPath(filename, operation) {
|
|
|
19
19
|
} finally { await directory.close(); }
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
// Reuse one pinned directory for a batch of direct-child operations. Every
|
|
23
|
+
// ancestor and the directory itself are still opened with O_NOFOLLOW;
|
|
24
|
+
// callers retain the leaf operation's own no-follow/exclusive-create checks.
|
|
25
|
+
export async function withWorkerDirectory(directory, operation) {
|
|
26
|
+
return withWorkerPath(directory, async anchored => {
|
|
27
|
+
const handle = await open(anchored, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
28
|
+
try {
|
|
29
|
+
return await operation(async (filename, action) => {
|
|
30
|
+
if (filename.includes('\0') || filename.split('/').includes('..')
|
|
31
|
+
|| (filename !== directory && dirname(filename) !== directory)) {
|
|
32
|
+
throw new Error('Invalid worker path outside pinned directory');
|
|
33
|
+
}
|
|
34
|
+
const leaf = filename === directory ? '.' : basename(filename);
|
|
35
|
+
return action(`/proc/self/fd/${handle.fd}/${leaf}`);
|
|
36
|
+
});
|
|
37
|
+
} finally { await handle.close(); }
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
22
41
|
// #2915 review 4 (finding 4): `privateOutput: true` REPAIRS a loose mode
|
|
23
42
|
// (chmod 0600) rather than rejecting it — correct for the worker's own
|
|
24
43
|
// final-output file, which the launcher itself created and is free to
|
|
@@ -249,6 +249,7 @@ export function launchIsolatedWorker({
|
|
|
249
249
|
const outcome = {
|
|
250
250
|
launched: Number.isInteger(child.pid) && child.pid > 0,
|
|
251
251
|
mode: detected.mode, child, pid: child.pid,
|
|
252
|
+
ownedGroup: ownedGroup === true,
|
|
252
253
|
...(attached ? { transportSupervisor: true } : {}),
|
|
253
254
|
diagnostic: nativeSandbox ? 'Native CLI sandbox boundary; no cgroup resource confinement' : `launched without resource confinement: ${detected.reason}`,
|
|
254
255
|
gate: resolvedGate,
|
|
@@ -8,7 +8,7 @@ const TERMINATION_BUDGET_MS = 2000;
|
|
|
8
8
|
const TERMINATION_ATTEMPT_MS = 100;
|
|
9
9
|
const TERMINATION_MAX_ATTEMPTS = 21;
|
|
10
10
|
|
|
11
|
-
export function observeWorkerTermination({ mode, native, workerExited, identity,
|
|
11
|
+
export function observeWorkerTermination({ mode, native, workerExited, identity, detachedPid,
|
|
12
12
|
supervisor = sampleWorkerIdentity(process.pid), kill = process.kill, invocationId,
|
|
13
13
|
scan = scanWorkerInvocationProcesses, groupStates = sampleGroupStates, deadline, now = () => performance.now() } = {}) {
|
|
14
14
|
if (mode === 'systemd-unit') {
|
|
@@ -18,20 +18,33 @@ export function observeWorkerTermination({ mode, native, workerExited, identity,
|
|
|
18
18
|
? 'unit inactive evidence' : native?.cgroupEmpty !== true ? 'empty unit cgroup (TasksCurrent=0)' : null };
|
|
19
19
|
}
|
|
20
20
|
if (!workerExited) return { confirmed: false, missing: 'launcher-observed worker exit' };
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
// A successful detached spawn establishes pgid=pid even if /proc vanished
|
|
22
|
+
// before capture. This is read-only containment evidence, never a recovered
|
|
23
|
+
// birth identity or signal authority. The launcher's birth is a conservative
|
|
24
|
+
// lower bound for descendants; without worker birth, unreadable processes
|
|
25
|
+
// retain the scan's stricter fail-closed handling (no ancestry exclusions).
|
|
26
|
+
const group = identity ?? (Number.isSafeInteger(detachedPid) && supervisor?.pid === process.pid
|
|
27
|
+
&& /^\d+$/.test(supervisor.startTicks ?? '') ? {
|
|
28
|
+
pid: detachedPid, pgid: detachedPid, uid: supervisor.uid,
|
|
29
|
+
host: supervisor.host, bootId: supervisor.bootId, startTicks: supervisor.startTicks,
|
|
30
|
+
} : null);
|
|
31
|
+
if (!group || group.pid !== group.pgid || group.uid !== process.getuid?.()
|
|
32
|
+
|| !supervisor || group.host !== supervisor.host || group.bootId !== supervisor.bootId
|
|
33
|
+
|| !isSafeWorkerGroupTarget(group.pgid, supervisor)) {
|
|
24
34
|
return { confirmed: false, missing: 'launcher-owned process group identity on this host and boot' };
|
|
25
35
|
}
|
|
36
|
+
const scanOptions = { invocationId, startTicks: group.startTicks, uid: group.uid, now,
|
|
37
|
+
deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
|
|
38
|
+
...(identity ? { workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId } : {}) };
|
|
26
39
|
let groupEmpty = false;
|
|
27
40
|
try {
|
|
28
|
-
kill(-
|
|
41
|
+
kill(-group.pgid, 0);
|
|
29
42
|
// Signal 0 also reaches zombies. A reaper that never waits (a container's
|
|
30
43
|
// PID 1) can leave killed members as zombies indefinitely; a group whose
|
|
31
44
|
// remaining members are all zombies has no live process (#3853).
|
|
32
45
|
// Absence from /proc is never proof; only observed zombies explaining
|
|
33
46
|
// signal 0, with no live or unreadable member, count as an empty group.
|
|
34
|
-
const states = groupStates(
|
|
47
|
+
const states = groupStates(group.pgid);
|
|
35
48
|
groupEmpty = !!states && states.zombies > 0 && states.live === 0 && states.unreadable === 0;
|
|
36
49
|
}
|
|
37
50
|
catch (error) {
|
|
@@ -42,16 +55,12 @@ export function observeWorkerTermination({ mode, native, workerExited, identity,
|
|
|
42
55
|
if (error.code === 'ESRCH') {
|
|
43
56
|
// A standalone observation gets one scan, at most 2 s. An explicit
|
|
44
57
|
// deadline leaves the shared budget and retries to its caller.
|
|
45
|
-
return scan(
|
|
46
|
-
deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
|
|
47
|
-
workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId });
|
|
58
|
+
return scan(scanOptions);
|
|
48
59
|
}
|
|
49
60
|
return { confirmed: false, missing: `empty owned process group (signal-0 returned ${error.code ?? 'unknown'})` };
|
|
50
61
|
}
|
|
51
62
|
if (groupEmpty) {
|
|
52
|
-
return scan(
|
|
53
|
-
deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
|
|
54
|
-
workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId });
|
|
63
|
+
return scan(scanOptions);
|
|
55
64
|
}
|
|
56
65
|
return { confirmed: false, missing: 'empty owned process group (signal-0 still finds members)', retryable: true };
|
|
57
66
|
}
|