@aiwg/cli 2026.10.12 → 2026.10.14

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 (56) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +44 -1
  2. package/dist/src/cli/handlers/use-bundle-counts.js +32 -6
  3. package/dist/src/cli/handlers/use-skill-assets.js +207 -0
  4. package/dist/src/cli/handlers/use.js +30 -193
  5. package/dist/src/config/authorization-cli.js +11 -3
  6. package/dist/src/decision/context-pruning-common.js +41 -0
  7. package/dist/src/decision/context-pruning-evaluation.js +366 -0
  8. package/dist/src/decision/context-pruning-pilot.js +431 -0
  9. package/dist/src/decision/context-pruning-types.js +19 -0
  10. package/dist/src/decision/context-pruning.js +5 -847
  11. package/dist/src/decision/ensemble/contract.js +4 -24
  12. package/dist/src/decision/qualification/release.js +5 -62
  13. package/dist/src/extensions/manifest.js +8 -1
  14. package/dist/src/extensions/project-local-doctor.js +78 -2
  15. package/dist/src/extensions/validation.js +10 -11
  16. package/dist/src/gates/evaluate.js +3 -13
  17. package/dist/src/gates/upstream-ceiling.js +111 -0
  18. package/dist/src/models/provider-models.js +5 -8
  19. package/dist/src/models/wrapper-definitions.js +14 -0
  20. package/dist/src/models/wrapper-deployment.js +48 -25
  21. package/dist/src/models/wrapper-enforcement.js +72 -0
  22. package/dist/src/policy/hitl-check.js +80 -0
  23. package/dist/src/rules/activation.d.mts +2 -0
  24. package/dist/src/rules/activation.mjs +23 -0
  25. package/dist/src/skills/adapters/local.js +32 -9
  26. package/dist/src/skills/agent-skills.js +2 -0
  27. package/dist/src/skills/cli-display.js +33 -0
  28. package/dist/src/skills/cli.js +2 -26
  29. package/dist/src/skills/collision-discovery.js +84 -0
  30. package/dist/src/skills/deployer.js +20 -75
  31. package/dist/src/skills/deployment-ownership.js +74 -0
  32. package/dist/src/skills/doctor.js +2 -2
  33. package/dist/src/skills/importer.js +4 -26
  34. package/dist/src/skills/registry.js +22 -7
  35. package/dist/src/smiths/context-pipeline/parallelism-section.js +7 -3
  36. package/package.json +3 -1
  37. package/tools/agents/providers/antigravity.mjs +3 -5
  38. package/tools/agents/providers/base.mjs +3 -3
  39. package/tools/agents/providers/claude.mjs +3 -5
  40. package/tools/agents/providers/codex.mjs +3 -5
  41. package/tools/agents/providers/copilot.mjs +3 -5
  42. package/tools/agents/providers/cursor.mjs +3 -5
  43. package/tools/agents/providers/factory.mjs +3 -5
  44. package/tools/agents/providers/grok-build.mjs +9 -7
  45. package/tools/agents/providers/model-wrapper.mjs +86 -0
  46. package/tools/agents/providers/omp.mjs +3 -1
  47. package/tools/agents/providers/openclaw.mjs +3 -5
  48. package/tools/agents/providers/opencode.mjs +3 -5
  49. package/tools/agents/providers/provider-paths-staging.mjs +9 -0
  50. package/tools/agents/providers/rule-delivery.mjs +4 -4
  51. package/tools/agents/providers/warp.mjs +3 -5
  52. package/tools/agents/providers/windsurf.mjs +3 -5
  53. package/tools/plugin/package-plugins.mjs +2 -2
  54. package/tools/skills/codex-skill-transform.mjs +232 -0
  55. package/tools/skills/deploy-skills-codex.mjs +8 -249
  56. package/tools/warp/warp-content.mjs +548 -0
@@ -1,5 +1,39 @@
1
1
  /** AIWG's reviewed Pi bridge. Loaded only after Pi project trust is granted. */
2
2
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
+ import { execFile } from 'node:child_process';
4
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { basename, join } from 'node:path';
7
+ import { promisify } from 'node:util';
8
+
9
+ const execute = promisify(execFile);
10
+ type Action = { category: string; repo: string; environment: string; resources: string[]; reversible: boolean; impact: 'low' | 'medium' | 'high' };
11
+ type Check = { decision: string; receipt?: { file: string; effectId: string } };
12
+
13
+ /** Deployed bridges call the installed CLI, never import checkout-only source paths. */
14
+ export async function checkAiwgAuthorization(projectDir: string, action: Action): Promise<Check> {
15
+ const temporary = await mkdtemp(join(tmpdir(), 'aiwg-pi-authorization-'));
16
+ try {
17
+ const file = join(temporary, 'action.json');
18
+ await writeFile(file, JSON.stringify(action), { mode: 0o600 });
19
+ const result = await execute('aiwg', ['config', 'authorization', 'check', '--action-file', file, '--target', projectDir],
20
+ { cwd: projectDir, timeout: 15_000, maxBuffer: 64 * 1024 });
21
+ return JSON.parse(result.stdout) as Check;
22
+ } catch { return { decision: 'escalate' }; }
23
+ finally { await rm(temporary, { recursive: true, force: true }); }
24
+ }
25
+
26
+ /** Host-only descriptors and callbacks; tool/issue/model payloads cannot supply these authority fields. */
27
+ export async function evaluateAiwgPiAction(projectDir: string, action: Action, hasUI: boolean,
28
+ confirm?: () => Promise<boolean>, check = checkAiwgAuthorization,
29
+ ): Promise<{ block: true; reason: string } | undefined> {
30
+ let result: Check;
31
+ try { result = await check(projectDir, action); } catch { result = { decision: 'escalate' }; }
32
+ if (result.decision === 'auto-authorized' && result.receipt?.file && result.receipt.effectId) return undefined;
33
+ if (result.decision === 'deny') return { block: true, reason: 'Denied by AIWG operator policy.' };
34
+ if (!hasUI) return { block: true, reason: 'AIWG policy blocked a destructive or package-mutating command in headless mode.' };
35
+ return await confirm?.() ? undefined : { block: true, reason: 'Denied by AIWG operator policy.' };
36
+ }
3
37
 
4
38
  const destructive = /(?:^|[;&|]\s*)(?:sudo\s+)?(?:rm\s+-\S*r\S*\s+|git\s+(?:reset\s+--hard|clean\s+-)|chmod\s+777|chown\s+-R)/i;
5
39
  const packageMutation = /(?:^|[;&|]\s*)(?:npm|pnpm|yarn|bun|pipx?|uv|cargo)\s+(?:install|add|update|upgrade)\b/i;
@@ -8,8 +42,17 @@ export async function evaluateAiwgPiCommand(
8
42
  command: string,
9
43
  hasUI: boolean,
10
44
  confirm?: () => Promise<boolean>,
45
+ projectDir?: string,
11
46
  ): Promise<{ block: true; reason: string } | undefined> {
12
47
  if (!destructive.test(command) && !packageMutation.test(command)) return undefined;
48
+ if (projectDir) {
49
+ // Shell commands have unbounded resources and possible global effects. Never
50
+ // infer a reversible file edit from argv or accept authority in tool input.
51
+ return evaluateAiwgPiAction(projectDir, {
52
+ category: destructive.test(command) ? 'repo.delete' : 'dependency.install',
53
+ repo: basename(projectDir), environment: 'local', resources: [], reversible: false, impact: 'high',
54
+ }, hasUI, confirm);
55
+ }
13
56
  if (!hasUI) return { block: true, reason: 'AIWG policy blocked a destructive or package-mutating command in headless mode.' };
14
57
  return await confirm?.() ? undefined : { block: true, reason: 'Denied by AIWG operator policy.' };
15
58
  }
@@ -21,6 +64,6 @@ export default function aiwgBridge(pi: ExtensionAPI): void {
21
64
  return evaluateAiwgPiCommand(command, context.hasUI, async () => {
22
65
  const choice = await context.ui.select('AIWG policy requires explicit approval for this command.', ['Deny', 'Allow once']);
23
66
  return choice === 'Allow once';
24
- });
67
+ }, context.cwd);
25
68
  });
26
69
  }
@@ -1,16 +1,36 @@
1
1
  // Count bundle artifacts from native files and activation-selected rule receipts.
2
2
  import { promises as fs } from 'node:fs';
3
3
  import path from 'node:path';
4
- export async function countDeployedBundleRules(bundlePath, target, deployPath) {
5
- if (!deployPath)
4
+ import { createHash } from 'node:crypto';
5
+ import { parseRuleFrontmatter } from '../../rules/activation.mjs';
6
+ export async function countDeployedBundleRules(bundlePath, target, deployPath, provider) {
7
+ if (!deployPath && !provider)
6
8
  return 0;
7
- const destination = path.resolve(target, deployPath);
9
+ // The shared rule projector uses this conventional directory even when a
10
+ // provider has no native rule loader (for example Pi).
11
+ const destination = path.resolve(target, deployPath || `.${provider}/rules`);
8
12
  let selected = [];
13
+ let managed = {};
9
14
  try {
10
15
  const receipt = JSON.parse(await fs.readFile(path.join(destination, '.aiwg-manifest.json'), 'utf8'));
11
16
  selected = Array.isArray(receipt.ruleSources) ? receipt.ruleSources : [];
17
+ managed = receipt.managed ?? {};
12
18
  }
13
19
  catch { /* Legacy deployments have only native files. */ }
20
+ const indexed = new Set();
21
+ for (const extension of ['.md', '.mdc']) {
22
+ const name = `RULES-INDEX${extension}`;
23
+ try {
24
+ const content = await fs.readFile(path.join(destination, name), 'utf8');
25
+ const hash = `sha256:${createHash('sha256').update(content).digest('hex')}`;
26
+ if (managed[name]?.hash !== hash)
27
+ continue;
28
+ // Rule names may contain spaces (for example "Diversity Awareness").
29
+ for (const match of content.matchAll(/`aiwg show rule ([^`]+?) --body`/g))
30
+ indexed.add(match[1]);
31
+ }
32
+ catch { /* An index receipt alone does not deliver a rule. */ }
33
+ }
14
34
  let sources;
15
35
  try {
16
36
  sources = (await fs.readdir(path.join(bundlePath, 'rules'))).filter(name => name.endsWith('.md'));
@@ -20,9 +40,15 @@ export async function countDeployedBundleRules(bundlePath, target, deployPath) {
20
40
  }
21
41
  let count = 0;
22
42
  for (const name of sources) {
23
- if (selected.includes(path.resolve(bundlePath, 'rules', name))) {
24
- count++;
25
- continue;
43
+ const source = path.resolve(bundlePath, 'rules', name);
44
+ if (selected.includes(source)) {
45
+ const { data } = parseRuleFrontmatter(await fs.readFile(source, 'utf8'));
46
+ const metadata = data;
47
+ // Other activations can be delivered inside context or bound artifacts.
48
+ if (metadata.activation !== 'summary' || indexed.has(metadata.name || path.basename(name, '.md'))) {
49
+ count++;
50
+ continue;
51
+ }
26
52
  }
27
53
  for (const extension of ['.md', '.mdc']) {
28
54
  try {
@@ -0,0 +1,207 @@
1
+ // Reconcile skill-relative and bundle-root support assets after provider deployment.
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { canDeploySkill, sameSkillOwner, extractFrameworkSlug } from '../../providers/skill-ownership.mjs';
7
+ import { resolveOmpPaths } from '../../providers/omp-paths.mjs';
8
+ import { deployedSkillRoots } from '../../providers/deployed-skill-roots.js';
9
+ import { getFrameworkRoot } from '../../channel/manager.mjs';
10
+ async function fileExists(file) {
11
+ try {
12
+ await fs.access(file);
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ const SKILL_SUPPORT_REFERENCE = /(?:^|[\s`('"\[])((?:templates|references|scripts|assets)\/[A-Za-z0-9._@/+\-]*[A-Za-z0-9_@/+\-])(?=$|[.?!\s`)'"\],:;])/gm;
20
+ /** Copy one support file, preserving its executable bit. */
21
+ async function copySkillSupportFile(source, destination, skillDir) {
22
+ await fs.mkdir(path.dirname(destination), { recursive: true });
23
+ await fs.copyFile(source, destination);
24
+ await fs.chmod(destination, (await fs.stat(source)).mode & 0o777);
25
+ // Extend the shared copier's receipt for bundle-root assets too. Adapters
26
+ // without that receipt keep their own ownership and cleanup contract.
27
+ if (!skillDir)
28
+ return;
29
+ const manifestPath = path.join(skillDir, '.aiwg-manifest.json');
30
+ let manifest;
31
+ try {
32
+ manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
33
+ }
34
+ catch {
35
+ return;
36
+ }
37
+ if (!manifest.skillSource || !manifest.managed?.['SKILL.md'])
38
+ return;
39
+ manifest.managed[path.relative(skillDir, destination)] = {
40
+ ...manifest.managed['SKILL.md'],
41
+ hash: `sha256:${createHash('sha256').update(await fs.readFile(destination)).digest('hex')}`,
42
+ };
43
+ await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
44
+ }
45
+ /**
46
+ * Materialize a directory-valued support-asset reference (#2503).
47
+ *
48
+ * Applies the same rules the single-file path applies, per entry: symlinks are
49
+ * refused rather than followed (a link inside a bundle can point anywhere), and
50
+ * file modes are preserved so script packs stay executable. Empty directories
51
+ * are still created — a reference to an empty pack is odd but not an error.
52
+ */
53
+ async function copySkillSupportTree(source, destination, sourceSkillMd, reference, deployFile, skillDir) {
54
+ await fs.mkdir(destination, { recursive: true });
55
+ const label = reference.replace(/\/+$/, '');
56
+ const entries = await fs.readdir(source, { withFileTypes: true });
57
+ for (const entry of entries) {
58
+ const from = path.join(source, entry.name);
59
+ const to = path.join(destination, entry.name);
60
+ if (entry.isSymbolicLink()) {
61
+ throw new Error(`unsafe skill support asset '${label}/${entry.name}' referenced by ${sourceSkillMd}: symbolic links are not deployed`);
62
+ }
63
+ if (entry.isDirectory()) {
64
+ await copySkillSupportTree(from, to, sourceSkillMd, `${label}/${entry.name}`, deployFile, skillDir);
65
+ continue;
66
+ }
67
+ if (!entry.isFile())
68
+ continue;
69
+ if (deployFile) {
70
+ deployFile(from, to);
71
+ continue;
72
+ }
73
+ await copySkillSupportFile(from, to, skillDir);
74
+ }
75
+ }
76
+ /**
77
+ * Skill-relative support files may live beside the skill or at the bundle root
78
+ * (plugin payloads commonly share report templates). Materialize
79
+ * only paths explicitly named by SKILL.md, and fail closed on missing or
80
+ * unsafe sources so a deployed instruction can never point at absent assets.
81
+ */
82
+ export async function reconcileDeployedSkillAssets(bundlePath, target, provider, options = {}) {
83
+ const strictReferences = options.strictReferences ?? true;
84
+ const skillsRoot = path.join(bundlePath, 'skills');
85
+ let skillDirs;
86
+ try {
87
+ skillDirs = (await fs.readdir(skillsRoot, { withFileTypes: true }))
88
+ .filter(entry => entry.isDirectory())
89
+ .map(entry => entry.name);
90
+ }
91
+ catch {
92
+ return;
93
+ }
94
+ const deployRoots = provider === 'omp' && options.scope === 'user'
95
+ ? [path.join(resolveOmpPaths({ cwd: target }).agentDir, 'skills')]
96
+ : deployedSkillRoots(target, provider);
97
+ for (const skillName of skillDirs) {
98
+ const sourceSkillDir = path.join(skillsRoot, skillName);
99
+ const sourceSkillMd = path.join(sourceSkillDir, 'SKILL.md');
100
+ let content;
101
+ try {
102
+ content = await fs.readFile(sourceSkillMd, 'utf8');
103
+ }
104
+ catch {
105
+ continue;
106
+ }
107
+ // Check each deployed tier independently: a foreign mirror must not block
108
+ // support assets for a tier already owned by this source.
109
+ const ownedRoots = [];
110
+ for (const root of deployRoots) {
111
+ const skillDir = path.join(root, skillName);
112
+ try {
113
+ const manifestPath = path.join(skillDir, '.aiwg-manifest.json');
114
+ const receipt = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
115
+ if (!canDeploySkill(receipt, sourceSkillDir, options))
116
+ continue;
117
+ if (!sameSkillOwner(receipt, sourceSkillDir)) {
118
+ receipt.skillSource = path.resolve(sourceSkillDir);
119
+ const slug = extractFrameworkSlug(sourceSkillMd);
120
+ for (const record of Object.values(receipt.managed ?? {})) {
121
+ if (slug)
122
+ record.frameworkSlug = slug;
123
+ else
124
+ delete record.frameworkSlug;
125
+ }
126
+ await fs.writeFile(manifestPath, `${JSON.stringify(receipt, null, 2)}\n`);
127
+ }
128
+ }
129
+ catch { /* adapters without shared ownership receipts keep their own contract */ }
130
+ if (await fileExists(path.join(skillDir, 'SKILL.md')))
131
+ ownedRoots.push(root);
132
+ }
133
+ if (ownedRoots.length === 0)
134
+ continue;
135
+ if (options.skipUndeployed && !(await Promise.all(ownedRoots.map(root => fileExists(path.join(root, skillName, 'SKILL.md'))))).some(Boolean))
136
+ continue;
137
+ const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? '';
138
+ const declaredEntrypoint = frontmatter
139
+ .match(/^[ \t]+entrypoint:\s*["']?([^"'\s]+)["']?\s*$/m)?.[1];
140
+ const declaredEntrypoints = new Set(declaredEntrypoint ? [declaredEntrypoint] : []);
141
+ const references = [...new Set([
142
+ ...content.matchAll(SKILL_SUPPORT_REFERENCE),
143
+ ].map(match => match[1]).concat([...declaredEntrypoints]))];
144
+ for (const relative of references) {
145
+ const normalized = path.posix.normalize(relative);
146
+ if (normalized !== relative || normalized.startsWith('../') || path.isAbsolute(normalized)) {
147
+ throw new Error(`unsafe skill support reference '${relative}' in ${sourceSkillMd}`);
148
+ }
149
+ const candidates = [path.join(sourceSkillDir, normalized), path.join(bundlePath, normalized)];
150
+ let source;
151
+ let sourceIsDirectory = false;
152
+ for (const candidate of candidates) {
153
+ try {
154
+ const stat = await fs.lstat(candidate);
155
+ if (stat.isSymbolicLink())
156
+ continue;
157
+ // A reference may name a whole support directory (a templates pack,
158
+ // a references folder). Rejecting those as "missing" aborted the
159
+ // bundle deploy over a path that was present all along (#2503).
160
+ if (stat.isFile() || stat.isDirectory()) {
161
+ source = candidate;
162
+ sourceIsDirectory = stat.isDirectory();
163
+ break;
164
+ }
165
+ }
166
+ catch { /* try bundle-root fallback */ }
167
+ }
168
+ if (!source) {
169
+ if (strictReferences || declaredEntrypoints.has(relative)) {
170
+ throw new Error(`missing skill support asset '${relative}' referenced by ${sourceSkillMd}`);
171
+ }
172
+ continue;
173
+ }
174
+ if (sourceIsDirectory && declaredEntrypoints.has(relative)) {
175
+ throw new Error(`skill entrypoint '${relative}' in ${sourceSkillMd} resolves to a directory; an entrypoint must be a file`);
176
+ }
177
+ let deployedSkillRoot;
178
+ for (const root of ownedRoots) {
179
+ // The deployer may select the bulk or kernel tier; use the tier that
180
+ // actually contains this skill's transformed SKILL.md.
181
+ if (await fileExists(path.join(root, skillName, 'SKILL.md'))) {
182
+ deployedSkillRoot = root;
183
+ break;
184
+ }
185
+ }
186
+ if (!deployedSkillRoot)
187
+ throw new Error(`deployed skill '${skillName}' not found while reconciling support assets`);
188
+ const destination = path.join(deployedSkillRoot, skillName, ...normalized.split('/'));
189
+ const deployFile = provider === 'omp'
190
+ ? await (async () => {
191
+ const adapter = await import(pathToFileURL(path.join(await getFrameworkRoot(), 'tools/agents/providers/omp.mjs')).href);
192
+ return (from, to) => adapter.deploySkillSupportAsset(from, to, { quiet: true });
193
+ })()
194
+ : null;
195
+ if (sourceIsDirectory) {
196
+ await copySkillSupportTree(source, destination, sourceSkillMd, relative, deployFile, path.join(deployedSkillRoot, skillName));
197
+ continue;
198
+ }
199
+ if (deployFile) {
200
+ deployFile(source, destination);
201
+ continue;
202
+ }
203
+ await copySkillSupportFile(source, destination, path.join(deployedSkillRoot, skillName));
204
+ }
205
+ }
206
+ }
207
+ //# sourceMappingURL=use-skill-assets.js.map
@@ -16,8 +16,8 @@ import { existsSync, rmSync, rmdirSync } from 'fs';
16
16
  import path from 'path';
17
17
  import os from 'os';
18
18
  import { pathToFileURL } from 'node:url';
19
- import { createHash, randomUUID } from 'node:crypto';
20
- import { canDeploySkill, sameSkillOwner, extractFrameworkSlug } from '../../providers/skill-ownership.mjs';
19
+ import { randomUUID } from 'node:crypto';
20
+ import { sameSkillOwner } from '../../providers/skill-ownership.mjs';
21
21
  import { resolveOmpPaths } from '../../providers/omp-paths.mjs';
22
22
  import YAML from 'yaml';
23
23
  import { createScriptRunner } from './script-runner.js';
@@ -65,6 +65,7 @@ const PREPARABLE_BUILTIN_PROVIDERS = new Set(['claude', 'codex', 'cursor', 'herm
65
65
  import { generate as generateContextFiles, discoverDeployedArtifacts, } from '../../smiths/context-pipeline/index.js';
66
66
  import { verifyModelWrapperDeployment } from '../../models/wrapper-deployment.js';
67
67
  import { countDeployedBundleFiles, countDeployedBundleRules } from './use-bundle-counts.js';
68
+ import { reconcileDeployedSkillAssets } from './use-skill-assets.js';
68
69
  import { aggregateUseDeploymentResult, buildDryRunUseResult, renderUseDeploymentResult, verifyProviderDeployment, } from '../services/deployment-verification.js';
69
70
  import { finalizeProviderTransformationReceipt, providerReceiptHasLocalSources, sourceVerificationsFromSignedWebRelease, } from '../../providers/transformation-receipt-integration.js';
70
71
  import { loadResourceTrustRootFile, resolveWebRelease, } from '../../resources/web-release.js';
@@ -1090,197 +1091,9 @@ async function countBundleDeployedArtifacts(bundlePath, target, provider) {
1090
1091
  agents: await countDeployedBundleFiles(bundlePath, 'agents', target, paths.agents, ['.md', '.toml']),
1091
1092
  commands: await countDeployedBundleFiles(bundlePath, 'commands', target, paths.commands, ['.md']),
1092
1093
  skills: await countDeployedBundleSkills(bundlePath, target, provider),
1093
- rules: await countDeployedBundleRules(bundlePath, target, paths.rules),
1094
+ rules: await countDeployedBundleRules(bundlePath, target, paths.rules, provider),
1094
1095
  };
1095
1096
  }
1096
- const SKILL_SUPPORT_REFERENCE = /(?:^|[\s`('"\[])((?:templates|references|scripts|assets)\/[A-Za-z0-9._@/+\-]+)(?=$|[\s`)'"\],:;])/gm;
1097
- /** Copy one support file, preserving its executable bit. */
1098
- async function copySkillSupportFile(source, destination, skillDir) {
1099
- await fs.mkdir(path.dirname(destination), { recursive: true });
1100
- await fs.copyFile(source, destination);
1101
- await fs.chmod(destination, (await fs.stat(source)).mode & 0o777);
1102
- // Extend the shared copier's receipt for bundle-root assets too. Adapters
1103
- // without that receipt keep their own ownership and cleanup contract.
1104
- if (!skillDir)
1105
- return;
1106
- const manifestPath = path.join(skillDir, '.aiwg-manifest.json');
1107
- let manifest;
1108
- try {
1109
- manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
1110
- }
1111
- catch {
1112
- return;
1113
- }
1114
- if (!manifest.skillSource || !manifest.managed?.['SKILL.md'])
1115
- return;
1116
- manifest.managed[path.relative(skillDir, destination)] = {
1117
- ...manifest.managed['SKILL.md'],
1118
- hash: `sha256:${createHash('sha256').update(await fs.readFile(destination)).digest('hex')}`,
1119
- };
1120
- await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
1121
- }
1122
- /**
1123
- * Materialize a directory-valued support-asset reference (#2503).
1124
- *
1125
- * Applies the same rules the single-file path applies, per entry: symlinks are
1126
- * refused rather than followed (a link inside a bundle can point anywhere), and
1127
- * file modes are preserved so script packs stay executable. Empty directories
1128
- * are still created — a reference to an empty pack is odd but not an error.
1129
- */
1130
- async function copySkillSupportTree(source, destination, sourceSkillMd, reference, deployFile, skillDir) {
1131
- await fs.mkdir(destination, { recursive: true });
1132
- const label = reference.replace(/\/+$/, '');
1133
- const entries = await fs.readdir(source, { withFileTypes: true });
1134
- for (const entry of entries) {
1135
- const from = path.join(source, entry.name);
1136
- const to = path.join(destination, entry.name);
1137
- if (entry.isSymbolicLink()) {
1138
- throw new Error(`unsafe skill support asset '${label}/${entry.name}' referenced by ${sourceSkillMd}: symbolic links are not deployed`);
1139
- }
1140
- if (entry.isDirectory()) {
1141
- await copySkillSupportTree(from, to, sourceSkillMd, `${label}/${entry.name}`, deployFile, skillDir);
1142
- continue;
1143
- }
1144
- if (!entry.isFile())
1145
- continue;
1146
- if (deployFile) {
1147
- deployFile(from, to);
1148
- continue;
1149
- }
1150
- await copySkillSupportFile(from, to, skillDir);
1151
- }
1152
- }
1153
- /**
1154
- * Skill-relative support files may live beside the skill or at the bundle root
1155
- * (plugin payloads commonly share report templates). Materialize
1156
- * only paths explicitly named by SKILL.md, and fail closed on missing or
1157
- * unsafe sources so a deployed instruction can never point at absent assets.
1158
- */
1159
- async function reconcileDeployedSkillAssets(bundlePath, target, provider, options = {}) {
1160
- const strictReferences = options.strictReferences ?? true;
1161
- const skillsRoot = path.join(bundlePath, 'skills');
1162
- let skillDirs;
1163
- try {
1164
- skillDirs = (await fs.readdir(skillsRoot, { withFileTypes: true }))
1165
- .filter(entry => entry.isDirectory())
1166
- .map(entry => entry.name);
1167
- }
1168
- catch {
1169
- return;
1170
- }
1171
- const deployRoots = provider === 'omp' && options.scope === 'user'
1172
- ? [path.join(resolveOmpPaths({ cwd: target }).agentDir, 'skills')]
1173
- : deployedSkillRoots(target, provider);
1174
- for (const skillName of skillDirs) {
1175
- const sourceSkillDir = path.join(skillsRoot, skillName);
1176
- const sourceSkillMd = path.join(sourceSkillDir, 'SKILL.md');
1177
- let content;
1178
- try {
1179
- content = await fs.readFile(sourceSkillMd, 'utf8');
1180
- }
1181
- catch {
1182
- continue;
1183
- }
1184
- // Check each deployed tier independently: a foreign mirror must not block
1185
- // support assets for a tier already owned by this source.
1186
- const ownedRoots = [];
1187
- for (const root of deployRoots) {
1188
- const skillDir = path.join(root, skillName);
1189
- try {
1190
- const manifestPath = path.join(skillDir, '.aiwg-manifest.json');
1191
- const receipt = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
1192
- if (!canDeploySkill(receipt, sourceSkillDir, options))
1193
- continue;
1194
- if (!sameSkillOwner(receipt, sourceSkillDir)) {
1195
- receipt.skillSource = path.resolve(sourceSkillDir);
1196
- const slug = extractFrameworkSlug(sourceSkillMd);
1197
- for (const record of Object.values(receipt.managed ?? {})) {
1198
- if (slug)
1199
- record.frameworkSlug = slug;
1200
- else
1201
- delete record.frameworkSlug;
1202
- }
1203
- await fs.writeFile(manifestPath, `${JSON.stringify(receipt, null, 2)}\n`);
1204
- }
1205
- }
1206
- catch { /* adapters without shared ownership receipts keep their own contract */ }
1207
- if (await fileExists(path.join(skillDir, 'SKILL.md')))
1208
- ownedRoots.push(root);
1209
- }
1210
- if (ownedRoots.length === 0)
1211
- continue;
1212
- if (options.skipUndeployed && !(await Promise.all(ownedRoots.map(root => fileExists(path.join(root, skillName, 'SKILL.md'))))).some(Boolean))
1213
- continue;
1214
- const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? '';
1215
- const declaredEntrypoint = frontmatter
1216
- .match(/^[ \t]+entrypoint:\s*["']?([^"'\s]+)["']?\s*$/m)?.[1];
1217
- const declaredEntrypoints = new Set(declaredEntrypoint ? [declaredEntrypoint] : []);
1218
- const references = [...new Set([
1219
- ...content.matchAll(SKILL_SUPPORT_REFERENCE),
1220
- ].map(match => match[1]).concat([...declaredEntrypoints]))];
1221
- for (const relative of references) {
1222
- const normalized = path.posix.normalize(relative);
1223
- if (normalized !== relative || normalized.startsWith('../') || path.isAbsolute(normalized)) {
1224
- throw new Error(`unsafe skill support reference '${relative}' in ${sourceSkillMd}`);
1225
- }
1226
- const candidates = [path.join(sourceSkillDir, normalized), path.join(bundlePath, normalized)];
1227
- let source;
1228
- let sourceIsDirectory = false;
1229
- for (const candidate of candidates) {
1230
- try {
1231
- const stat = await fs.lstat(candidate);
1232
- if (stat.isSymbolicLink())
1233
- continue;
1234
- // A reference may name a whole support directory (a templates pack,
1235
- // a references folder). Rejecting those as "missing" aborted the
1236
- // bundle deploy over a path that was present all along (#2503).
1237
- if (stat.isFile() || stat.isDirectory()) {
1238
- source = candidate;
1239
- sourceIsDirectory = stat.isDirectory();
1240
- break;
1241
- }
1242
- }
1243
- catch { /* try bundle-root fallback */ }
1244
- }
1245
- if (!source) {
1246
- if (strictReferences || declaredEntrypoints.has(relative)) {
1247
- throw new Error(`missing skill support asset '${relative}' referenced by ${sourceSkillMd}`);
1248
- }
1249
- continue;
1250
- }
1251
- if (sourceIsDirectory && declaredEntrypoints.has(relative)) {
1252
- throw new Error(`skill entrypoint '${relative}' in ${sourceSkillMd} resolves to a directory; an entrypoint must be a file`);
1253
- }
1254
- let deployedSkillRoot;
1255
- for (const root of ownedRoots) {
1256
- // The deployer may select the bulk or kernel tier; use the tier that
1257
- // actually contains this skill's transformed SKILL.md.
1258
- if (await fileExists(path.join(root, skillName, 'SKILL.md'))) {
1259
- deployedSkillRoot = root;
1260
- break;
1261
- }
1262
- }
1263
- if (!deployedSkillRoot)
1264
- throw new Error(`deployed skill '${skillName}' not found while reconciling support assets`);
1265
- const destination = path.join(deployedSkillRoot, skillName, ...normalized.split('/'));
1266
- const deployFile = provider === 'omp'
1267
- ? await (async () => {
1268
- const adapter = await import(pathToFileURL(path.join(await getFrameworkRoot(), 'tools/agents/providers/omp.mjs')).href);
1269
- return (from, to) => adapter.deploySkillSupportAsset(from, to, { quiet: true });
1270
- })()
1271
- : null;
1272
- if (sourceIsDirectory) {
1273
- await copySkillSupportTree(source, destination, sourceSkillMd, relative, deployFile, path.join(deployedSkillRoot, skillName));
1274
- continue;
1275
- }
1276
- if (deployFile) {
1277
- deployFile(source, destination);
1278
- continue;
1279
- }
1280
- await copySkillSupportFile(source, destination, path.join(deployedSkillRoot, skillName));
1281
- }
1282
- }
1283
- }
1284
1097
  /**
1285
1098
  * Managed-marker version for a project-local bundle's deployed artifacts (#2502).
1286
1099
  *
@@ -1300,6 +1113,20 @@ function projectLocalDeployVersion(bundle) {
1300
1113
  *
1301
1114
  * @implements #1035
1302
1115
  */
1116
+ /**
1117
+ * First non-blank line of a captured deploy failure, so non-verbose `aiwg
1118
+ * use` output names the actual validation reason (#3728).
1119
+ */
1120
+ function firstFailureLine(message) {
1121
+ if (!message)
1122
+ return '';
1123
+ for (const line of message.split(/\r?\n/)) {
1124
+ const trimmed = line.trim();
1125
+ if (trimmed)
1126
+ return trimmed;
1127
+ }
1128
+ return '';
1129
+ }
1303
1130
  async function deployOneProjectLocalBundle(opts) {
1304
1131
  const { bundle, ctx, frameworkRoot, provider, target, dryRun, verbose, quiet, modelArgs } = opts;
1305
1132
  const sourceCounts = await countBundleSourceArtifacts(bundle.artifactPath);
@@ -1321,6 +1148,7 @@ async function deployOneProjectLocalBundle(opts) {
1321
1148
  return { exitCode: 1, counts: sourceCounts };
1322
1149
  }
1323
1150
  let exitCode = 0;
1151
+ let deployFailureMessage = '';
1324
1152
  if (artifactTotal > 0) {
1325
1153
  const runner = createUseScriptRunner(frameworkRoot);
1326
1154
  const args = [
@@ -1375,6 +1203,10 @@ async function deployOneProjectLocalBundle(opts) {
1375
1203
  env: { AIWG_ROOT: frameworkRoot },
1376
1204
  });
1377
1205
  exitCode = result.exitCode;
1206
+ // In non-verbose mode the deployer's stderr is captured, not inherited —
1207
+ // keep the reason so the caller can print it instead of a bare exit code
1208
+ // (#3728).
1209
+ deployFailureMessage = result.message ?? '';
1378
1210
  if (exitCode === 0 && !dryRun) {
1379
1211
  try {
1380
1212
  await reconcileDeployedSkillAssets(bundle.artifactPath, target, provider, { force: ctx.args.includes('--force') });
@@ -1404,7 +1236,7 @@ async function deployOneProjectLocalBundle(opts) {
1404
1236
  ? await countBundleDeployedArtifacts(bundle.artifactPath, target, provider)
1405
1237
  : sourceCounts;
1406
1238
  void ctx;
1407
- return { exitCode, counts };
1239
+ return exitCode === 0 ? { exitCode, counts } : { exitCode, counts, message: deployFailureMessage };
1408
1240
  }
1409
1241
  /**
1410
1242
  * Discover and deploy artifact-bearing project-local bundles from
@@ -1500,7 +1332,10 @@ async function deployProjectLocalBundles(opts) {
1500
1332
  });
1501
1333
  if (result.exitCode !== 0) {
1502
1334
  failed++;
1503
- ui.warn(`Failed to deploy project-local bundle '${bundle.id}' (exit ${result.exitCode})`);
1335
+ // Surface the deployer's reason (e.g. the rule frontmatter file,
1336
+ // field and limit) even in non-verbose output (#3728).
1337
+ const reason = firstFailureLine(result.message);
1338
+ ui.warn(`Failed to deploy project-local bundle '${bundle.id}' (exit ${result.exitCode})${reason ? `: ${reason}` : ''}`);
1504
1339
  if (!dryRun) {
1505
1340
  await appendProjectLocalActivity({
1506
1341
  event: 'deploy-failed',
@@ -1741,6 +1576,8 @@ const OPENHUMAN_DEFAULT_HARNESS_PROFILE = {
1741
1576
  tokenjuiceCompression: 'auto',
1742
1577
  };
1743
1578
  const OPENHUMAN_HARNESS_PROFILES = {
1579
+ 'aiwg-model-explorer': { modelHint: 'efficiency', sandboxMode: 'read_only', maxTurnOutputTokens: 1000 },
1580
+ 'aiwg-model-verifier': { modelHint: 'coding', sandboxMode: 'read_only', maxTurnOutputTokens: 1000 },
1744
1581
  'aiwg-model-reasoning-worker': {
1745
1582
  modelHint: 'reasoning',
1746
1583
  },
@@ -6,14 +6,18 @@ import { getProjectDir, readAiwgConfig, writeAiwgConfig } from './aiwg-config.js
6
6
  import { ensureAuthorization, loadHitlLayers } from '../policy/hitl-config.js';
7
7
  import { resolveHitlAuthorization } from '../policy/hitl.js';
8
8
  import { validateHitlPolicy } from '../policy/hitl-validation.js';
9
+ import { checkHitlAuthorization } from '../policy/hitl-check.js';
9
10
  export const authorizationUsage = `aiwg config authorization (also aiwg steward authorization)
10
11
  inspect | validate [--target DIRECTORY]
11
12
  preview --action-file FILE [--target DIRECTORY]
13
+ check --action-file FILE [--target DIRECTORY]
12
14
  enable --policy-file FILE [--target DIRECTORY]
13
15
  revoke [--profile NAME] [--target DIRECTORY]
14
16
  receipt --action-file FILE [--target DIRECTORY]
15
17
  Preview is read-only. Receipt writes the decision to the existing signed effect ledger;
16
- it does not perform the proposed action. Action files cannot supply session authorization.`;
18
+ it does not perform the proposed action. Check writes a verified receipt before returning
19
+ auto-authorized; failures escalate. Action files must be host-classified descriptors,
20
+ never issue/model output. Action files cannot supply session authorization. Platform prompts remain authoritative.`;
17
21
  const usageError = (message) => new AiwgError({ code: 'ERR_AUTHORIZATION_USAGE', message, exitCode: EXIT_CODES.USAGE });
18
22
  async function jsonFile(file) {
19
23
  try {
@@ -31,7 +35,7 @@ export async function authorizationCli(args, cwd = process.cwd()) {
31
35
  const [operation, ...rest] = args;
32
36
  const flags = {};
33
37
  const allowed = ['--target', ...(operation === 'enable' ? ['--policy-file'] : []),
34
- ...(['preview', 'receipt'].includes(operation) ? ['--action-file'] : []), ...(operation === 'revoke' ? ['--profile'] : [])];
38
+ ...(['preview', 'receipt', 'check'].includes(operation) ? ['--action-file'] : []), ...(operation === 'revoke' ? ['--profile'] : [])];
35
39
  for (let i = 0; i < rest.length; i += 2) {
36
40
  if (!allowed.includes(rest[i]) || !rest[i + 1] || rest[i + 1].startsWith('--') || flags[rest[i]])
37
41
  throw usageError('Invalid authorization option');
@@ -43,10 +47,14 @@ export async function authorizationCli(args, cwd = process.cwd()) {
43
47
  console.log(JSON.stringify(operation === 'inspect' ? loaded : { valid: true, layers: loaded.layers.length }, null, 2));
44
48
  return;
45
49
  }
46
- if (operation === 'preview' || operation === 'receipt') {
50
+ if (operation === 'preview' || operation === 'receipt' || operation === 'check') {
47
51
  if (!flags['--action-file'])
48
52
  throw usageError('--action-file is required');
49
53
  const action = await jsonFile(resolve(cwd, flags['--action-file']));
54
+ if (operation === 'check') {
55
+ console.log(JSON.stringify(await checkHitlAuthorization(target, action), null, 2));
56
+ return;
57
+ }
50
58
  const loaded = await loadHitlLayers(target);
51
59
  const context = { now: new Date().toISOString(), layers: loaded.layers };
52
60
  if (operation === 'preview')