@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,17 +1,8 @@
1
1
  import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { load as loadYaml } from 'js-yaml';
4
- import { MODEL_WRAPPERS } from './provider-models.js';
5
- const TIERS = {
6
- reasoning: 'premium',
7
- coding: 'standard',
8
- efficiency: 'economy',
9
- };
10
- const EFFORTS = {
11
- reasoning: 'high',
12
- coding: 'medium',
13
- efficiency: 'low',
14
- };
4
+ import { MODEL_WRAPPER_DEFINITIONS } from './wrapper-definitions.js';
5
+ import { isFlagshipModel } from './tiers.js';
15
6
  const CLAUDE_ALIASES = {
16
7
  reasoning: 'opus',
17
8
  coding: 'sonnet',
@@ -66,7 +57,7 @@ function artifactFields(file, content) {
66
57
  if (/\.json$/i.test(file)) {
67
58
  try {
68
59
  const parsed = JSON.parse(content);
69
- return parsed && typeof parsed === 'object' ? parsed : null;
60
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
70
61
  }
71
62
  catch {
72
63
  return null;
@@ -94,38 +85,69 @@ function addMismatch(mismatches, wrapper, file, field, reason, expected, actual)
94
85
  reason,
95
86
  });
96
87
  }
97
- async function validateArtifact(file, role, expectation) {
98
- const wrapper = MODEL_WRAPPERS[role];
88
+ async function validateArtifact(file, definition, expectation) {
89
+ const { name: wrapper, role, tier, effort, readOnly } = definition;
99
90
  const mismatches = [];
100
91
  const content = await fs.readFile(file, 'utf8');
101
92
  if (!content.trim()) {
102
93
  addMismatch(mismatches, wrapper, file, 'content', 'wrapper artifact is empty');
103
94
  return mismatches;
104
95
  }
105
- const fields = artifactFields(file, content);
96
+ const fields = artifactFields(file, content)
97
+ ?? (expectation.provider === 'windsurf' && content.includes(`### ${wrapper}`) ? { name: wrapper } : null);
106
98
  if (!fields) {
107
99
  addMismatch(mismatches, wrapper, file, 'format', 'wrapper artifact is malformed or has no parseable metadata');
108
100
  return mismatches;
109
101
  }
110
- const actualName = fieldValue(fields, 'name');
102
+ const actualName = fieldValue(fields, 'name') ?? (expectation.provider === 'opencode' ? wrapper : undefined);
111
103
  if (actualName !== wrapper)
112
104
  addMismatch(mismatches, wrapper, file, 'name', 'wrapper identity does not match its deployed filename', wrapper, actualName);
113
105
  const actualRole = fieldValue(fields, 'model-role', 'modelRole', 'aiwg-model-role');
114
106
  if (actualRole && actualRole !== role)
115
107
  addMismatch(mismatches, wrapper, file, 'model-role', 'wrapper role is stale or mismatched', role, actualRole);
116
108
  const actualTier = fieldValue(fields, 'model-tier', 'modelTier', 'aiwg-model-tier');
117
- if (actualTier && actualTier !== TIERS[role])
118
- addMismatch(mismatches, wrapper, file, 'model-tier', 'wrapper tier is stale or mismatched', TIERS[role], actualTier);
109
+ const standardFallback = tier === 'economy' && actualTier === 'standard'
110
+ && (readOnly || expectation.provider === 'cursor');
111
+ if (actualTier && actualTier !== tier && !standardFallback)
112
+ addMismatch(mismatches, wrapper, file, 'model-tier', 'wrapper tier is stale or mismatched', tier, actualTier);
119
113
  const actualModel = fieldValue(fields, 'model', 'model_hint', 'modelHint');
120
114
  const expectedModel = expectation.models?.[role];
115
+ if (actualModel && isFlagshipModel(actualModel))
116
+ addMismatch(mismatches, wrapper, file, 'model', 'wrapper model is flagship; wrappers cannot elect flagship', undefined, actualModel);
117
+ if (readOnly) {
118
+ if (expectation.provider === 'codex' && fields.sandbox_mode !== 'read-only')
119
+ addMismatch(mismatches, wrapper, file, 'sandbox_mode', 'read-only wrapper must use the native read-only sandbox', 'read-only', fieldValue(fields, 'sandbox_mode'));
120
+ const tools = Array.isArray(fields.tools) ? fields.tools : typeof fields.tools === 'string' ? fields.tools.split(/[,\s]+/) : [];
121
+ if (['claude', 'copilot', 'factory', 'omp', 'antigravity', 'openclaw'].includes(expectation.provider ?? '') && tools.length === 0)
122
+ addMismatch(mismatches, wrapper, file, 'tools', 'read-only wrapper is missing its explicit tool allowlist');
123
+ if (tools.some(tool => /^(?:write|edit|create|apply[_-]?patch|multiedit|task|agent|write_to_file|replace_file_content)$/i.test(String(tool))))
124
+ addMismatch(mismatches, wrapper, file, 'tools', 'read-only wrapper exposes mutation or delegation tools');
125
+ const allowlists = {
126
+ claude: ['Read', 'Grep', 'Glob', 'Bash'], copilot: ['search/codebase', 'terminal'],
127
+ factory: ['Execute', 'Glob', 'Grep', 'Read'], omp: ['read', 'grep', 'glob', 'bash'],
128
+ antigravity: ['view_file', 'grep_search', 'run_command'], openclaw: ['Read', 'Grep', 'Glob', 'Bash'],
129
+ };
130
+ const allowed = allowlists[expectation.provider ?? ''];
131
+ if (allowed && (tools.length !== allowed.length || allowed.some(tool => !tools.includes(tool))))
132
+ addMismatch(mismatches, wrapper, file, 'tools', 'read-only wrapper tools differ from the provider allowlist');
133
+ if (expectation.provider === 'opencode') {
134
+ const permissions = fields.permission;
135
+ if (permissions?.edit !== 'deny' || permissions?.task !== 'deny' || permissions?.['*'] !== 'deny')
136
+ addMismatch(mismatches, wrapper, file, 'permission', 'read-only wrapper must deny edits, delegation and unlisted tools');
137
+ }
138
+ if (expectation.provider === 'cursor' && fields.readonly !== true)
139
+ addMismatch(mismatches, wrapper, file, 'readonly', 'Cursor wrapper must enable its native read-only control');
140
+ if (!content.includes('WorkerClaims') || !content.includes('criterion') || !content.includes('Stop rules'))
141
+ addMismatch(mismatches, wrapper, file, 'return-contract', 'read-only wrapper is missing its condensed worker return contract');
142
+ }
121
143
  if (expectation.provider === 'codex') {
122
144
  if (!actualModel)
123
145
  addMismatch(mismatches, wrapper, file, 'model', 'Codex wrapper has no exact model pin', expectedModel);
124
146
  else if (expectedModel && actualModel !== expectedModel)
125
147
  addMismatch(mismatches, wrapper, file, 'model', 'Codex wrapper model does not match the effective catalog', expectedModel, actualModel);
126
148
  const actualEffort = fieldValue(fields, 'model_reasoning_effort');
127
- if (actualEffort !== EFFORTS[role])
128
- addMismatch(mismatches, wrapper, file, 'model_reasoning_effort', 'Codex wrapper effort does not match its role', EFFORTS[role], actualEffort);
149
+ if (actualEffort !== effort)
150
+ addMismatch(mismatches, wrapper, file, 'model_reasoning_effort', 'Codex wrapper effort does not match its role', effort, actualEffort);
129
151
  if (!fieldValue(fields, 'developer_instructions'))
130
152
  addMismatch(mismatches, wrapper, file, 'developer_instructions', 'Codex wrapper has no bootstrap instructions', 'non-empty');
131
153
  }
@@ -136,26 +158,27 @@ async function validateArtifact(file, role, expectation) {
136
158
  if (!actualRole)
137
159
  addMismatch(mismatches, wrapper, file, 'model-role', 'Claude wrapper is missing its canonical role', role);
138
160
  if (!actualTier)
139
- addMismatch(mismatches, wrapper, file, 'model-tier', 'Claude wrapper is missing its canonical tier', TIERS[role]);
161
+ addMismatch(mismatches, wrapper, file, 'model-tier', 'Claude wrapper is missing its canonical tier', tier);
140
162
  }
141
163
  return mismatches;
142
164
  }
143
165
  export async function verifyModelWrapperDeployment(agentsPath, expectation = {}) {
144
- const expected = Object.entries(MODEL_WRAPPERS);
166
+ const expected = MODEL_WRAPPER_DEFINITIONS;
145
167
  if (!agentsPath)
146
168
  return {
147
169
  supported: false,
148
170
  valid: false,
149
171
  agentsPath: null,
150
172
  found: [],
151
- missing: expected.map(([, wrapper]) => wrapper),
173
+ missing: expected.map(({ name }) => name),
152
174
  mismatches: [],
153
175
  };
154
176
  const files = await collectFiles(agentsPath);
155
177
  const found = [];
156
178
  const missing = [];
157
179
  const mismatches = [];
158
- for (const [role, wrapper] of expected) {
180
+ for (const definition of expected) {
181
+ const wrapper = definition.name;
159
182
  const matches = files.filter(file => path.basename(file).replace(/(?:\.agent)?\.(?:md|toml|json|yaml|yml)$/i, '') === wrapper);
160
183
  if (matches.length === 0) {
161
184
  missing.push(wrapper);
@@ -164,7 +187,7 @@ export async function verifyModelWrapperDeployment(agentsPath, expectation = {})
164
187
  found.push(wrapper);
165
188
  if (matches.length > 1)
166
189
  addMismatch(mismatches, wrapper, matches[0], 'path', `multiple deployed wrapper artifacts found: ${matches.join(', ')}`);
167
- mismatches.push(...await validateArtifact(matches[0], role, expectation));
190
+ mismatches.push(...await validateArtifact(matches[0], definition, expectation));
168
191
  }
169
192
  return {
170
193
  supported: true,
@@ -0,0 +1,72 @@
1
+ // Describes controls on deployed wrapper artifacts, distinct from headless CLI controls.
2
+ import { compileModelPolicy, loadProviderModelCatalog } from './catalog-policy.js';
3
+ import { MODEL_WRAPPER_DEFINITIONS } from './wrapper-definitions.js';
4
+ const NATIVE_CONTROLS = {
5
+ claude: { model: 'model', effort: 'effort' },
6
+ codex: { model: 'model', effort: 'model_reasoning_effort' },
7
+ copilot: { model: 'model' }, cursor: { model: 'model' },
8
+ factory: { model: 'model', effort: 'reasoningEffort' },
9
+ opencode: { model: 'model' }, omp: { model: 'model', effort: 'thinkingLevel' },
10
+ };
11
+ const GLOBAL_ONLY = new Set(['warp', 'hermes', 'grokbot', 'muse']);
12
+ export function wrapperControls(provider) {
13
+ return NATIVE_CONTROLS[provider] ?? {};
14
+ }
15
+ export function isConcreteWrapperModel(model) {
16
+ return Boolean(model && !/^(?:configured\/|Hint\(|auto$|inherit(?:ed)?$|default$|profile-selected$|global-delegation-model$)/i.test(model));
17
+ }
18
+ export function resolveWrapperPin(provider, wrapper, options = {}) {
19
+ const controls = wrapperControls(provider);
20
+ const catalog = options.catalog ?? loadProviderModelCatalog();
21
+ let tier = wrapper.tier;
22
+ let role = wrapper.role;
23
+ const compile = () => compileModelPolicy({ provider, artifact: 'agent', catalog,
24
+ policy: { role, tier, effort: options.effort ?? wrapper.effort,
25
+ ...(options.override ? { override: options.override } : {}) } });
26
+ let policy = compile();
27
+ // Auto can select a flagship; every economy wrapper needs the concrete fallback.
28
+ if (controls.model && policy.effectiveModel === 'auto' && !options.override) {
29
+ tier = 'standard';
30
+ role = 'coding';
31
+ policy = compile();
32
+ }
33
+ if (controls.model && options.override && !isConcreteWrapperModel(options.override)) {
34
+ throw new Error(`${provider}: wrapper override must be a concrete model pin`);
35
+ }
36
+ const model = controls.model && isConcreteWrapperModel(policy.effectiveModel) ? policy.effectiveModel : undefined;
37
+ const effort = model && controls.effort ? policy.fields[controls.effort] : undefined;
38
+ if (model && controls.effort && !effort)
39
+ throw new Error(`${provider}: unsupported wrapper effort`);
40
+ return { tier, role, model, effort, controls,
41
+ enforcement: (GLOBAL_ONLY.has(provider) ? 'global-only' : model ? 'pinned' : 'inherited') };
42
+ }
43
+ /** Static artifact defaults; this does not inspect live sessions or assert runtime enforcement. */
44
+ export function wrapperEnforcementReport(provider) {
45
+ const catalog = loadProviderModelCatalog();
46
+ const controls = wrapperControls(provider);
47
+ const known = provider in catalog.providers;
48
+ const states = known ? MODEL_WRAPPER_DEFINITIONS.map(wrapper => resolveWrapperPin(provider, wrapper, { catalog }).enforcement) : [];
49
+ const state = GLOBAL_ONLY.has(provider) ? 'global-only'
50
+ : states.length > 0 && states.every(value => value === 'pinned') ? 'pinned' : 'inherited';
51
+ const effort = state === 'pinned' && controls.effort
52
+ ? `pinned via ${controls.effort} (high/medium/low by wrapper)` : 'not enforced per wrapper';
53
+ const details = {
54
+ claude: 'Use AIWG wrappers or an explicit invocation model. Unpinned general-purpose agents inherit; CLAUDE_CODE_SUBAGENT_MODEL supplies a fallback and CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 can override pins.',
55
+ omp: 'Native model and thinkingLevel fields can pin exact operator role models; configured/* catalog entries are placeholders.',
56
+ 'grok-build': 'Not enforced: native-agent model translation remains gated by #2577; configured selectors do not establish tier enforcement.',
57
+ openclaw: 'Markdown wrapper mirrors do not set native subagents.model or per-spawn overrides.',
58
+ openhuman: 'User harness wrappers carry semantic model hints; project wrappers omit model. Neither is an exact pin.',
59
+ antigravity: 'Wrapper mirrors do not project native CLI model/effort flags.',
60
+ windsurf: 'Portable wrapper model selection is unsupported; the main UI session controls selection.',
61
+ pi: 'Agents are reference skills; CLI model/thinking flags are separate from deployed wrappers.',
62
+ 'deepseek-harness': 'Agent references do not pin the configured Harness route.',
63
+ hermes: 'All delegated workers share the provider delegation configuration.',
64
+ warp: 'Model selection follows the Warp run/profile.',
65
+ grokbot: 'No verified AIWG-owned per-worker model setting is available.',
66
+ muse: 'Session --model or settings.json model controls selection; per-agent pins are unverified.',
67
+ };
68
+ return `Tier enforcement (generated wrapper defaults): ${state}; effort: ${effort}. `
69
+ + `${details[provider] ?? (known ? 'Native custom subagents carry explicit catalog model selectors.' : 'Provider wrapper controls are unverified.')} `
70
+ + 'Explicit operator pins are preserved where supported. This is not a live resolved-model audit; provider/account policy may substitute models.';
71
+ }
72
+ //# sourceMappingURL=wrapper-enforcement.js.map
@@ -0,0 +1,80 @@
1
+ // Checks host-classified effects and requires a verified signed receipt before suppressing a workflow prompt.
2
+ import { lstat, realpath } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
4
+ import { effectSession, openLedger } from '../effects/host.js';
5
+ import { loadHitlLayers } from './hitl-config.js';
6
+ import { recordHitlAuthorization } from './hitl-receipt.js';
7
+ import { resolveHitlAuthorization, validHitlAction } from './hitl.js';
8
+ /** Resolve existing ancestors as well as new leaves; dangling links fail closed. */
9
+ async function canonical(path) {
10
+ try {
11
+ return await realpath(path);
12
+ }
13
+ catch (error) {
14
+ if (error.code !== 'ENOENT')
15
+ throw error;
16
+ try {
17
+ await lstat(path);
18
+ throw new Error('Unresolved action symlink');
19
+ }
20
+ catch (statError) {
21
+ if (statError.code !== 'ENOENT')
22
+ throw statError;
23
+ }
24
+ const parent = dirname(path);
25
+ if (parent === path)
26
+ throw error;
27
+ return resolve(await canonical(parent), basename(path));
28
+ }
29
+ }
30
+ const policyPath = (path) => /(^|\/)(aiwg\.config|AGENTS\.md|WORKSPACE\.md|AIWG\.md|CLAUDE\.md)$/.test(path)
31
+ || /(^|\/)(rules|policies|hooks)(\/|$)/.test(path)
32
+ || /^(\.git|\.claude|\.codex|\.agents|\.github|\.gitea)(\/|$)/.test(path);
33
+ const secretPath = (path) => /(^|\/)(\.env(?:\.[^/]*)?|\.ssh|\.aws|credentials?|tokens?|secrets?)(\/|$)/i.test(path);
34
+ /** Input is a host descriptor, never an issue, model response, or authorization claim. */
35
+ export async function canonicalHitlAction(projectDir, input) {
36
+ if (!validHitlAction(input))
37
+ return input;
38
+ const root = await realpath(projectDir);
39
+ const resources = [];
40
+ for (const path of input.resources) {
41
+ const resource = relative(root, await canonical(resolve(root, path))).split('\\').join('/');
42
+ if (!resource || resource === '..' || resource.startsWith('../') || isAbsolute(resource))
43
+ return null;
44
+ resources.push(resource);
45
+ }
46
+ const action = { ...input, resources: [...new Set(resources)].sort() };
47
+ // Check both spellings: an alias must not hide a protected resource.
48
+ const paths = [...input.resources, ...resources];
49
+ if (paths.some(secretPath))
50
+ action.category = 'secret.access';
51
+ else if (action.category !== 'repo.read' && paths.some(policyPath))
52
+ action.category = 'policy.override';
53
+ return action;
54
+ }
55
+ /** No receipt, no automatic action. Errors retain the caller's existing review path. */
56
+ export async function checkHitlAuthorization(projectDir, input, options = {}) {
57
+ let context = { now: new Date().toISOString(), layers: [], ...options };
58
+ try {
59
+ const loaded = await loadHitlLayers(projectDir);
60
+ context = { ...context, layers: loaded.layers };
61
+ const action = await canonicalHitlAction(loaded.projectDir, input);
62
+ const decision = resolveHitlAuthorization(action, context);
63
+ if (decision.decision !== 'auto-authorized')
64
+ return decision;
65
+ // Reload policies and the clock at consumption time, including expiry and revocation.
66
+ context = { ...context, now: new Date().toISOString(), layers: (await loadHitlLayers(projectDir)).layers,
67
+ expectedPolicyVersion: options.expectedPolicyVersion ?? decision.policyVersion };
68
+ const ledger = openLedger(await effectSession(loaded.projectDir, 'custom'));
69
+ const recorded = await recordHitlAuthorization(ledger, action, context);
70
+ if (recorded.resolution.decision !== 'auto-authorized')
71
+ return recorded.resolution;
72
+ if (recorded.reconciled.result.verification.result !== 'present')
73
+ throw new Error('Unverified HITL receipt');
74
+ return { ...recorded.resolution, receipt: { file: recorded.file, effectId: recorded.intent.effectId } };
75
+ }
76
+ catch {
77
+ return { ...resolveHitlAuthorization(null, context), decision: 'escalate', reason: 'authorization-check-unavailable' };
78
+ }
79
+ }
80
+ //# sourceMappingURL=hitl-check.js.map
@@ -19,6 +19,8 @@ export const ruleFrontmatterSchema: Record<string, unknown>;
19
19
  export function inferRuleActivation(enforcement?: unknown): 'on-demand';
20
20
  export function validateRuleFrontmatter(data: unknown): RuleValidationResult;
21
21
  export function parseRuleFrontmatter(content: string): RuleValidationResult & { data: unknown; body: string };
22
+ export const RULE_SUMMARY_MAX_LENGTH: number;
23
+ export function formatRuleFrontmatterError(file: string, data: unknown, diagnostics: RuleDiagnostic[]): string;
22
24
  export const CORE_BODY_MAX_BYTES: number;
23
25
  export const CORE_TOTAL_MAX_BYTES: number;
24
26
  export const CORE_RULES_START: string;
@@ -57,6 +57,29 @@ export function validateRuleFrontmatter(data) {
57
57
  };
58
58
  }
59
59
 
60
+ /** Maximum summary length in Unicode code points after trimming (#3728). */
61
+ export const RULE_SUMMARY_MAX_LENGTH = 240;
62
+
63
+ /**
64
+ * Render a rule frontmatter failure as one line naming the file, the field
65
+ * and the limit. Shared by deployment and `aiwg doctor --project-local`
66
+ * (#3728) so both surfaces report the same reason; the raw Ajv pattern
67
+ * message encodes the limit only as a regex, so a too-long summary gets an
68
+ * explicit sentence.
69
+ */
70
+ export function formatRuleFrontmatterError(file, data, diagnostics) {
71
+ const detail = diagnostics.map((item) => item.message).join('; ');
72
+ const summary = typeof data?.summary === 'string' ? data.summary.trim() : null;
73
+ if (
74
+ summary !== null
75
+ && [...summary].length > RULE_SUMMARY_MAX_LENGTH
76
+ && diagnostics.some((item) => item.message.includes('/summary'))
77
+ ) {
78
+ return `${file}: summary is ${[...summary].length} characters; the limit is ${RULE_SUMMARY_MAX_LENGTH} characters (single line). ${detail}`;
79
+ }
80
+ return `${file}: ${detail}`;
81
+ }
82
+
60
83
  /** Parse complete Markdown source, preserving authored body and opaque metadata. */
61
84
  export function parseRuleFrontmatter(content) {
62
85
  const source = content.replace(/^\uFEFF/, '');
@@ -9,6 +9,7 @@
9
9
  import fs from 'fs';
10
10
  import path from 'path';
11
11
  import { fileURLToPath } from 'url';
12
+ import { discoverLocalSkillOwners, higherLocalSkillOwner, selectSkillOwners } from '../collision-discovery.js';
12
13
  import { getProviderDefinition, resolveProviderPathValue, } from '../../providers/provider-definitions.js';
13
14
  const _scriptDir = path.dirname(fileURLToPath(import.meta.url));
14
15
  function resolveAiwgRoot() {
@@ -115,19 +116,28 @@ function deduplicateManifests(paths) {
115
116
  });
116
117
  }
117
118
  export class LocalAdapter {
119
+ discoveryOptions;
120
+ aiwgRoot;
118
121
  id = 'local';
119
122
  name = 'Local (AIWG Installation)';
120
123
  cachedSkills = null;
124
+ constructor(discoveryOptions, aiwgRoot = AIWG_ROOT) {
125
+ this.discoveryOptions = discoveryOptions;
126
+ this.aiwgRoot = aiwgRoot;
127
+ }
128
+ withLocalOwners(skills) {
129
+ return selectSkillOwners([...skills, ...discoverLocalSkillOwners(this.discoveryOptions ?? { projectDir: process.cwd() })]);
130
+ }
121
131
  async isAvailable() {
122
- return fs.existsSync(path.join(AIWG_ROOT, 'agentic', 'code'));
132
+ return fs.existsSync(path.join(this.aiwgRoot, 'agentic', 'code'));
123
133
  }
124
134
  async list() {
125
135
  if (this.cachedSkills)
126
- return this.cachedSkills;
136
+ return this.withLocalOwners(this.cachedSkills);
127
137
  const skills = [];
128
- const agenticDir = path.join(AIWG_ROOT, 'agentic', 'code');
138
+ const agenticDir = path.join(this.aiwgRoot, 'agentic', 'code');
129
139
  if (!fs.existsSync(agenticDir))
130
- return skills;
140
+ return this.withLocalOwners(skills);
131
141
  // Find all manifest.json files in frameworks/ and addons/
132
142
  const frameworksDir = path.join(agenticDir, 'frameworks');
133
143
  const addonsDir = path.join(agenticDir, 'addons');
@@ -163,6 +173,7 @@ export class LocalAdapter {
163
173
  name: skill.name,
164
174
  description: skill.description,
165
175
  source: 'local',
176
+ origin: 'aiwg-managed',
166
177
  package: packageName,
167
178
  platforms,
168
179
  installed: true,
@@ -202,6 +213,7 @@ export class LocalAdapter {
202
213
  name: skillName,
203
214
  description,
204
215
  source: 'local',
216
+ origin: 'aiwg-managed',
205
217
  package: packageName,
206
218
  platforms,
207
219
  installed: true,
@@ -212,7 +224,7 @@ export class LocalAdapter {
212
224
  }
213
225
  }
214
226
  this.cachedSkills = skills;
215
- return skills;
227
+ return this.withLocalOwners(skills);
216
228
  }
217
229
  async search(query) {
218
230
  const all = await this.list();
@@ -226,8 +238,10 @@ export class LocalAdapter {
226
238
  const match = all.find((s) => s.name === name);
227
239
  if (!match)
228
240
  return undefined;
241
+ if ('path' in match)
242
+ return match;
229
243
  // Find the SKILL.md for full details
230
- const agenticDir = path.join(AIWG_ROOT, 'agentic', 'code');
244
+ const agenticDir = path.join(this.aiwgRoot, 'agentic', 'code');
231
245
  const skillMdPaths = this.findSkillMds(agenticDir);
232
246
  const skillMdPath = skillMdPaths.find((p) => path.basename(path.dirname(p)) === name);
233
247
  const details = { ...match };
@@ -263,6 +277,11 @@ export class LocalAdapter {
263
277
  return details;
264
278
  }
265
279
  async install(name, options) {
280
+ const collision = higherLocalSkillOwner(name, 'aiwg-managed', {
281
+ ...this.discoveryOptions, projectDir: options.projectDir,
282
+ });
283
+ if (collision)
284
+ throw new Error(`${collision.origin}-owned skill "${name}" takes precedence over aiwg-managed-owned skill at ${collision.path}`);
266
285
  const details = await this.info(name);
267
286
  if (!details || !details.path) {
268
287
  throw new Error(`Skill '${name}' not found in local registry`);
@@ -280,16 +299,20 @@ export class LocalAdapter {
280
299
  }
281
300
  // Copy skill directory to target
282
301
  const sourceDir = path.dirname(details.path);
283
- fs.mkdirSync(targetDir, { recursive: true });
302
+ if (fs.existsSync(targetDir)) {
303
+ throw new Error(`project/user-owned target "${targetDir}" blocks aiwg-managed-owned skill "${name}"`);
304
+ }
305
+ fs.mkdirSync(path.dirname(targetDir), { recursive: true });
306
+ fs.mkdirSync(targetDir);
284
307
  const entries = fs.readdirSync(sourceDir, { withFileTypes: true });
285
308
  for (const entry of entries) {
286
309
  const srcPath = path.join(sourceDir, entry.name);
287
310
  const destPath = path.join(targetDir, entry.name);
288
311
  if (entry.isFile()) {
289
- fs.copyFileSync(srcPath, destPath);
312
+ fs.copyFileSync(srcPath, destPath, fs.constants.COPYFILE_EXCL);
290
313
  }
291
314
  else if (entry.isDirectory()) {
292
- fs.cpSync(srcPath, destPath, { recursive: true });
315
+ fs.cpSync(srcPath, destPath, { recursive: true, errorOnExist: true, force: false });
293
316
  }
294
317
  }
295
318
  // Codex `agents/openai.yaml` UI sidecar (#1129 PUW-028).
@@ -88,10 +88,12 @@ export const AIWG_SKILL_CONTROL_FIELDS = [
88
88
  /**
89
89
  * Higher values win. This preserves the upstream project-over-user rule while
90
90
  * keeping explicitly imported skills ahead of AIWG's packaged defaults.
91
+ * Account-synced skills sit below operator ownership; see docs/skills/agent-skills.md.
91
92
  */
92
93
  export const AGENT_SKILL_COLLISION_PRECEDENCE = Object.freeze({
93
94
  project: 400,
94
95
  user: 300,
96
+ synced: 250,
95
97
  imported: 200,
96
98
  'aiwg-managed': 100,
97
99
  });
@@ -0,0 +1,33 @@
1
+ export function displaySkillCollisions(skill) {
2
+ for (const diagnostic of skill.diagnostics ?? []) {
3
+ console.log(` ${diagnostic.code}: ${diagnostic.message} (${diagnostic.file})`);
4
+ }
5
+ }
6
+ /**
7
+ * Format skill results as a table
8
+ */
9
+ export function displaySkillsTable(skills) {
10
+ if (skills.length === 0) {
11
+ console.log(' No skills found.');
12
+ return;
13
+ }
14
+ // Group by source
15
+ const bySource = new Map();
16
+ for (const skill of skills) {
17
+ const list = bySource.get(skill.source) || [];
18
+ list.push(skill);
19
+ bySource.set(skill.source, list);
20
+ }
21
+ for (const [source, sourceSkills] of bySource) {
22
+ console.log(`\n ${source} (${sourceSkills.length} skills):`);
23
+ console.log(' ' + '-'.repeat(70));
24
+ for (const skill of sourceSkills) {
25
+ const name = skill.name.padEnd(28);
26
+ const pkg = (skill.package || '').padEnd(18);
27
+ const desc = skill.description.slice(0, 40);
28
+ console.log(` ${name} ${pkg} ${desc}`);
29
+ displaySkillCollisions(skill);
30
+ }
31
+ }
32
+ }
33
+ //# sourceMappingURL=cli-display.js.map
@@ -11,6 +11,7 @@
11
11
  * @implements #539
12
12
  */
13
13
  import { spawn } from 'child_process';
14
+ import { displaySkillsTable, displaySkillCollisions } from './cli-display.js';
14
15
  import { searchSkills, listSkills, getSkillInfo, installSkill, publishSkill, importSkillSource, getAllAdapters, } from './registry.js';
15
16
  import { AgentSkillImportError } from './importer.js';
16
17
  import { AgentSkillDeploymentError, deployImportedAgentSkill, uninstallImportedAgentSkill, } from './deployer.js';
@@ -50,32 +51,6 @@ function parseFlags(args) {
50
51
  }
51
52
  return { provider, target, rest };
52
53
  }
53
- /**
54
- * Format skill results as a table
55
- */
56
- function displaySkillsTable(skills) {
57
- if (skills.length === 0) {
58
- console.log(' No skills found.');
59
- return;
60
- }
61
- // Group by source
62
- const bySource = new Map();
63
- for (const skill of skills) {
64
- const list = bySource.get(skill.source) || [];
65
- list.push(skill);
66
- bySource.set(skill.source, list);
67
- }
68
- for (const [source, sourceSkills] of bySource) {
69
- console.log(`\n ${source} (${sourceSkills.length} skills):`);
70
- console.log(' ' + '-'.repeat(70));
71
- for (const skill of sourceSkills) {
72
- const name = skill.name.padEnd(28);
73
- const pkg = (skill.package || '').padEnd(18);
74
- const desc = skill.description.slice(0, 40);
75
- console.log(` ${name} ${pkg} ${desc}`);
76
- }
77
- }
78
- }
79
54
  /**
80
55
  * Handle 'skills search' command
81
56
  */
@@ -121,6 +96,7 @@ async function handleInfo(args) {
121
96
  if (details.version)
122
97
  console.log(`Version: ${details.version}`);
123
98
  console.log(`Description: ${details.description}`);
99
+ displaySkillCollisions(details);
124
100
  if (details.platforms && details.platforms.length > 0) {
125
101
  console.log(`Platforms: ${details.platforms.join(', ')}`);
126
102
  }
@@ -0,0 +1,84 @@
1
+ // Discover local skill owners and resolve name collisions without executing skills.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { parse } from 'yaml';
6
+ import { listProviderDefinitions } from '../providers/provider-definitions.js';
7
+ import { AGENT_SKILLS_BASELINE, AGENT_SKILL_COLLISION_PRECEDENCE, } from './agent-skills.js';
8
+ import { isManagedTarget } from './deployment-ownership.js';
9
+ export function localSkillRoots(options) {
10
+ const project = path.resolve(options.projectDir);
11
+ const home = path.resolve(options.homeDir ?? os.homedir());
12
+ const roots = new Map();
13
+ for (const { skillNamespace: ns } of listProviderDefinitions()) {
14
+ const base = ns.pathType === 'home-dir' ? home : project;
15
+ roots.set(path.resolve(base, ns.skillsBaseDir), ns.pathType === 'home-dir' ? 'user' : 'project');
16
+ }
17
+ roots.set(path.join(project, '.agents', 'skills'), 'project');
18
+ roots.set(path.join(project, '.claude', '.aiwg', 'skills'), 'project');
19
+ roots.set(path.join(home, '.claude', 'skills'), 'user');
20
+ roots.set(path.join(home, '.claude', 'skills', 'synced'), 'synced');
21
+ return roots;
22
+ }
23
+ export function discoverLocalSkillOwners(options) {
24
+ const skills = [];
25
+ for (const [root, origin] of localSkillRoots(options)) {
26
+ if (!fs.existsSync(root))
27
+ continue;
28
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
29
+ if (!entry.isDirectory())
30
+ continue;
31
+ const directory = path.join(root, entry.name);
32
+ const file = path.join(directory, 'SKILL.md');
33
+ if (!fs.existsSync(file))
34
+ continue;
35
+ try {
36
+ const content = fs.readFileSync(file, 'utf8');
37
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content);
38
+ const metadata = match ? parse(match[1]) : {};
39
+ const name = typeof metadata?.name === 'string' ? metadata.name : entry.name;
40
+ // Synced ownership is determined by its account cache root, never a marker.
41
+ const owner = origin !== 'synced' && isManagedTarget(directory, name)
42
+ ? 'aiwg-managed' : origin;
43
+ skills.push({
44
+ name, description: typeof metadata?.description === 'string' ? metadata.description : `Skill: ${name}`,
45
+ source: 'local', installed: true, origin: owner, path: file, content,
46
+ });
47
+ }
48
+ catch { /* Unreadable or malformed skills cannot be selected. */ }
49
+ }
50
+ }
51
+ return skills;
52
+ }
53
+ function rank(skill) {
54
+ return skill.origin ? AGENT_SKILL_COLLISION_PRECEDENCE[skill.origin] : 0;
55
+ }
56
+ export function skillCollisionDiagnostic(name, winner, loser, file) {
57
+ return {
58
+ code: 'AS_SKILL_COLLISION', severity: 'warning', file, yamlPath: '$.name',
59
+ message: `${winner}-owned skill "${name}" takes precedence over ${loser}-owned skill`,
60
+ upstreamBaseline: AGENT_SKILLS_BASELINE.revision,
61
+ remediation: 'Rename the skill or explicitly remove the higher-precedence collision.',
62
+ };
63
+ }
64
+ export function selectSkillOwners(skills) {
65
+ const selected = new Map();
66
+ // Path breaks equal-origin ties independently of filesystem enumeration order.
67
+ const sorted = [...skills].sort((a, b) => rank(b) - rank(a)
68
+ || (a.path ?? '').localeCompare(b.path ?? '') || a.name.localeCompare(b.name));
69
+ for (const skill of sorted) {
70
+ const winner = selected.get(skill.name);
71
+ if (!winner) {
72
+ selected.set(skill.name, { ...skill, diagnostics: [...(skill.diagnostics ?? [])] });
73
+ }
74
+ else if (winner.origin && skill.origin) {
75
+ winner.diagnostics.push(skillCollisionDiagnostic(skill.name, winner.origin, skill.origin, skill.path ?? ''));
76
+ winner.diagnostics.push(...(skill.diagnostics ?? []));
77
+ }
78
+ }
79
+ return [...selected.values()].sort((a, b) => a.name.localeCompare(b.name));
80
+ }
81
+ export function higherLocalSkillOwner(name, incoming, options) {
82
+ return selectSkillOwners(discoverLocalSkillOwners(options)).find(skill => skill.name === name && rank(skill) > AGENT_SKILL_COLLISION_PRECEDENCE[incoming]);
83
+ }
84
+ //# sourceMappingURL=collision-discovery.js.map