@aiwg/cli 2026.10.16 → 2026.10.18

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 (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -0,0 +1,13 @@
1
+ export function shellRefusalDiagnostics(plan) {
2
+ const seen = new Set();
3
+ return [...plan.diagnostics, ...plan.exclusions.flatMap(row => row.diagnostics)].filter(diagnostic => {
4
+ if (diagnostic.blocking === false)
5
+ return false;
6
+ const key = JSON.stringify(diagnostic);
7
+ if (seen.has(key))
8
+ return false;
9
+ seen.add(key);
10
+ return true;
11
+ });
12
+ }
13
+ //# sourceMappingURL=models-refusal.js.map
@@ -1,4 +1,5 @@
1
1
  import { MODELS_HELP } from './models-help.js';
2
+ import { shellRefusalDiagnostics } from './models-refusal.js';
2
3
  import { updateJson } from '../../models/config-writer.js';
3
4
  import { atomicConfigWrite as atomicWrite } from '../../config/worker-write.js';
4
5
  import { handleWorkerAdoptionArgs } from '../../config/worker-adoption-cli.js';
@@ -128,7 +129,7 @@ async function resolveDirect(ctx, services) {
128
129
  const plan = await resolveWorkerInvocation(snapshot, request, drivers, services.now?.());
129
130
  const runnable = plan.invocation?.readiness === 'launchable';
130
131
  if (shell && !runnable)
131
- console.error(JSON.stringify({ status: 'blocked', diagnostics: plan.diagnostics }, null, 2));
132
+ console.error(JSON.stringify({ status: 'blocked', diagnostics: shellRefusalDiagnostics(plan) }, null, 2));
132
133
  else if (shell && plan.invocation?.transport === 'shell')
133
134
  print(plan.invocation.shellCommand, false);
134
135
  else
@@ -0,0 +1,133 @@
1
+ // Remove bundled provider files and reconcile their existing config atomically.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { writeAiwgConfig } from '../../config/aiwg-config.js';
5
+ import { resolveProjectAiwgDir } from '../../config/project-artifacts.js';
6
+ import { removeClaudeAttribution } from '../../extensions/claude-hooks-installer.js';
7
+ import { planDeploymentRemoval } from '../../providers/deployment-removal.js';
8
+ import { applyRemovalTransaction } from '../../providers/removal-transaction.js';
9
+ function counts(decisions) {
10
+ const result = { agents: 0, commands: 0, skills: 0, rules: 0 };
11
+ for (const item of decisions) {
12
+ if (!item.owned)
13
+ continue;
14
+ if (item.kind === 'agent')
15
+ result.agents++;
16
+ if (item.kind === 'command' || item.kind === 'skill-command')
17
+ result.commands++;
18
+ if (item.kind === 'rule')
19
+ result.rules++;
20
+ if (path.basename(item.path) === 'SKILL.md')
21
+ result.skills++;
22
+ }
23
+ return result;
24
+ }
25
+ const summary = (value) => `${value.agents} agents, ${value.commands} commands, ${value.rules} rules, ${value.skills} skills`;
26
+ export async function removeBundledDeployment(project, id, owner, config, providers, opts) {
27
+ const entry = config.installed[id];
28
+ const configBefore = JSON.stringify(config);
29
+ let writeConfig = false;
30
+ const lines = [], writes = new Map();
31
+ let removed = 0, modern = false;
32
+ try {
33
+ for (const provider of providers) {
34
+ const plan = planDeploymentRemoval(project, provider, owner, providers.length === Object.keys(entry.deployedTo).length);
35
+ modern ||= !plan.legacy;
36
+ lines.push(` Provider ${provider}:`);
37
+ lines.push(` Receipt inventory: ${summary(counts(plan.decisions))}; ${plan.recorded.length} owned file record(s).`);
38
+ lines.push(` aiwg.config deployedTo: ${summary(entry.deployedTo[provider])}.`);
39
+ const inventory = counts(plan.decisions);
40
+ if (Object.entries(inventory).some(([kind, value]) => value !== entry.deployedTo[provider][kind])) {
41
+ lines.push(' Count discrepancy: deployedTo is a historical provider snapshot; receipts alone determine ownership and deletions.');
42
+ }
43
+ for (const item of plan.decisions) {
44
+ const verb = opts.dryRun ? `Would ${item.action}` : item.action === 'remove' ? 'Remove' : item.action === 'release' ? 'Release' : 'Preserve';
45
+ lines.push(` ${verb} ${path.relative(project, item.path)}${item.pointer ? `#${item.pointer}` : ''} — ${item.reason}`);
46
+ if (item.action === 'remove' && item.owned)
47
+ removed++;
48
+ }
49
+ for (const write of plan.writes) {
50
+ const previous = writes.get(write.path);
51
+ if (previous && !previous.after?.equals(write.after || Buffer.alloc(0)) && (previous.after || write.after)) {
52
+ throw new Error(`Conflicting receipt writes for ${write.path}; no files removed`);
53
+ }
54
+ writes.set(write.path, write);
55
+ }
56
+ if (!opts.keepRegistry) {
57
+ const retained = plan.decisions.filter(item => item.owned && !item.legacy && item.action === 'preserve');
58
+ const unknown = plan.recorded.length === 0 && Object.values(entry.deployedTo[provider]).some(value => typeof value === 'number' && value > 0);
59
+ if (unknown)
60
+ lines.push(' Deployment record retained: legacy outputs are unverifiable.');
61
+ else {
62
+ const residual = counts(retained);
63
+ let unverifiable = 0;
64
+ for (const kind of Object.keys(residual)) {
65
+ const gap = Math.max(0, entry.deployedTo[provider][kind] - inventory[kind]);
66
+ residual[kind] += gap;
67
+ unverifiable += gap;
68
+ }
69
+ if (retained.length || unverifiable) {
70
+ entry.deployedTo[provider] = residual;
71
+ if (unverifiable)
72
+ lines.push(` Retained ${unverifiable} unverifiable historical artifact count(s); no ownership inferred.`);
73
+ lines.push(` Partial removal: ${retained.length} owned file record(s) retained; deployedTo counts reconciled.`);
74
+ }
75
+ else
76
+ delete entry.deployedTo[provider];
77
+ }
78
+ }
79
+ }
80
+ if (opts.keepRegistry)
81
+ lines.push(' Registry preserved (--keep-registry).');
82
+ else {
83
+ if (!Object.keys(entry.deployedTo).length)
84
+ delete config.installed[id];
85
+ writeConfig = JSON.stringify(config) !== configBefore;
86
+ const configPath = path.join(project, '.aiwg/aiwg.config');
87
+ if (writeConfig)
88
+ writes.set(configPath, { path: configPath, before: fs.readFileSync(configPath), after: Buffer.from(`${JSON.stringify(config, null, 2)}\n`), commit: true });
89
+ const mirror = path.join(resolveProjectAiwgDir(project), 'aiwg.config');
90
+ if (writeConfig && mirror !== configPath && fs.existsSync(path.dirname(mirror)))
91
+ writes.set(mirror, { path: mirror,
92
+ before: fs.existsSync(mirror) ? fs.readFileSync(mirror) : null, after: Buffer.from(`${JSON.stringify(config, null, 2)}\n`), commit: true });
93
+ lines.push(writeConfig ? ` ${opts.dryRun ? 'Would update' : 'Update'} .aiwg/aiwg.config to match the remaining receipts.`
94
+ : ' Deployment records unchanged; .aiwg/aiwg.config preserved.');
95
+ }
96
+ if (!opts.dryRun) {
97
+ const legacyAttribution = !modern && !opts.keepRegistry && providers.includes('claude') && !Object.values(config.installed).some(item => item.deployedTo.claude);
98
+ const settings = path.join(project, '.claude/settings.json');
99
+ if (legacyAttribution && fs.existsSync(settings))
100
+ writes.set(settings, { path: settings,
101
+ before: fs.readFileSync(settings), after: fs.readFileSync(settings), commit: true });
102
+ await applyRemovalTransaction([...writes.values()], async () => {
103
+ if (writeConfig)
104
+ await writeAiwgConfig(project, config);
105
+ // Preserve existing attribution-only cleanup for legacy installations.
106
+ if (legacyAttribution)
107
+ await removeClaudeAttribution(project);
108
+ });
109
+ const directories = new Set();
110
+ for (const write of writes.values()) {
111
+ if (write.after !== null)
112
+ continue;
113
+ let dir = path.dirname(write.path);
114
+ while (dir !== project && dir.startsWith(`${project}${path.sep}`)) {
115
+ directories.add(dir);
116
+ dir = path.dirname(dir);
117
+ }
118
+ }
119
+ for (const dir of [...directories].sort((a, b) => b.length - a.length)) {
120
+ try {
121
+ fs.rmdirSync(dir);
122
+ }
123
+ catch { /* Nonempty directories preserve operator files and remaining receipts. */ }
124
+ }
125
+ }
126
+ lines.push(`${opts.dryRun ? 'Would remove' : 'Removed'} ${removed} unchanged recorded file(s); operator files preserved.`);
127
+ return { exitCode: 0, message: lines.join('\n') };
128
+ }
129
+ catch (error) {
130
+ return { exitCode: 1, message: `Framework removal failed: ${error instanceof Error ? error.message : String(error)}` };
131
+ }
132
+ }
133
+ //# sourceMappingURL=remove-bundled.js.map
@@ -0,0 +1,31 @@
1
+ // Focused subcommand handlers preserving the public facade.
2
+ const REMOVE_FLAGS_WITH_VALUES = new Set([
3
+ '--provider',
4
+ '--platform',
5
+ '--scope',
6
+ '--target',
7
+ '--prefix',
8
+ ]);
9
+ export function firstRemovePositional(args) {
10
+ for (let i = 0; i < args.length; i += 1) {
11
+ const arg = args[i];
12
+ if (REMOVE_FLAGS_WITH_VALUES.has(arg)) {
13
+ i += 1;
14
+ continue;
15
+ }
16
+ if (!arg.startsWith('-'))
17
+ return arg;
18
+ }
19
+ return undefined;
20
+ }
21
+ export function parseRemoveProvider(args) {
22
+ const idx = args.findIndex(a => a === '--provider' || a === '--platform');
23
+ if (idx < 0)
24
+ return {};
25
+ const provider = args[idx + 1];
26
+ if (!provider || provider.startsWith('-')) {
27
+ return { error: 'Error: --provider requires a provider name' };
28
+ }
29
+ return { provider };
30
+ }
31
+ //# sourceMappingURL=remove-options.js.map
@@ -0,0 +1,174 @@
1
+ import { releaseSkillOwnership } from "../../providers/skill-ownership.mjs";
2
+ import { removeClaudeAttribution } from "../../extensions/claude-hooks-installer.js";
3
+ import { createHash } from "node:crypto";
4
+ import * as os from "node:os";
5
+ import { firstRemovePositional, parseRemoveProvider } from "./remove-options.js";
6
+ export async function removeUserScopeDeploy(args) {
7
+ const positional = firstRemovePositional(args);
8
+ if (!positional) {
9
+ return {
10
+ exitCode: 1,
11
+ message: 'Error: framework name required\n\nUsage: aiwg remove <framework> --scope user [--provider <p>] [--dry-run]',
12
+ };
13
+ }
14
+ const dryRun = args.includes('--dry-run');
15
+ const providerParse = parseRemoveProvider(args);
16
+ if (providerParse.error) {
17
+ return {
18
+ exitCode: 1,
19
+ message: `${providerParse.error}\n\nUsage: aiwg remove <framework> --scope user [--provider <p>] [--dry-run]`,
20
+ };
21
+ }
22
+ const provider = providerParse.provider;
23
+ const { readUserRegistry, removeUserDeploy } = await import('../../config/user-registry.js');
24
+ const { USER_SCOPE_PATHS } = await import('../scope-resolver.js');
25
+ const registry = await readUserRegistry();
26
+ const entry = registry.installed[positional];
27
+ if (!entry) {
28
+ return {
29
+ exitCode: 1,
30
+ message: `Error: framework '${positional}' is not deployed at user scope.\n\nRun 'aiwg list --scope user' to see installed frameworks.`,
31
+ };
32
+ }
33
+ const providersToRevert = provider ? [provider] : Object.keys(entry.deployedTo);
34
+ if (provider && !entry.deployedTo[provider]) {
35
+ return {
36
+ exitCode: 1,
37
+ message: `Error: framework '${positional}' is not deployed at user scope for provider '${provider}'.\n\nDeployed providers: ${Object.keys(entry.deployedTo).join(', ') || '(none)'}`,
38
+ };
39
+ }
40
+ const fs = await import('node:fs/promises');
41
+ const path = await import('node:path');
42
+ const linesOut = [];
43
+ if (dryRun)
44
+ linesOut.push(`[dry-run] Plan for user-scope remove of '${positional}':`);
45
+ else
46
+ linesOut.push(`Removing user-scope mirror of '${positional}':`);
47
+ const { resolveFrameworkDir } = await import('./use.js');
48
+ const owner = resolveFrameworkDir(positional) ?? positional;
49
+ let totalDeleted = 0;
50
+ let conservativeFallbackUsed = false;
51
+ for (const p of providersToRevert) {
52
+ const userPaths = USER_SCOPE_PATHS[p];
53
+ if (!userPaths) {
54
+ linesOut.push(` ⚠ ${p}: no user-scope paths registered — skipping (manual cleanup may be needed)`);
55
+ continue;
56
+ }
57
+ // Cast through unknown to access the optional `entries` snapshot recorded
58
+ // by the Cycle 3 mirror. Older registry entries won't have it.
59
+ const providerEntry = entry.deployedTo[p];
60
+ const recorded = providerEntry?.entries;
61
+ if (!recorded) {
62
+ // Pre-Cycle-3 entry: surface the deploy paths and let the operator
63
+ // clean them up manually. We can't safely auto-delete because the dirs
64
+ // are shared with other frameworks.
65
+ conservativeFallbackUsed = true;
66
+ const existingDirs = [
67
+ { type: 'agents', path: userPaths.agents },
68
+ { type: 'commands', path: userPaths.commands },
69
+ { type: 'skills', path: userPaths.skills },
70
+ { type: 'rules', path: userPaths.rules },
71
+ { type: 'behaviors', path: userPaths.behaviors },
72
+ ].filter(t => t.path);
73
+ linesOut.push(` ⚠ ${p}: registry entry has no per-artifact manifest (deployed before Cycle 3). Manual cleanup of these dirs may be needed:`);
74
+ for (const t of existingDirs) {
75
+ const stat = await fs.stat(t.path).catch(() => null);
76
+ if (stat && stat.isDirectory()) {
77
+ linesOut.push(` - ${t.path}`);
78
+ }
79
+ }
80
+ continue;
81
+ }
82
+ // Precise revert — walk the recorded entry names and delete each one
83
+ // from its corresponding user-scope dir.
84
+ const sets = [
85
+ ['agents', userPaths.agents, recorded.agents],
86
+ ['commands', userPaths.commands, recorded.commands],
87
+ ['skills', userPaths.skills, recorded.skills],
88
+ ['rules', userPaths.rules, recorded.rules],
89
+ ['behaviors', userPaths.behaviors, recorded.behaviors],
90
+ ];
91
+ for (const [type, dir, names] of sets) {
92
+ if (!dir || !names || names.length === 0)
93
+ continue;
94
+ let deletedHere = 0;
95
+ let managed = {};
96
+ if (type !== 'skills') {
97
+ try {
98
+ managed = JSON.parse(await fs.readFile(path.join(dir, '.aiwg-manifest.json'), 'utf8')).managed ?? {};
99
+ }
100
+ catch { /* Legacy mirrors may have no digest receipt. */ }
101
+ }
102
+ for (const name of names) {
103
+ const target = path.join(dir, name);
104
+ const shared = Object.entries(registry.installed).some(([framework, installed]) => framework !== positional
105
+ && installed.deployedTo[p]?.entries?.[type]?.includes(name));
106
+ if (shared || managed[name]?.owners?.some(candidate => candidate !== owner)) {
107
+ linesOut.push(` · ${p} ${type}: preserve ${target} — shared with another installed framework`);
108
+ continue;
109
+ }
110
+ if (type !== 'skills') {
111
+ const digest = managed[name]?.hash;
112
+ if (digest !== undefined) {
113
+ const stat = await fs.lstat(target).catch(() => null);
114
+ const bytes = stat?.isFile() ? await fs.readFile(target).catch(() => null) : null;
115
+ if (!bytes || `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== digest) {
116
+ linesOut.push(` · ${p} ${type}: preserve ${target} — modified or unverifiable managed file`);
117
+ continue;
118
+ }
119
+ }
120
+ else
121
+ linesOut.push(` ⚠ ${p} ${type}: ${target} — legacy manifest has no digest; ${dryRun ? 'would remove' : 'removing'} by recorded name`);
122
+ }
123
+ if (dryRun) {
124
+ linesOut.push(` · ${p} ${type}: ${target}`);
125
+ deletedHere++;
126
+ continue;
127
+ }
128
+ try {
129
+ if (type === 'skills') {
130
+ const released = releaseSkillOwnership(target, { frameworkSlug: owner });
131
+ if (released === null)
132
+ continue;
133
+ }
134
+ else {
135
+ await fs.rm(target, { recursive: true, force: true });
136
+ }
137
+ deletedHere++;
138
+ totalDeleted++;
139
+ }
140
+ catch (err) {
141
+ linesOut.push(` ⚠ ${p} ${type}: failed to remove ${target}: ${err instanceof Error ? err.message : String(err)}`);
142
+ }
143
+ }
144
+ if (!dryRun && deletedHere > 0) {
145
+ linesOut.push(` ✓ ${p} ${type}: removed ${deletedHere} entry/entries from ${dir}`);
146
+ }
147
+ else if (dryRun) {
148
+ linesOut.push(` (${deletedHere} ${type} would be removed from ${dir})`);
149
+ }
150
+ }
151
+ }
152
+ if (!dryRun) {
153
+ if (provider) {
154
+ await removeUserDeploy({ framework: positional, provider });
155
+ }
156
+ else {
157
+ await removeUserDeploy({ framework: positional });
158
+ }
159
+ if (providersToRevert.includes('claude') && !Object.values((await readUserRegistry()).installed).some(item => item.deployedTo.claude))
160
+ await removeClaudeAttribution(os.homedir());
161
+ linesOut.push('');
162
+ if (conservativeFallbackUsed) {
163
+ linesOut.push('Registry updated. Some providers had no per-artifact manifest (pre-Cycle-3 deploys); inspect the dirs listed above and clean up manually if needed.');
164
+ }
165
+ else {
166
+ linesOut.push(`Registry updated. ${totalDeleted} artifact entry/entries removed.`);
167
+ }
168
+ }
169
+ return {
170
+ exitCode: 0,
171
+ message: linesOut.join('\n') + '\n',
172
+ };
173
+ }
174
+ //# sourceMappingURL=remove-user.js.map
@@ -0,0 +1,201 @@
1
+ import { createScriptRunner } from "./script-runner.js";
2
+ import { getFrameworkRoot } from "../../channel/manager.mjs";
3
+ import * as path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { getProjectDir } from "../../config/aiwg-config.js";
6
+ import { removeClaudeAttribution } from "../../extensions/claude-hooks-installer.js";
7
+ import { isScopeUser } from "./subcommands-list-format.js";
8
+ import { firstRemovePositional, parseRemoveProvider } from "./remove-options.js";
9
+ import { removeUserScopeDeploy } from "./remove-user.js";
10
+ /**
11
+ * Remove framework handler
12
+ *
13
+ * Delegates to tools/plugin/plugin-uninstaller-cli.mjs
14
+ */
15
+ export const removeHandler = {
16
+ id: "remove",
17
+ name: "Remove Framework",
18
+ description: "Remove installed framework, plugin, or project-local bundle",
19
+ category: "framework",
20
+ aliases: [],
21
+ async help() {
22
+ return { exitCode: 0, rawOutput: true, message: [
23
+ 'Usage: aiwg remove <id> [options]',
24
+ '',
25
+ 'Remove an installed framework, plugin, or project-local bundle by id (for example all or sdlc).',
26
+ 'Project scope is the default; without --provider, process all recorded provider deployments.',
27
+ '"all" is an installed bundle id, not a wildcard for every installed entry.',
28
+ 'Bundled deployments use ownership receipts to remove unchanged agents, commands, rules and skills.',
29
+ 'Project-local removal reverts deployed artifacts using recorded hashes; bundle source is preserved.',
30
+ '',
31
+ 'Options:',
32
+ ' --dry-run List planned removals and preserved paths with reasons; write nothing.',
33
+ ' --provider <p> Select one recorded provider deployment.',
34
+ ' --keep-registry Keep project installed/deployedTo records after removal. By default,',
35
+ ' remove selected deployment records and drop the id when none remain.',
36
+ ' Project-local partial reverts retain their registry records.',
37
+ ' --force Override project-local mutation refusal or legacy plugin dependency checks;',
38
+ ' does not override bundled file hash/ownership preservation.',
39
+ ' --scope user Remove the user-scope mirror using ~/.aiwg/installed.json instead.',
40
+ ' --user Alias for --scope user; user mirror removal updates its own registry.',
41
+ ' --target <d> Target a project directory (alias: --prefix; default: cwd).',
42
+ ' --help, -h Show this help.',
43
+ '',
44
+ 'Bundled file removal preserves modified files, unrecorded operator files, foreign skills,',
45
+ 'and symlinks inside skill directories. Project-local bundle source is never deleted.',
46
+ 'Legacy outputs without receipts are unverifiable and preserved.',
47
+ 'Recorded settings and hooks restore pre-deploy values; operator edits are kept and reported.',
48
+ 'User-scope legacy records without artifact manifests require manual file cleanup.',
49
+ 'Unregistered ids fall back to the legacy plugin uninstaller (also supports --keep-data).',
50
+ '',
51
+ 'Examples:',
52
+ ' aiwg remove all --dry-run',
53
+ ' aiwg remove sdlc --provider claude --dry-run',
54
+ ' aiwg remove my-bundle --keep-registry',
55
+ ' aiwg remove sdlc --scope user --provider codex --dry-run',
56
+ ].join('\n') };
57
+ },
58
+ async execute(ctx) {
59
+ // Explicit provider removal is separate from framework removal. The native
60
+ // adapter validates receipt hashes and preserves operator modifications.
61
+ const nativeRemovalProvider = parseRemoveProvider(ctx.args);
62
+ if (firstRemovePositional(ctx.args) === 'omp' && nativeRemovalProvider.provider === 'omp') {
63
+ // Loaded from the package root, not by a path relative to this file: the
64
+ // compiled handler sits one directory deeper than its source.
65
+ const { uninstall } = (await import(pathToFileURL(path.join(await getFrameworkRoot(), 'tools/agents/providers/omp.mjs')).href));
66
+ const { getProjectDir } = await import('../../config/aiwg-config.js');
67
+ const dryRun = ctx.args.includes('--dry-run');
68
+ const scope = ctx.args.includes('--user') || isScopeUser(ctx.args) ? 'user' : 'project';
69
+ const count = uninstall(getProjectDir({ cwd: ctx.cwd }, ctx.args), { dryRun, scope });
70
+ return { exitCode: 0, message: `${dryRun ? 'Would remove' : 'Removed'} ${count} unchanged OMP-owned files; operator files preserved.` };
71
+ }
72
+ // #1156 Phase 1 — `--scope user` / `--user`: revert the user-scope mirror
73
+ // for the given framework. Independent of any project; reads the per-user
74
+ // registry at ~/.aiwg/installed.json to find what was deployed, deletes
75
+ // the mirrored artifacts under the provider's USER_SCOPE_PATHS, and
76
+ // updates the registry.
77
+ if (ctx.args.includes('--user') || isScopeUser(ctx.args)) {
78
+ return await removeUserScopeDeploy(ctx.args);
79
+ }
80
+ if (firstRemovePositional(ctx.args) === 'grok-build') {
81
+ const providerParse = parseRemoveProvider(ctx.args);
82
+ if (providerParse.provider !== 'grok-build' || providerParse.error) {
83
+ return { exitCode: 1, message: 'Use aiwg remove grok-build --provider grok-build [--dry-run] for reviewed project-scope removal.' };
84
+ }
85
+ const frameworkRoot = await getFrameworkRoot();
86
+ const { uninstall } = (await import(pathToFileURL(path.join(frameworkRoot, 'tools/agents/providers/grok-build.mjs')).href));
87
+ const { readAiwgConfig, writeAiwgConfig } = await import('../../config/aiwg-config.js');
88
+ const target = getProjectDir({ cwd: ctx.cwd }, ctx.args);
89
+ const dryRun = ctx.args.includes('--dry-run');
90
+ const report = uninstall(target, { dryRun, srcRoot: frameworkRoot });
91
+ if (!dryRun && report.skipped.length === 0) {
92
+ const config = await readAiwgConfig(target);
93
+ if (config) {
94
+ for (const [name, entry] of Object.entries(config.installed ?? {})) {
95
+ delete entry.deployedTo?.['grok-build'];
96
+ if (Object.keys(entry.deployedTo ?? {}).length === 0)
97
+ delete config.installed[name];
98
+ }
99
+ await writeAiwgConfig(target, config);
100
+ }
101
+ }
102
+ const lines = [
103
+ `${dryRun ? 'Would remove' : 'Removed'} ${dryRun ? report.planned.length : report.removed.length} unchanged AIWG-owned Grok Build artifact(s).`,
104
+ ...report.planned.map(relative => ` ${relative}`),
105
+ ...report.skipped.map(relative => ` Preserved modified or unverifiable: ${relative}`),
106
+ 'Operator-owned Grok content and shared context files are preserved.',
107
+ ];
108
+ return { exitCode: report.skipped.length ? 1 : 0, message: lines.join('\n') };
109
+ }
110
+ // #1037 — Project-local-aware remove. If the first positional arg matches
111
+ // a project-local entry in `installed`, route to the new handler.
112
+ // Otherwise fall through to the existing plugin-uninstaller flow.
113
+ const positionalArg = firstRemovePositional(ctx.args);
114
+ const providerParse = parseRemoveProvider(ctx.args);
115
+ if (providerParse.error) {
116
+ return {
117
+ exitCode: 1,
118
+ message: `${providerParse.error}\n\nUsage: aiwg remove <id> [--force] [--dry-run] [--provider <p>] [--keep-registry]`,
119
+ };
120
+ }
121
+ if (!positionalArg) {
122
+ return {
123
+ exitCode: 1,
124
+ message: 'Error: framework or bundle id required\n\nUsage: aiwg remove <id> [--force] [--dry-run] [--provider <p>] [--keep-registry]',
125
+ };
126
+ }
127
+ if (positionalArg) {
128
+ try {
129
+ const { readAiwgConfig, writeAiwgConfig, getProjectDir } = await import('../../config/aiwg-config.js');
130
+ const { removeProjectLocalBundle } = await import('../../extensions/project-local-remove.js');
131
+ const projectDir = getProjectDir({ cwd: ctx.cwd }, ctx.args);
132
+ const config = await readAiwgConfig(projectDir);
133
+ const entry = config?.installed?.[positionalArg];
134
+ if (config && entry && entry.source !== 'project-local') {
135
+ const { resolveFrameworkDir } = await import('./use.js');
136
+ const { removeBundledDeployment } = await import('./remove-bundled.js');
137
+ const providers = Object.keys(entry.deployedTo).filter(p => !providerParse.provider || p === providerParse.provider);
138
+ if (providerParse.provider && providers.length === 0) {
139
+ return { exitCode: 1, message: `Error: '${positionalArg}' is not deployed for provider '${providerParse.provider}'.` };
140
+ }
141
+ return removeBundledDeployment(projectDir, positionalArg, resolveFrameworkDir(positionalArg) ?? positionalArg, config, providers, {
142
+ dryRun: ctx.args.includes('--dry-run'), keepRegistry: ctx.args.includes('--keep-registry'),
143
+ });
144
+ }
145
+ if (config && entry?.source === 'project-local') {
146
+ const force = ctx.args.includes('--force');
147
+ const dryRun = ctx.args.includes('--dry-run');
148
+ const keepRegistry = ctx.args.includes('--keep-registry');
149
+ const provider = providerParse.provider;
150
+ const result = await removeProjectLocalBundle(config, projectDir, positionalArg, { force, dryRun, keepRegistry, provider });
151
+ // Print outcome summary
152
+ const lines = [];
153
+ if (dryRun)
154
+ lines.push(`[dry-run] Plan for project-local '${positionalArg}':`);
155
+ for (const o of result.outcomes) {
156
+ const marker = o.reverted ? '✓' : '⚠';
157
+ lines.push(` ${marker} ${o.provider} :: ${o.artifactPath} [${o.case}] ${o.message}`);
158
+ }
159
+ if (result.revertedProviders.length > 0) {
160
+ lines.push(`Fully reverted: ${result.revertedProviders.join(', ')}`);
161
+ }
162
+ if (result.partialProviders.length > 0) {
163
+ lines.push(`Partial (registry preserved): ${result.partialProviders.join(', ')}`);
164
+ }
165
+ if (lines.length > 0)
166
+ console.log(lines.join('\n'));
167
+ if (!dryRun) {
168
+ await writeAiwgConfig(projectDir, config);
169
+ if (result.revertedProviders.includes('claude') && !Object.values(config.installed).some(item => item.deployedTo.claude))
170
+ await removeClaudeAttribution(projectDir);
171
+ }
172
+ // Note: source under .aiwg/<type>/<name>/ is intentionally NOT
173
+ // deleted (load-bearing invariant from #1048 design).
174
+ return {
175
+ exitCode: result.partialProviders.length > 0 ? 1 : 0,
176
+ message: result.partialProviders.length > 0
177
+ ? `Some artifacts skipped (see above). Use --force to override mutation refusal.`
178
+ : '',
179
+ };
180
+ }
181
+ }
182
+ catch (err) {
183
+ // A failed receipt/config read must never trigger a second, legacy deletion path.
184
+ const msg = err instanceof Error ? err.message : String(err);
185
+ return { exitCode: 1, message: `Framework removal pre-check failed: ${msg}` };
186
+ }
187
+ }
188
+ if (providerParse.provider) {
189
+ return {
190
+ exitCode: 1,
191
+ message: `Error: --provider is only supported for project-local or user-scope remove. '${positionalArg}' is not a project-local bundle.\n\nUse 'aiwg remove ${positionalArg}' without --provider, or 'aiwg remove ${positionalArg} --scope user --provider ${providerParse.provider}' for a user-scope mirror. Refs #1610.`,
192
+ };
193
+ }
194
+ const frameworkRoot = await getFrameworkRoot();
195
+ const runner = createScriptRunner(frameworkRoot);
196
+ return runner.run("tools/plugin/plugin-uninstaller-cli.mjs", ctx.args, {
197
+ cwd: ctx.cwd,
198
+ });
199
+ },
200
+ };
201
+ //# sourceMappingURL=remove.js.map