@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,91 @@
1
+ // Parse the corpus resolve arguments, emit per-reference results, and preserve semantic exit codes.
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { AiwgError } from '../../cli/errors.js';
5
+ import { createResolverClients, resolveReference } from './resolve.js';
6
+ export const RESOLVE_USAGE = 'aiwg corpus resolve "<title | URL | arXiv ID | DOI | bibliography line>" [--year YYYY] [--json]\naiwg corpus resolve --from-file refs.txt [--year YYYY] [--json]\nExit codes: 0 resolved, 2 ambiguous, 3 unresolved (batch: worst line), 1 usage error.\n';
7
+ function usage(message) {
8
+ throw new AiwgError({ code: 'ERR_CORPUS_RESOLVE_USAGE', message, exitCode: 1, hint: RESOLVE_USAGE.trim() });
9
+ }
10
+ function render(result) {
11
+ const lines = [`${result.line ? `Line ${result.line}: ` : ''}${result.status}: ${result.input}`];
12
+ for (const candidate of result.candidates)
13
+ lines.push(` ${candidate.score.toFixed(3)} ${candidate.paper.title} (${candidate.paper.id})`);
14
+ for (const finding of result.findings)
15
+ lines.push(` Finding ${finding.type}: supplied "${finding.supplied}"; returned "${finding.returned}"`);
16
+ for (const match of result.corpus_matches)
17
+ lines.push(` Already in corpus: ${match.ref} (${match.matched_by.join(', ')})`);
18
+ for (const path of result.paths_tried)
19
+ lines.push(` Tried ${path.source}/${path.method}: ${path.query} → ${path.status} (${path.returned.length})${path.error ? `: ${path.error}` : ''}`);
20
+ if (result.incomplete)
21
+ lines.push(` Incomplete${result.error ? `: ${result.error}` : ''}`);
22
+ return lines.join('\n') + '\n';
23
+ }
24
+ export async function resolveCli(args, root, cwd) {
25
+ if (args.includes('--help') || args.includes('-h')) {
26
+ process.stdout.write(RESOLVE_USAGE);
27
+ return;
28
+ }
29
+ let input;
30
+ let fromFile;
31
+ let year;
32
+ let json = false;
33
+ const seen = new Set();
34
+ for (let i = 0; i < args.length; i++) {
35
+ const arg = args[i];
36
+ if (arg.startsWith('--')) {
37
+ if (seen.has(arg))
38
+ usage(`${arg} may only be supplied once`);
39
+ seen.add(arg);
40
+ }
41
+ if (arg === '--json') {
42
+ json = true;
43
+ continue;
44
+ }
45
+ if (arg === '--year' || arg === '--from-file') {
46
+ const value = args[++i];
47
+ if (!value || value.startsWith('--'))
48
+ usage(`${arg} requires a value`);
49
+ if (arg === '--from-file') {
50
+ if (fromFile)
51
+ usage('--from-file may only be supplied once');
52
+ fromFile = value;
53
+ }
54
+ else {
55
+ if (year !== undefined || !/^(?:18|19|20|21)\d{2}$/.test(value))
56
+ usage('--year requires one year between 1800 and 2199');
57
+ year = Number(value);
58
+ }
59
+ }
60
+ else {
61
+ if (arg.startsWith('-'))
62
+ usage(`Unknown resolve option: ${arg}`);
63
+ if (input !== undefined)
64
+ usage('Supply one quoted reference');
65
+ input = arg;
66
+ }
67
+ }
68
+ if (input !== undefined && fromFile)
69
+ usage('A reference and --from-file are mutually exclusive');
70
+ if (!fromFile && !input?.trim())
71
+ usage('Supply a reference or --from-file');
72
+ const references = fromFile ? readFileSync(resolve(cwd, fromFile), 'utf8').split(/\r?\n/)
73
+ .flatMap((text, index) => text.trim() ? [{ input: text.trim(), line: index + 1 }] : []) : [{ input: input }];
74
+ const clients = createResolverClients();
75
+ const results = [];
76
+ for (const reference of references) {
77
+ try {
78
+ results.push({ ...await resolveReference(reference.input, root, year, clients), ...reference });
79
+ }
80
+ catch (error) {
81
+ results.push({ ...reference, reference: { input: reference.input }, status: 'unresolved', incomplete: true,
82
+ error: error instanceof Error ? error.message : String(error), candidates: [], findings: [], paths_tried: [],
83
+ already_in_corpus: false, corpus_matches: [] });
84
+ }
85
+ }
86
+ process.stdout.write(json ? JSON.stringify(fromFile ? results : results[0], null, 2) + '\n' : results.map(render).join('\n'));
87
+ const exitCode = results.reduce((worst, result) => Math.max(worst, { resolved: 0, ambiguous: 2, unresolved: 3 }[result.status]), 0);
88
+ if (exitCode)
89
+ throw new AiwgError({ code: 'ERR_CORPUS_RESOLVE_RESULT', message: 'Reference resolution requires review; see results', exitCode });
90
+ }
91
+ //# sourceMappingURL=resolve-cli.js.map
@@ -0,0 +1,41 @@
1
+ // Reuse the corpus readers to locate identities in reference and citation frontmatter.
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { loadCorpus, parseFrontmatter } from '../corpus-views/ref-parser.js';
5
+ import { identityKeys, parseResearchIdentifier } from '../../research/identity.js';
6
+ /** Build once for expansion; resolve retains the same ID/title matching contract. */
7
+ export function loadCorpusIdentities(root) {
8
+ return loadCorpus(root).records.map(record => {
9
+ const keys = new Set(identityKeys({ title: record.title }));
10
+ const fields = [];
11
+ let bodyArxiv;
12
+ for (const file of [record.path, join(root, 'documentation', 'citations', `${record.refId}-citations.md`)]) {
13
+ if (!existsSync(file))
14
+ continue;
15
+ const text = readFileSync(file, 'utf8');
16
+ const fm = parseFrontmatter(text);
17
+ fields.push(fm);
18
+ for (const key of identityKeys(fm))
19
+ keys.add(key);
20
+ for (const url of text.match(/https?:\/\/(?:export\.)?arxiv\.org\/(?:abs|pdf|html)\/[^\s<>\]\)]+/gi) ?? []) {
21
+ const id = parseResearchIdentifier(url);
22
+ if (id?.kind === 'arxiv') {
23
+ bodyArxiv ??= id.id;
24
+ break;
25
+ }
26
+ }
27
+ }
28
+ // Other body links may cite unheld papers; only a missing primary ID needs this fallback.
29
+ if (bodyArxiv && ![...keys].some(key => key.startsWith('arxivId:') || key.startsWith('doi:')))
30
+ keys.add(`arxivId:${bodyArxiv}`);
31
+ return { ref: record.refId, path: record.path, fields, keys };
32
+ });
33
+ }
34
+ export function findInCorpus(root, paper, index = loadCorpusIdentities(root)) {
35
+ const wanted = new Set(identityKeys(paper));
36
+ return index.flatMap(record => {
37
+ const matched = [...record.keys].filter(key => wanted.has(key)).map(key => key.slice(0, key.indexOf(':')));
38
+ return matched.length ? [{ ref: record.ref, matched_by: [...new Set(matched)] }] : [];
39
+ });
40
+ }
41
+ //# sourceMappingURL=resolve-corpus.js.map
@@ -0,0 +1,105 @@
1
+ // Resolve partial paper references through audited client attempts and conservative scoring.
2
+ import { ArxivClient } from '../../research/clients/arxiv.js';
3
+ import { CrossRefClient } from '../../research/clients/crossref.js';
4
+ import { SemanticScholarClient } from '../../research/clients/semantic-scholar.js';
5
+ import { normalizeIdentity, normalizeTitle } from '../../research/identity.js';
6
+ import { classifyCandidates, mergePapers, parsePartialReference, scorePaper } from '../../research/reference-match.js';
7
+ import { ResearchError, ResearchErrorCode } from '../../research/types.js';
8
+ import { findInCorpus } from './resolve-corpus.js';
9
+ export function createResolverClients() {
10
+ return { arxiv: new ArxivClient(), s2: new SemanticScholarClient(), crossref: new CrossRefClient() };
11
+ }
12
+ function canonicalPaper(paper) {
13
+ const identity = normalizeIdentity(paper);
14
+ return { ...paper, ...Object.fromEntries(Object.entries(identity).filter(([key, value]) => key !== 'title' && value !== undefined)) };
15
+ }
16
+ function s2Identifier(identifier) {
17
+ switch (identifier.kind) {
18
+ case 'arxiv': return `ARXIV:${identifier.id}`;
19
+ case 'doi': return `DOI:${identifier.id}`;
20
+ case 'acl': return `ACL:${identifier.id}`;
21
+ case 'openreview': return `URL:https://openreview.net/forum?id=${identifier.id}`;
22
+ case 's2': return identifier.id;
23
+ }
24
+ }
25
+ export async function resolveReference(input, root, year, clients = createResolverClients()) {
26
+ const reference = parsePartialReference(input, year);
27
+ const paths = [];
28
+ const findings = [];
29
+ const papers = [];
30
+ const verified = new Set();
31
+ const identifier = reference.identifier;
32
+ async function attempt(source, method, query, run, byId = false) {
33
+ try {
34
+ const returned = (await run()).slice(0, 5).map(canonicalPaper);
35
+ if (returned.some(paper => !paper.id || !normalizeTitle(paper.title))) {
36
+ throw new ResearchError(ResearchErrorCode.RF_301, 'Response lacks a paper identity or title');
37
+ }
38
+ paths.push({ source, method, query, status: returned.length ? 'returned' : 'empty', returned });
39
+ for (const paper of returned) {
40
+ if (byId && identifier) {
41
+ const key = { arxiv: 'arxivId', doi: 'doi', acl: 'aclId', openreview: 'openReviewId', s2: 's2PaperId' }[identifier.kind];
42
+ const actual = paper[key];
43
+ if (actual && identifier.kind !== 's2' && String(actual).toLowerCase() !== identifier.id.toLowerCase()) {
44
+ findings.push({ type: 'identifier_mismatch', supplied: identifier.id, returned: String(actual), candidate: paper.id });
45
+ continue;
46
+ }
47
+ if (identifier.kind === 's2' && !identifier.id.startsWith('CorpusId:') && paper.s2PaperId?.toLowerCase() !== identifier.id.toLowerCase()) {
48
+ findings.push({ type: 'identifier_mismatch', supplied: identifier.id, returned: paper.s2PaperId ?? paper.id, candidate: paper.id });
49
+ continue;
50
+ }
51
+ // A direct lookup establishes the requested ID when the API omits that externalId.
52
+ if (identifier.kind !== 's2')
53
+ Object.assign(paper, { [key]: identifier.id });
54
+ verified.add(paper.id);
55
+ }
56
+ papers.push(paper);
57
+ }
58
+ }
59
+ catch (error) {
60
+ const missing = error instanceof ResearchError && error.code === ResearchErrorCode.RF_300;
61
+ paths.push({ source, method, query, status: missing ? 'empty' : 'error', returned: [],
62
+ ...(missing ? {} : { error: error instanceof Error ? error.message : String(error) }) });
63
+ }
64
+ }
65
+ if (identifier) {
66
+ if (identifier.kind === 'arxiv') {
67
+ await attempt('arxiv', 'id', identifier.id, async () => [await clients.arxiv.getPaperById(identifier.id)], true);
68
+ }
69
+ else if (identifier.kind === 'doi') {
70
+ await attempt('crossref', 'id', identifier.id, async () => [await clients.crossref.getPaperByDoi(identifier.id)], true);
71
+ }
72
+ const id = s2Identifier(identifier);
73
+ await attempt('semantic-scholar', 'id', id, async () => [await clients.s2.getPaperById(id)], true);
74
+ }
75
+ const identifierUnresolved = Boolean(identifier && verified.size === 0);
76
+ if (identifierUnresolved && identifier) {
77
+ const idPaths = paths.filter(path => path.method === 'id');
78
+ findings.push({ type: 'identifier_unresolved', supplied: identifier.id, paths: idPaths,
79
+ returned: idPaths.map(path => {
80
+ const detail = path.error ?? path.returned.map(paper => JSON.stringify(normalizeIdentity(paper))).join(', ');
81
+ const outcome = path.returned.length ? 'returned (identifier mismatch)' : path.status;
82
+ return `${path.source}/${path.method} (${path.query}): ${outcome}${detail ? `: ${detail}` : ''}`;
83
+ }).join('; ') });
84
+ }
85
+ if (reference.title && (!identifier || papers.length === 0)) {
86
+ await attempt('semantic-scholar', 'title-match', reference.title, () => clients.s2.matchTitle(reference.title));
87
+ const query = `ti:"${normalizeTitle(reference.title)}"`;
88
+ await attempt('arxiv', 'title', query, async () => (await clients.arxiv.search(query, { limit: 5 })).papers);
89
+ await attempt('crossref', 'bibliographic', input, async () => (await clients.crossref.searchBibliographic(input, { limit: 5 })).papers);
90
+ }
91
+ const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, verified.has(paper.id)))
92
+ .sort((a, b) => b.score - a.score || a.paper.id.localeCompare(b.paper.id)).slice(0, 5);
93
+ for (const candidate of candidates) {
94
+ if (reference.title && normalizeTitle(reference.title) !== normalizeTitle(candidate.paper.title)) {
95
+ findings.push({ type: 'title_mismatch', supplied: reference.title, returned: candidate.paper.title, candidate: candidate.paper.id });
96
+ }
97
+ }
98
+ const classified = classifyCandidates(candidates);
99
+ const status = identifierUnresolved && classified === 'resolved' ? 'ambiguous' : classified;
100
+ const paper = status === 'resolved' ? candidates[0].paper : undefined;
101
+ const corpusMatches = paper ? findInCorpus(root, paper) : [];
102
+ return { input, reference, status, incomplete: paths.some(path => path.status === 'error'), candidates,
103
+ ...(paper ? { paper } : {}), findings, paths_tried: paths, already_in_corpus: corpusMatches.length > 0, corpus_matches: corpusMatches };
104
+ }
105
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,40 @@
1
+ // Validate public doctor flags before routing early-return modes.
2
+ import { argsTerminatorIndex, hasPositionalOrSwitch, requireFlagValue, valueTokenIndexes } from '../flag-parsing.js';
3
+ export function parsePublicDoctorFlags(args) {
4
+ const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli', '--forget-approval'];
5
+ const knownFlags = new Set([
6
+ ...valueFlags, '--list-approvals', '--all-providers', '--probe-workers', '--qualify', '--yes', '--dry-run', '--no-budget-check', '--strict-context', '--json',
7
+ '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
8
+ ]);
9
+ const hasSwitch = (name) => hasPositionalOrSwitch(args, name, valueFlags);
10
+ const values = new Map();
11
+ for (const flag of valueFlags) {
12
+ values.set(flag, requireFlagValue(args, { rejectEmpty: true, precedence: 'last' }, flag));
13
+ }
14
+ const consumed = valueTokenIndexes(args, valueFlags);
15
+ for (let i = 0; i < argsTerminatorIndex(args); i += 1) {
16
+ const token = args[i];
17
+ if (consumed.has(i) || !token.startsWith('-'))
18
+ continue;
19
+ const name = token.split('=')[0];
20
+ if (!knownFlags.has(name) || (token.includes('=') && !valueFlags.includes(name))) {
21
+ throw new Error(`Unknown flag: ${name}`);
22
+ }
23
+ }
24
+ if (hasSwitch('--decision-offload') && (hasSwitch('--probe-workers') || hasSwitch('--deployment') || hasSwitch('--user') || values.get('--scope') !== undefined)) {
25
+ throw new Error('--decision-offload is a separate offline mode; do not combine it with worker, deployment or user-scope checks');
26
+ }
27
+ if (['--list-approvals', '--forget-approval', '--qualify', '--cli', '--yes', '--dry-run'].some(flag => hasSwitch(flag) || values.get(flag)) && !hasSwitch('--probe-workers')) {
28
+ throw new Error('--list-approvals, --forget-approval, --qualify, --cli, --yes and --dry-run require --probe-workers');
29
+ }
30
+ if ((hasSwitch('--list-approvals') || values.get('--forget-approval')) && ((hasSwitch('--list-approvals') && values.get('--forget-approval')) || ['--qualify', '--dry-run', '--decision-offload', '--deployment', '--user'].some(hasSwitch) || values.get('--scope') !== undefined)) {
31
+ throw new Error('Approval management must run separately from other doctor modes');
32
+ }
33
+ if (values.get('--forget-approval') && !hasSwitch('--yes'))
34
+ throw new Error('--forget-approval requires --yes');
35
+ if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload')) {
36
+ throw new Error('--json requires --probe-workers or --deployment or --decision-offload');
37
+ }
38
+ return { hasSwitch, values };
39
+ }
40
+ //# sourceMappingURL=doctor-args.js.map
@@ -13,9 +13,11 @@ Options:
13
13
  --scope <scope> Verification scope: project or user
14
14
  --user Alias for --scope user
15
15
  --qualify With --probe-workers, record installation and configured model/role approval
16
- --yes Confirm worker qualification without a terminal
16
+ --list-approvals With --probe-workers, list recorded approvals offline (supports --json)
17
+ --forget-approval PATH With --probe-workers --yes, remove approvals for this workspace
18
+ --yes Confirm worker qualification or approval removal
17
19
  --dry-run With --probe-workers, preview qualification without writes
18
- --cli NAME Limit worker probes/qualification to one configured CLI
20
+ --cli NAME Limit worker probes, qualification, or approvals to one CLI
19
21
  --decision-offload Show offline advisory decision readiness and adoption report
20
22
  --probe-workers Run bounded worker CLI version probes (default: config-only, no subprocess)
21
23
  --project-local Include project-local artifact diagnostics
@@ -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