@aiwg/cli 2026.10.12 → 2026.10.15

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 (104) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +44 -1
  4. package/dist/src/artifacts/corpus-tools/cli.js +32 -0
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +1 -1
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +89 -0
  7. package/dist/src/artifacts/corpus-tools/expand-queue.js +38 -0
  8. package/dist/src/artifacts/corpus-tools/expand-state.js +40 -0
  9. package/dist/src/artifacts/corpus-tools/expand.js +125 -0
  10. package/dist/src/artifacts/corpus-tools/resolve-cli.js +91 -0
  11. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  12. package/dist/src/artifacts/corpus-tools/resolve.js +105 -0
  13. package/dist/src/cli/handlers/doctor-args.js +40 -0
  14. package/dist/src/cli/handlers/doctor-help.js +4 -2
  15. package/dist/src/cli/handlers/use-bundle-counts.js +32 -6
  16. package/dist/src/cli/handlers/use-skill-assets.js +207 -0
  17. package/dist/src/cli/handlers/use.js +30 -193
  18. package/dist/src/cli/handlers/utilities.js +5 -31
  19. package/dist/src/config/authorization-cli.js +11 -3
  20. package/dist/src/config/worker-context.js +33 -4
  21. package/dist/src/decision/context-pruning-common.js +41 -0
  22. package/dist/src/decision/context-pruning-evaluation.js +366 -0
  23. package/dist/src/decision/context-pruning-pilot.js +431 -0
  24. package/dist/src/decision/context-pruning-types.js +19 -0
  25. package/dist/src/decision/context-pruning.js +5 -847
  26. package/dist/src/decision/ensemble/contract.js +4 -24
  27. package/dist/src/decision/heldout/collector.js +1 -1
  28. package/dist/src/decision/qualification/release.js +5 -62
  29. package/dist/src/extensions/manifest.js +8 -1
  30. package/dist/src/extensions/project-local-doctor.js +78 -2
  31. package/dist/src/extensions/validation.js +10 -11
  32. package/dist/src/features/catalog.js +1 -1
  33. package/dist/src/gates/evaluate.js +5 -15
  34. package/dist/src/gates/heldout.js +42 -0
  35. package/dist/src/gates/index.js +2 -1
  36. package/dist/src/gates/upstream-ceiling.js +111 -0
  37. package/dist/src/models/provider-models.js +5 -8
  38. package/dist/src/models/worker-installation-store.mjs +228 -0
  39. package/dist/src/models/worker-installation.mjs +7 -162
  40. package/dist/src/models/wrapper-definitions.js +14 -0
  41. package/dist/src/models/wrapper-deployment.js +48 -25
  42. package/dist/src/models/wrapper-enforcement.js +72 -0
  43. package/dist/src/policy/hitl-check.js +80 -0
  44. package/dist/src/providers/provider-definitions.js +10 -10
  45. package/dist/src/research/clients/arxiv.js +10 -4
  46. package/dist/src/research/clients/base.js +5 -4
  47. package/dist/src/research/clients/crossref.js +9 -1
  48. package/dist/src/research/clients/semantic-scholar.js +73 -44
  49. package/dist/src/research/identity.js +85 -0
  50. package/dist/src/research/index.js +1 -0
  51. package/dist/src/research/reference-match.js +89 -0
  52. package/dist/src/rules/activation.d.mts +2 -0
  53. package/dist/src/rules/activation.mjs +23 -0
  54. package/dist/src/rules/core-startup.d.mts +2 -0
  55. package/dist/src/rules/core-startup.mjs +31 -0
  56. package/dist/src/skills/adapters/local.js +32 -9
  57. package/dist/src/skills/agent-skills.js +2 -0
  58. package/dist/src/skills/cli-display.js +33 -0
  59. package/dist/src/skills/cli.js +2 -26
  60. package/dist/src/skills/collision-discovery.js +84 -0
  61. package/dist/src/skills/deployer.js +20 -75
  62. package/dist/src/skills/deployment-ownership.js +74 -0
  63. package/dist/src/skills/doctor.js +2 -2
  64. package/dist/src/skills/importer.js +4 -26
  65. package/dist/src/skills/registry.js +22 -7
  66. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  67. package/dist/src/smiths/context-pipeline/aiwg-md.js +3 -0
  68. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  69. package/dist/src/smiths/context-pipeline/generator.js +40 -104
  70. package/dist/src/smiths/context-pipeline/managed-hook.js +10 -0
  71. package/dist/src/smiths/context-pipeline/parallelism-section.js +7 -3
  72. package/package.json +6 -2
  73. package/tools/agents/deploy-agents.mjs +2 -123
  74. package/tools/agents/providers/antigravity.mjs +4 -6
  75. package/tools/agents/providers/base.mjs +3 -3
  76. package/tools/agents/providers/claude.mjs +3 -5
  77. package/tools/agents/providers/codex.mjs +3 -5
  78. package/tools/agents/providers/context-write.mjs +12 -0
  79. package/tools/agents/providers/copilot.mjs +3 -5
  80. package/tools/agents/providers/cursor.mjs +3 -5
  81. package/tools/agents/providers/factory.mjs +3 -5
  82. package/tools/agents/providers/grok-build.mjs +17 -12
  83. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  84. package/tools/agents/providers/hermes-startup.mjs +209 -0
  85. package/tools/agents/providers/hermes.mjs +9 -359
  86. package/tools/agents/providers/model-wrapper.mjs +90 -0
  87. package/tools/agents/providers/muse.mjs +3 -3
  88. package/tools/agents/providers/omp.mjs +3 -1
  89. package/tools/agents/providers/openclaw.mjs +3 -5
  90. package/tools/agents/providers/opencode.mjs +3 -5
  91. package/tools/agents/providers/pi.mjs +1 -1
  92. package/tools/agents/providers/provider-paths-staging.mjs +9 -0
  93. package/tools/agents/providers/rule-delivery.mjs +26 -228
  94. package/tools/agents/providers/rule-presentation.mjs +13 -4
  95. package/tools/agents/providers/rule-projection.mjs +119 -0
  96. package/tools/agents/providers/rule-startup.mjs +70 -0
  97. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  98. package/tools/agents/providers/warp.mjs +5 -7
  99. package/tools/agents/providers/windsurf.mjs +14 -62
  100. package/tools/plugin/package-plugins.mjs +2 -2
  101. package/tools/plugin/plugin-links.mjs +3 -0
  102. package/tools/skills/codex-skill-transform.mjs +232 -0
  103. package/tools/skills/deploy-skills-codex.mjs +8 -249
  104. package/tools/warp/warp-content.mjs +548 -0
@@ -0,0 +1,89 @@
1
+ // Parse partial citations and score distinct candidate identities without choosing close matches.
2
+ import { normalizeIdentity, normalizeTitle, parseResearchIdentifier } from './identity.js';
3
+ /** Common quoted, APA-style and title-plus-year citations; retain the untouched input. */
4
+ export function parsePartialReference(input, year) {
5
+ const identifier = parseResearchIdentifier(input);
6
+ let rest = identifier ? input.replace(identifier.matched, '') : input;
7
+ rest = rest.replace(/^\s*\[\d+\]\s*/, '').trim();
8
+ const quoted = rest.match(/["“]([^"”]+)["”]/);
9
+ const apa = rest.match(/^(.+?)\s*\(((?:18|19|20|21)\d{2})\)\.?\s+(.+)$/);
10
+ const authorYear = rest.match(/^(.+?(?:et al\.|,\s*[A-Z]\.))\s*((?:18|19|20|21)\d{2})\.?\s+(.+)$/);
11
+ const bibliography = apa ?? authorYear;
12
+ // A number inside a title is not publication metadata; require citation cues.
13
+ const date = (quoted ? rest.replace(quoted[0], '') : rest).match(/\(((?:18|19|20|21)\d{2})\)/);
14
+ const inferredYear = bibliography?.[2] ?? date?.[1];
15
+ const firstAuthor = bibliography?.[1].split(/,|\s+et al\.|\s+and\s+|\s+&\s+/)[0].trim();
16
+ if (quoted)
17
+ rest = quoted[1];
18
+ else if (bibliography)
19
+ rest = bibliography[3].split(/\.\s+/)[0];
20
+ else if (date)
21
+ rest = rest.replace(date[0], '');
22
+ rest = rest.replace(/^[\s.,;:()[\]{}"']+|[\s.,;:()[\]{}"']+$/g, '').trim();
23
+ return { input, identifier, title: normalizeTitle(rest) ? rest : undefined, year: year ?? (inferredYear ? Number(inferredYear) : undefined), firstAuthor };
24
+ }
25
+ /** Jaccard token-set similarity avoids substring matches scoring as exact titles. */
26
+ export function titleSimilarity(left, right) {
27
+ const a = new Set(normalizeTitle(left).split(' ').filter(Boolean));
28
+ const b = new Set(normalizeTitle(right).split(' ').filter(Boolean));
29
+ const union = new Set([...a, ...b]).size;
30
+ return union ? [...a].filter(token => b.has(token)).length / union : 0;
31
+ }
32
+ function surname(name) {
33
+ return normalizeTitle(name.includes(',') ? name.split(',')[0] : name.trim().split(/\s+/).at(-1) ?? '');
34
+ }
35
+ /** Title weight .9; supplied year and first author each add .05, then renormalize. */
36
+ export function scorePaper(reference, paper, verifiedId = false) {
37
+ const title = reference.title ? titleSimilarity(reference.title, paper.title) : (verifiedId ? 1 : 0);
38
+ const parts = { title };
39
+ let sum = 0.9 * title;
40
+ let weight = 0.9;
41
+ if (reference.year !== undefined) {
42
+ parts.year = paper.year === reference.year ? 1 : 0;
43
+ sum += 0.05 * parts.year;
44
+ weight += 0.05;
45
+ }
46
+ if (reference.firstAuthor) {
47
+ parts.first_author = surname(reference.firstAuthor) === surname(paper.authors[0]?.name ?? '') ? 1 : 0;
48
+ sum += 0.05 * parts.first_author;
49
+ weight += 0.05;
50
+ }
51
+ if (verifiedId)
52
+ parts.identifier = 1;
53
+ return { paper, score: sum / weight, score_parts: parts };
54
+ }
55
+ /** Apply inclusive approved boundaries; epsilon only compensates floating-point subtraction. */
56
+ export function classifyCandidates(candidates) {
57
+ const best = candidates[0]?.score ?? 0;
58
+ if (best + 1e-12 < 0.6)
59
+ return 'unresolved';
60
+ const margin = best - (candidates[1]?.score ?? 0);
61
+ return best + 1e-12 >= 0.92 && margin + 1e-12 >= 0.05 ? 'resolved' : 'ambiguous';
62
+ }
63
+ /** Merge only corroborated identifiers; title equality alone does not establish identity. */
64
+ export function mergePapers(papers) {
65
+ const merged = [];
66
+ for (const paper of papers) {
67
+ const identity = normalizeIdentity(paper);
68
+ const previous = merged.find(existing => {
69
+ const other = normalizeIdentity(existing);
70
+ const ids = ['arxivId', 'doi', 's2PaperId', 'openReviewId', 'aclId'];
71
+ if (ids.some(key => identity[key] && other[key] && identity[key] !== other[key]))
72
+ return false;
73
+ return ids.some(key => identity[key] && identity[key] === other[key]);
74
+ });
75
+ if (!previous) {
76
+ merged.push({ ...paper });
77
+ continue;
78
+ }
79
+ // Source order determines metadata precedence; later sources only fill missing fields.
80
+ for (const [key, value] of Object.entries(paper)) {
81
+ if (value !== undefined && (!previous[key] ||
82
+ (Array.isArray(previous[key]) && previous[key].length === 0))) {
83
+ previous[key] = value;
84
+ }
85
+ }
86
+ }
87
+ return merged;
88
+ }
89
+ //# sourceMappingURL=reference-match.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/, '');
@@ -0,0 +1,2 @@
1
+ export function renderCoreStartup(rules: Array<{ name: string; coreBody?: string }>): string;
2
+ export function ensureCoreStartup(content: string): string;
@@ -0,0 +1,31 @@
1
+ /** Share compact core rendering between provider deployment and fresh regeneration. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { findPackageRoot } from '../cli/find-package-root.js';
6
+ import { parseRuleFrontmatter, readCoreBody, validateCoreSet } from './activation.mjs';
7
+
8
+ export function renderCoreStartup(rules) {
9
+ const cores = [...new Map(rules.filter(rule => rule.coreBody !== undefined).map(rule => [rule.name, rule])).values()];
10
+ const errors = validateCoreSet(cores.map(rule => ({ name: rule.name, text: rule.coreBody })));
11
+ if (errors.length) throw new Error(errors.join('; '));
12
+ return cores.length ? `<!-- AIWG:rule-core:start -->\n## Core rules\n\n${cores.map(rule => rule.coreBody).join('\n\n')}\n<!-- AIWG:rule-core:end -->\n` : '';
13
+ }
14
+
15
+ export function ensureCoreStartup(content) {
16
+ // Deployment has already selected and validated the project's core set.
17
+ if (content.includes('<!-- AIWG:rule-core:start -->')) return content;
18
+ const root = findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
19
+ if (!root) throw new Error('AIWG package unavailable; run aiwg use before regenerating context.');
20
+ const dir = path.join(root, 'agentic/code/addons/aiwg-utils/rules');
21
+ if (!fs.existsSync(dir)) throw new Error('Core rule sources unavailable; run aiwg use before regenerating context.');
22
+ const rules = fs.readdirSync(dir).filter(name => name.endsWith('.md') && !name.endsWith('.core.md')).flatMap(name => {
23
+ const file = path.join(dir, name);
24
+ const parsed = parseRuleFrontmatter(fs.readFileSync(file, 'utf8'));
25
+ if (!parsed.valid) throw new Error(`Invalid core rule source ${file}; run aiwg use after repairing it.`);
26
+ return parsed.rule.activation === 'core' ? [{ name: parsed.data.name || path.basename(file, '.md'), coreBody: readCoreBody(file) }] : [];
27
+ });
28
+ const block = renderCoreStartup(rules);
29
+ if (!block) throw new Error('No core rule sources found; run aiwg use before regenerating context.');
30
+ return `${content}${content.endsWith('\n') ? '\n' : '\n\n'}${block}`;
31
+ }
@@ -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
@@ -9,60 +9,13 @@
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { randomUUID } from 'node:crypto';
12
- import { normalizeProviderDefinitionId } from '../providers/provider-definitions.js';
13
- import { AGENT_SKILLS_SIDECAR_SCHEMA } from './agent-skills.js';
14
12
  import { getImportedAgentSkill } from './importer.js';
13
+ import { higherLocalSkillOwner, skillCollisionDiagnostic } from './collision-discovery.js';
14
+ import { isManagedTarget, readDeploymentSidecar, providersShareProjectionSurface } from './deployment-ownership.js';
15
15
  import { resolvePolicy } from './deployment-policy.js';
16
16
  import { projectionDocument, providerSkillBytes, sidecarBytes } from './deployment-projection.js';
17
17
  import { AGENT_SKILL_MANAGED_MARKER, AGENT_SKILL_DEPLOYMENT_SIDECAR, MARKER_CONTENT, assertPortableName, fail, } from './deployment-types.js';
18
18
  export { AGENT_SKILL_MANAGED_MARKER, AGENT_SKILL_DEPLOYMENT_SIDECAR, AgentSkillDeploymentError, } from './deployment-types.js';
19
- function readDeploymentSidecar(targetPath, expectedName, expectedProvider) {
20
- try {
21
- const sidecarPath = path.join(targetPath, AGENT_SKILL_DEPLOYMENT_SIDECAR);
22
- const stat = fs.lstatSync(sidecarPath);
23
- if (!stat.isFile() || stat.isSymbolicLink())
24
- return undefined;
25
- const value = JSON.parse(fs.readFileSync(sidecarPath, 'utf8'));
26
- if (value.schemaVersion !== 1
27
- || value.kind !== 'aiwg-managed-agent-skill-projection'
28
- || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.name)
29
- || !normalizeProviderDefinitionId(value.provider)
30
- || !/^[0-9a-f]{64}$/.test(value.sourceDigest)
31
- || !['native', 'projected', 'degraded', 'unsupported'].includes(value.projectionStatus)
32
- || !Array.isArray(value.reasons)
33
- || !value.reasons.every((item) => typeof item === 'string')
34
- || !Array.isArray(value.warnings)
35
- || !value.warnings.every((item) => typeof item === 'string')
36
- || value.portable?.$schema !== AGENT_SKILLS_SIDECAR_SCHEMA
37
- || value.portable.schemaVersion !== 1
38
- || typeof value.portable.aiwg !== 'object'
39
- || value.portable.aiwg === null
40
- || Array.isArray(value.portable.aiwg)
41
- || value.portable.provenance?.sourceDigest !== value.sourceDigest
42
- || !['strict', 'compatible', 'discovery'].includes(value.portable.validationProfile)
43
- || !['untrusted', 'trusted', 'revoked'].includes(value.portable.trust?.state)
44
- || !['inactive', 'active', 'blocked'].includes(value.portable.trust?.activation)
45
- || (expectedName !== undefined && value.name !== expectedName)
46
- || (expectedProvider !== undefined && value.provider !== expectedProvider)
47
- || path.basename(targetPath) !== value.name) {
48
- return undefined;
49
- }
50
- return value;
51
- }
52
- catch {
53
- return undefined;
54
- }
55
- }
56
- /**
57
- * Codex, Antigravity, DeepSeek Harness, and Muse intentionally consume the
58
- * same portable project skill surface (<repo>/.agents/skills). A projection
59
- * written for any member is managed ownership for the others when the
60
- * desired payload is otherwise byte-identical.
61
- */
62
- function providersShareProjectionSurface(actual, expected) {
63
- const shared = new Set(['antigravity', 'codex', 'deepseek-harness', 'muse']);
64
- return actual === expected || (shared.has(actual) && shared.has(expected));
65
- }
66
19
  function buildProjectionPlan(record, options) {
67
20
  const policy = resolvePolicy(options.target, options);
68
21
  const targetPath = path.join(policy.root, record.name);
@@ -74,6 +27,14 @@ function buildProjectionPlan(record, options) {
74
27
  desiredEntries: [],
75
28
  };
76
29
  }
30
+ const collision = higherLocalSkillOwner(record.name, 'imported', options);
31
+ if (collision?.origin) {
32
+ const diagnostic = skillCollisionDiagnostic(record.name, collision.origin, 'imported', collision.path ?? '');
33
+ policy.status = 'degraded';
34
+ policy.reasons.push(diagnostic.message);
35
+ policy.warnings.push(`Existing ${collision.origin}-owned files were not modified: ${collision.path}`);
36
+ return { blocked: true, policy, targetPath, sourceDigest: record.digest, desiredEntries: [] };
37
+ }
77
38
  const { document, sourceEntries } = projectionDocument(record);
78
39
  const original = sourceEntries.find((entry) => (entry.kind === 'file' && entry.relativePath === 'SKILL.md'));
79
40
  const skillBytes = providerSkillBytes(record, policy, document, original?.bytes);
@@ -108,26 +69,6 @@ function buildProjectionPlan(record, options) {
108
69
  desiredEntries,
109
70
  };
110
71
  }
111
- function isManagedTarget(targetPath, expectedName, expectedProvider) {
112
- if (!fs.existsSync(targetPath))
113
- return false;
114
- try {
115
- const targetStat = fs.lstatSync(targetPath);
116
- const marker = path.join(targetPath, AGENT_SKILL_MANAGED_MARKER);
117
- const sidecar = readDeploymentSidecar(targetPath, expectedName);
118
- return (targetStat.isDirectory()
119
- && !targetStat.isSymbolicLink()
120
- && fs.lstatSync(marker).isFile()
121
- && !fs.lstatSync(marker).isSymbolicLink()
122
- && fs.readFileSync(marker, 'utf8') === MARKER_CONTENT
123
- && sidecar !== undefined
124
- && (expectedProvider === undefined
125
- || providersShareProjectionSurface(sidecar.provider, expectedProvider)));
126
- }
127
- catch {
128
- return false;
129
- }
130
- }
131
72
  function targetMatches(targetPath, desired, name, provider) {
132
73
  if (!isManagedTarget(targetPath, name, provider))
133
74
  return false;
@@ -196,6 +137,9 @@ function promoteAtomically(name, plan) {
196
137
  const existed = fs.existsSync(plan.targetPath);
197
138
  try {
198
139
  writeDesiredTree(staging, plan.desiredEntries);
140
+ if (!existed && fs.existsSync(plan.targetPath)) {
141
+ fail('AS_DEPLOY_COLLISION_RACE', 'project/user-owned target appeared before imported-owned skill promotion');
142
+ }
199
143
  if (existed) {
200
144
  if (!isManagedTarget(plan.targetPath, name, plan.policy.provider)) {
201
145
  fail('AS_DEPLOY_COLLISION_RACE', 'deployment target ownership changed before atomic promotion');
@@ -206,11 +150,11 @@ function promoteAtomically(name, plan) {
206
150
  fs.renameSync(staging, plan.targetPath);
207
151
  }
208
152
  catch (error) {
209
- if (fs.existsSync(plan.targetPath)) {
210
- fs.rmSync(plan.targetPath, { recursive: true, force: true });
211
- }
212
- if (fs.existsSync(backup))
153
+ // A failed rename did not install our tree. A newly appeared target is
154
+ // operator-owned; retain it and the backup rather than deleting either.
155
+ if (fs.existsSync(backup) && !fs.existsSync(plan.targetPath)) {
213
156
  fs.renameSync(backup, plan.targetPath);
157
+ }
214
158
  throw error;
215
159
  }
216
160
  if (fs.existsSync(backup)) {
@@ -268,13 +212,13 @@ export function deployImportedAgentSkill(name, options) {
268
212
  const record = requireDeployableImport(name, projectDir);
269
213
  const plan = buildProjectionPlan(record, { ...options, projectDir });
270
214
  const dryRun = options.dryRun ?? false;
271
- if (!plan.policy.supported) {
215
+ if (!plan.policy.supported || plan.blocked) {
272
216
  return result('deploy', 'blocked', dryRun, name, plan);
273
217
  }
274
218
  if (fs.existsSync(plan.targetPath)
275
219
  && !isManagedTarget(plan.targetPath, name, plan.policy.provider)) {
276
220
  plan.policy.status = 'degraded';
277
- plan.policy.reasons.push('target collision is not owned by AIWG');
221
+ plan.policy.reasons.push('target collision is not owned by AIWG: project/user-owned target blocks imported-owned skill');
278
222
  plan.policy.warnings.push('the existing user-owned target was not modified');
279
223
  return result('deploy', 'blocked', dryRun, name, plan);
280
224
  }
@@ -334,6 +278,7 @@ export function inspectImportedAgentSkillProjection(name, options) {
334
278
  exists,
335
279
  managed,
336
280
  matches: (plan.policy.supported
281
+ && !plan.blocked
337
282
  && managed
338
283
  && targetMatches(plan.targetPath, plan.desiredEntries, name, plan.policy.provider)),
339
284
  reasons: [...plan.policy.reasons],