lean-agents 0.8.0 → 1.0.0

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 (44) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/README.es.md +130 -24
  3. package/README.md +130 -24
  4. package/core/copilot-usage-tui.js +5 -2
  5. package/core/pins.json +18 -9
  6. package/package.json +3 -2
  7. package/scripts/behavior-diff.sh +47 -0
  8. package/scripts/bump-pins.mjs +14 -3
  9. package/scripts/ci-timing.mjs +61 -0
  10. package/scripts/labels.sh +1 -0
  11. package/scripts/lean.mjs +695 -76
  12. package/scripts/lib/adapters/antigravity.mjs +20 -9
  13. package/scripts/lib/adapters/claude.mjs +7 -2
  14. package/scripts/lib/adapters/copilot-cli.mjs +4 -3
  15. package/scripts/lib/adapters/opencode-v1.mjs +6 -13
  16. package/scripts/lib/adapters/opencode-v2.mjs +51 -3
  17. package/scripts/lib/adopt.mjs +172 -27
  18. package/scripts/lib/agent-lifecycle.mjs +140 -23
  19. package/scripts/lib/backup-stamp.mjs +25 -0
  20. package/scripts/lib/doctor.mjs +86 -14
  21. package/scripts/lib/feedback.mjs +22 -4
  22. package/scripts/lib/fsops.mjs +42 -14
  23. package/scripts/lib/inventory.mjs +5 -4
  24. package/scripts/lib/logins.mjs +28 -0
  25. package/scripts/lib/network.mjs +53 -13
  26. package/scripts/lib/opencode-backup.mjs +204 -0
  27. package/scripts/lib/opencode-upgrade.mjs +441 -0
  28. package/scripts/lib/opencode1.mjs +203 -0
  29. package/scripts/lib/parallel.mjs +7 -2
  30. package/scripts/lib/pins-diff.mjs +33 -0
  31. package/scripts/lib/pins.mjs +7 -2
  32. package/scripts/lib/plugin-health.mjs +191 -0
  33. package/scripts/lib/prereqs.mjs +203 -0
  34. package/scripts/lib/shell-path.mjs +22 -0
  35. package/scripts/lib/summary-data.mjs +30 -0
  36. package/scripts/lib/summary-html.mjs +159 -0
  37. package/scripts/lib/system.mjs +107 -16
  38. package/scripts/lib/terminals.mjs +101 -3
  39. package/scripts/lib/update-plan.mjs +60 -0
  40. package/scripts/lib/upgrade.mjs +112 -11
  41. package/scripts/lib/verify-prompt.mjs +46 -0
  42. package/scripts/pins-latest.mjs +27 -4
  43. package/scripts/release.mjs +26 -1
  44. package/scripts/version-watch.mjs +8 -2
@@ -1,4 +1,5 @@
1
1
  // Antigravity CLI (`agy`) adapter. Paths confirmed on agy 1.4.12 in CI.
2
+ import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { OWNED_MARK } from '../fsops.mjs';
4
5
  import { tierFor, modelFor } from '../render.mjs';
@@ -31,13 +32,20 @@ export function renderAntigravityAgent(agent, profile) {
31
32
  ].join('\n');
32
33
  }
33
34
 
34
- const skills = (tool, desc, repo, names) => ({
35
- tool,
36
- desc,
37
- run: [['npx', '-y', skillsCli(), 'add', repo, '--skill', ...names, '-a', 'antigravity-cli', '-g', '-y']],
38
- // Without -a: `remove -a` keeps ~/.agents/skills while another detected agent may share that folder.
39
- undo: [['npx', '-y', skillsCli(), 'remove', ...names, '-g', '-y']],
40
- });
35
+ // #148: a skill folder is ours only if an earlier run recorded it in state.json (prior) or it did not exist before.
36
+ // An unmarked folder with the same name is the user's: it is neither overwritten nor removed.
37
+ const skills = (home, prior, tool, desc, repo, names) => {
38
+ const mine = names.filter((n) => prior.some((c) => c.desc === desc && c.undo?.some((u) => u.includes(n))) || !fs.existsSync(path.join(home, '.gemini', 'config', 'skills', n)));
39
+ for (const n of names.filter((x) => !mine.includes(x))) console.log(`Kept your existing Antigravity skill "${n}": lean-agents did not install it and will not remove it.`);
40
+ if (!mine.length) return null;
41
+ return {
42
+ tool,
43
+ desc,
44
+ run: [['npx', '-y', skillsCli(), 'add', repo, '--skill', ...mine, '-a', 'antigravity-cli', '-g', '-y']],
45
+ // Without -a: `remove -a` keeps ~/.agents/skills while another detected agent may share that folder.
46
+ undo: [['npx', '-y', skillsCli(), 'remove', ...mine, '-g', '-y']],
47
+ };
48
+ };
41
49
 
42
50
  export function antigravityAdapter({ home, core, profile, opts, rules, adhdCommand }) {
43
51
  const dir = path.join(home, '.gemini', 'config');
@@ -63,10 +71,13 @@ export function antigravityAdapter({ home, core, profile, opts, rules, adhdComma
63
71
  console.log('Context Mode has no Antigravity setup in v2: skipped. Check `context-mode setup --list` for support.');
64
72
  }
65
73
  if (tools.includes('caveman')) {
66
- commands.push(skills('caveman', 'Caveman skills for Antigravity', skillSource('caveman'), ['caveman', 'caveman-compress', 'caveman-stats']));
74
+ const c = skills(home, opts.prior ?? [], 'caveman', 'Caveman skills for Antigravity', skillSource('caveman'), ['caveman', 'caveman-compress', 'caveman-stats']);
75
+ if (c) commands.push(c);
67
76
  }
68
77
  if (tools.includes('i-have-adhd')) {
69
- commands.push(skills('i-have-adhd', 'i-have-adhd skill for Antigravity', skillSource('i-have-adhd'), ['i-have-adhd']), adhdCommand);
78
+ const c = skills(home, opts.prior ?? [], 'i-have-adhd', 'i-have-adhd skill for Antigravity', skillSource('i-have-adhd'), ['i-have-adhd']);
79
+ // adhdCommand rewrites every i-have-adhd copy, so it must not run over a kept user skill.
80
+ if (c) commands.push(c, adhdCommand);
70
81
  }
71
82
  return { actions, commands };
72
83
  }
@@ -3,7 +3,7 @@
3
3
  import path from 'node:path';
4
4
  import { OWNED_MARK } from '../fsops.mjs';
5
5
  import { tierFor, modelFor } from '../render.mjs';
6
- import { privacyOf } from '../network.mjs';
6
+ import { privacyOf, updaterMode } from '../network.mjs';
7
7
  import { statuslineScript } from '../copilot-usage.mjs';
8
8
  import { marketplaceSource, skillSource, skillsCli } from '../pins.mjs';
9
9
 
@@ -54,7 +54,6 @@ export function claudeAdapter({ home, core, profile, opts, rulesPath, adhdComman
54
54
  edits.unshift({ path: ['model'], value: profile?.main_model ?? 'sonnet', mode: 'setIfAbsent' });
55
55
  const net = opts.network;
56
56
  const off = [
57
- ...(net.autoUpdate === 'off' ? ['DISABLE_AUTOUPDATER'] : []),
58
57
  ...(net.telemetry === 'off' ? ['DISABLE_TELEMETRY', 'DISABLE_ERROR_REPORTING'] : []),
59
58
  ...(net.outbound === 'off' ? ['DISABLE_BUG_COMMAND'] : []),
60
59
  // Also stops updates and telemetry, so only when every category is off.
@@ -62,6 +61,12 @@ export function claudeAdapter({ home, core, profile, opts, rulesPath, adhdComman
62
61
  ...(net.telemetry === 'off' ? ['DO_NOT_TRACK'] : []),
63
62
  ];
64
63
  for (const k of off) edits.push({ path: ['env', k], value: '1', mode: 'set' });
64
+ // Managed installs update through --update: off unless the user already chose a value (network off forces it).
65
+ // A DISABLE_AUTOUPDATER already in the environment is the user's own choice, so it is respected too.
66
+ const updater = updaterMode(opts);
67
+ if (updater && !(updater === 'setIfAbsent' && (opts.env ?? process.env).DISABLE_AUTOUPDATER !== undefined)) edits.push({ path: ['env', 'DISABLE_AUTOUPDATER'], value: '1', mode: updater });
68
+ // Opt-in only (#304): experimental, and a session started with it resumes only with it on. User settings only; project settings ignore it.
69
+ if (tools.includes('code-mode')) edits.push({ path: ['env', 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'], value: '1', mode: 'setIfAbsent' });
65
70
  if (tools.includes('copilot-usage')) {
66
71
  // Only when the user has no statusLine (setIfAbsent); uninstall removes it only while it is still ours. Forward slashes: Claude runs it through bash, also on Windows.
67
72
  const script = path.join(dir, 'lean-copilot-usage-statusline.mjs');
@@ -8,6 +8,7 @@ import { envDir } from '../system.mjs';
8
8
  import { localServer } from './opencode-v2.mjs';
9
9
  import { skillSource, skillsCli } from '../pins.mjs';
10
10
  import { toolEnv } from '../node-runtime.mjs';
11
+ import { updaterMode } from '../network.mjs';
11
12
 
12
13
  const CONTEXT_MODE_SCRIPT = fileURLToPath(new URL('../../copilot-context-mode.mjs', import.meta.url));
13
14
 
@@ -52,9 +53,9 @@ export function copilotAdapter({ home, core, profile, opts, rules, adhdCommand }
52
53
  edits.push({ path: ['mcpServers', name], value: { type: 'local', command, args, tools: ['*'] }, mode: 'setIfAbsent' });
53
54
  }
54
55
  if (edits.length) actions.push({ kind: 'json', path: path.join(dir, 'mcp-config.json'), edits, keepEmpty: [['mcpServers']] });
55
- if (opts.network.autoUpdate === 'off') {
56
- actions.push({ kind: 'json', path: path.join(dir, 'settings.json'), edits: [{ path: ['autoUpdate'], value: false, mode: 'set' }] });
57
- }
56
+ // Managed installs update through --update: off unless the user already set `autoUpdate` (network off forces it).
57
+ const updater = updaterMode(opts);
58
+ if (updater) actions.push({ kind: 'json', path: path.join(dir, 'settings.json'), edits: [{ path: ['autoUpdate'], value: false, mode: updater }] });
58
59
 
59
60
  if (tools.includes('rtk')) {
60
61
  commands.push({ tool: 'rtk', desc: 'RTK hook for Copilot CLI', run: [['rtk', 'init', '-g', '--copilot']], undo: [['rtk', 'init', '-g', '--copilot', '--uninstall']] });
@@ -1,10 +1,11 @@
1
1
  // OpenCode 1.x adapter (>=1.18.29). Keys checked against the 1.19.0 config schema; files
2
2
  // and commands are shared with the 2.x adapter, only config keys differ.
3
3
  import path from 'node:path';
4
- import { configPath, localServer, opencodeShared, profileEdits, shellEdit } from './opencode-v2.mjs';
4
+ import { configPath, dcpConfigAction, localServer, opencodeShared, profileEdits, shellEdit } from './opencode-v2.mjs';
5
5
  import { OWNED_MARK } from '../fsops.mjs';
6
6
  import { configHome } from '../system.mjs';
7
7
  import { npmSpec } from '../pins.mjs';
8
+ import { updaterMode } from '../network.mjs';
8
9
 
9
10
  // OpenCode 1.19's TUI runs server plugins in a Bun worker and never calls the factory in Orca's managed
10
11
  // plugins/orca-opencode-status.js, so Orca shows no status. Loading it from a file under another name
@@ -64,21 +65,13 @@ export function opencodeV1Adapter({ home, core, profile, opts, rulesPath }) {
64
65
  actions.push(...orcaShimActions({ dir, terminals: opts.terminals, platform: opts.platform }));
65
66
  if (tools.includes('ponytail')) edits.push({ path: ['plugin'], value: npmSpec('ponytail'), mode: 'arrayAdd', legacy: ['@dietrichgebert/ponytail'] });
66
67
  if (tools.includes('dcp')) {
67
- edits.push({ path: ['plugin'], value: npmSpec('opencode-dcp'), mode: 'arrayAdd' });
68
- const contextWindow = profile?.context_window ?? 200000;
69
- actions.push({
70
- kind: 'json',
71
- path: path.join(dir, 'dcp.jsonc'),
72
- edits: [
73
- { path: ['$schema'], value: 'https://raw.githubusercontent.com/Opencode-DCP/opencode-dynamic-context-pruning/master/dcp.schema.json', mode: 'setIfAbsent' },
74
- { path: ['compress', 'minContextLimit'], value: Math.round(contextWindow * 0.5), mode: 'setIfAbsent' },
75
- { path: ['compress', 'maxContextLimit'], value: Math.round(contextWindow * 0.8), mode: 'setIfAbsent' },
76
- ],
77
- });
68
+ edits.push({ path: ['plugin'], value: npmSpec('opencode-dcp'), mode: 'arrayAdd', legacy: [] }); // any DCP entry already there is the user's: kept, nothing appended (#212)
69
+ actions.push(dcpConfigAction(dir, profile));
78
70
  }
79
71
  const net = opts.network;
80
72
  if (net.outbound === 'off') edits.push({ path: ['share'], value: 'disabled', mode: 'set' });
81
- if (net.autoUpdate === 'off') edits.push({ path: ['autoupdate'], value: false, mode: 'set' });
73
+ // Managed installs update through --update: off unless the user already set `autoupdate` (network off forces it).
74
+ if (updaterMode(opts)) edits.push({ path: ['autoupdate'], value: false, mode: updaterMode(opts) });
82
75
  if (net.telemetry === 'off') edits.push({ path: ['experimental', 'openTelemetry'], value: false, mode: 'set' });
83
76
  if (net.outbound === 'off' && profile?.provider !== 'opencode') edits.push({ path: ['disabled_providers'], value: 'opencode', mode: 'arrayAdd' });
84
77
  actions.push({ kind: 'json', path: configPath(dir), edits });
@@ -4,11 +4,13 @@ import path from 'node:path';
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { parse } from 'jsonc-parser';
7
8
  import { OWNED_MARK } from '../fsops.mjs';
8
9
  import { tierFor, modelFor } from '../render.mjs';
9
10
  import { configHome } from '../system.mjs';
10
11
  import { gitBashPath } from '../terminals.mjs';
11
12
  import { PINS, npmSpec, skillSource, skillsCli } from '../pins.mjs';
13
+ import { updaterMode } from '../network.mjs';
12
14
 
13
15
  const PERMISSIONS = {
14
16
  'read-only': [' edit: deny', ' bash: deny'],
@@ -43,6 +45,20 @@ export function localServer(core, name) {
43
45
  return { type: 'local', command, enabled: true };
44
46
  }
45
47
 
48
+ // dcp.jsonc thresholds, shared by 1.x and 2.x. setIfAbsent keeps any value the user already set.
49
+ export function dcpConfigAction(dir, profile) {
50
+ const contextWindow = profile?.context_window ?? 200000;
51
+ return {
52
+ kind: 'json',
53
+ path: path.join(dir, 'dcp.jsonc'),
54
+ edits: [
55
+ { path: ['$schema'], value: 'https://raw.githubusercontent.com/Opencode-DCP/opencode-dynamic-context-pruning/master/dcp.schema.json', mode: 'setIfAbsent' },
56
+ { path: ['compress', 'minContextLimit'], value: Math.round(contextWindow * 0.5), mode: 'setIfAbsent' },
57
+ { path: ['compress', 'maxContextLimit'], value: Math.round(contextWindow * 0.8), mode: 'setIfAbsent' },
58
+ ],
59
+ };
60
+ }
61
+
46
62
  // MCP entry edit. `shape` turns a command array into this agent's entry. A server with `legacy` commands in core/mcp.json
47
63
  // (Context Mode: other versions, with or without `server`, npx or an nvm Node; `*` is a wildcard) has those entries replaced
48
64
  // by a rerun, so the npx and absolute forms flip either way. Anything else the user has is kept.
@@ -84,6 +100,17 @@ function ponytailConfig(home) {
84
100
  return path.join(appData, 'ponytail', 'config.json');
85
101
  }
86
102
 
103
+ // state.json is editable, so the undo does not trust its path: it re-derives the vendor dir from HOME (the engine points it at --home)
104
+ // and refuses anything else, or a symlink, through fsops.unsafe.
105
+ const SCRIPT = (fsops, system) => `import os from 'node:os'; import path from 'node:path'; import fs from 'node:fs';
106
+ import { unsafe } from ${JSON.stringify(fsops)}; import { configHome } from ${JSON.stringify(system)};
107
+ const home = os.homedir(); const want = path.join(configHome(home), 'opencode', 'vendor', 'i-have-adhd');
108
+ const why = (process.platform === 'win32' ? (x) => x.toLowerCase() : (x) => x)(path.resolve(process.argv[1])) !== (process.platform === 'win32' ? want.toLowerCase() : want) ? 'not the path lean-agents installed' : unsafe(want, [home]);
109
+ if (why) { console.error('refusing to remove ' + process.argv[1] + ': ' + why); process.exit(1); }
110
+ fs.rmSync(want, { recursive: true, force: true });`;
111
+ const vendorUndo = (vendor) => [process.execPath, '--input-type=module', '-e',
112
+ SCRIPT(pathToFileURL(fileURLToPath(new URL('../fsops.mjs', import.meta.url))).href, pathToFileURL(fileURLToPath(new URL('../system.mjs', import.meta.url))).href), vendor];
113
+
87
114
  // Everything that is the same on OpenCode 1.x and 2.x: files and commands, not config keys.
88
115
  export function opencodeShared({ home, dir, core, profile, opts, v2 = false }) {
89
116
  const tools = opts.tools;
@@ -103,7 +130,8 @@ export function opencodeShared({ home, dir, core, profile, opts, v2 = false }) {
103
130
  for (const agent of core.agents) {
104
131
  actions.push({ kind: 'file', path: path.join(dir, 'agents', `${agent.name}.md`), content: renderOpenCodeAgent(agent, profile) });
105
132
  }
106
- if (tools.includes('rtk')) {
133
+ // rtk (up to 1.2.1) writes a 1.x plugin that OpenCode 2 refuses to load (#179); VERIFY again when rtk supports the 2.x API.
134
+ if (tools.includes('rtk') && !v2) {
107
135
  commands.push({ tool: 'rtk', desc: 'RTK plugin for OpenCode', run: [['rtk', 'init', '-g', '--opencode']], undo: [['rtk', 'init', '-g', '--opencode', '--uninstall']] });
108
136
  }
109
137
  if (tools.includes('i-have-adhd')) {
@@ -114,7 +142,7 @@ export function opencodeShared({ home, dir, core, profile, opts, v2 = false }) {
114
142
  // The tag must still point at the pinned commit; a moved tag removes the checkout and fails the command.
115
143
  run: [['git', 'clone', '--depth', '1', '--branch', PINS['i-have-adhd'].version, 'https://github.com/ayghri/i-have-adhd', vendor],
116
144
  [process.execPath, fileURLToPath(new URL('../verify-commit.mjs', import.meta.url)), vendor, PINS['i-have-adhd'].sha]],
117
- undo: [['node', '-e', 'require("fs").rmSync(process.argv[1], { recursive: true, force: true })', vendor]],
145
+ undo: [vendorUndo(vendor)],
118
146
  skipIfExists: vendor,
119
147
  });
120
148
  actions.push({
@@ -155,9 +183,29 @@ export function opencodeV2Adapter({ home, core, profile, opts, rulesPath }) {
155
183
  if (tools.includes(name)) edits.push(mcpEdit(['mcp', 'servers', name], (command) => ({ type: 'local', command, enabled: true }), localServer(core, name).command, core.mcp[name].legacy));
156
184
  }
157
185
  if (tools.includes('ponytail')) edits.push({ path: ['plugins'], value: npmSpec('ponytail'), mode: 'arrayAdd', legacy: ['@dietrichgebert/ponytail'] });
186
+ if (tools.includes('dcp')) {
187
+ const pkg = PINS['opencode-dcp'].source;
188
+ edits.push({ path: ['plugins'], value: npmSpec('opencode-dcp'), mode: 'arrayAdd', legacy: [] }); // any DCP entry already there is the user's: kept, nothing appended (#212)
189
+ actions.push(dcpConfigAction(dir, profile));
190
+ for (const file of ['tui.json', 'tui.jsonc']) {
191
+ const p = path.join(dir, file);
192
+ if (fs.existsSync(p)) {
193
+ try {
194
+ const parsed = parse(fs.readFileSync(p, 'utf8'));
195
+ const plugins = Array.isArray(parsed?.plugin) ? parsed.plugin : [];
196
+ if (plugins.some(x => typeof x === 'string' && (x === pkg || x.startsWith(`${pkg}@`)))) {
197
+ actions.push({ kind: 'json', path: p, edits: [{ path: ['plugin'], value: npmSpec('opencode-dcp'), mode: 'arrayAdd', legacy: [`${pkg}@latest`, pkg] }] });
198
+ }
199
+ } catch (e) {
200
+ // skip
201
+ }
202
+ }
203
+ }
204
+ }
158
205
  if (opts.terminals?.includes('warp')) edits.push({ path: ['plugins'], value: npmSpec('warp-opencode'), mode: 'arrayAdd', legacy: ['@warp-dot-dev/opencode-warp'] });
159
206
  if (opts.network.outbound === 'off') edits.push({ path: ['share'], value: 'disabled', mode: 'set' });
160
- if (opts.network.autoUpdate === 'off') edits.push({ path: ['update'], value: 'disable', mode: 'set' });
207
+ // Managed installs update through --update: off unless the user already set `update` (network off forces it).
208
+ if (updaterMode(opts)) edits.push({ path: ['update'], value: 'disable', mode: updaterMode(opts) });
161
209
  if (opts.network.outbound === 'off') {
162
210
  if (profile?.provider !== 'opencode') {
163
211
  edits.push({ path: ['policies'], value: { effect: 'deny', action: 'provider.use', resource: 'opencode' }, mode: 'arrayAdd' });
@@ -6,23 +6,45 @@ import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
+ import { execFileSync } from 'node:child_process';
9
10
  import { parse } from 'jsonc-parser';
10
11
  import { hasMark, plan as planFiles, revertJsonEdits, sha, writePrivate, privateDir, dropBackups, unsafe } from './fsops.mjs';
11
12
  import { PINS, npmSpec, pinVersions } from './pins.mjs';
12
- import { configHome, envDir } from './system.mjs';
13
+ import { configHome, envDir, antigravityFootprint } from './system.mjs';
13
14
  import { configPath } from './adapters/opencode-v2.mjs';
14
15
  import { mcpServers } from './migrate.mjs';
15
- import { findNvm, resolveToolNodes, minVersion, installedNodes, toolEnv } from './node-runtime.mjs';
16
+ import { findNvm, resolveToolNodes, minVersion, compare, satisfies, installedNodes, toolEnv } from './node-runtime.mjs';
16
17
  import { run } from './system.mjs';
17
18
  import { doctor } from './doctor.mjs';
19
+ import { pluginHealth, probePlugins } from './plugin-health.mjs';
20
+ import { orcaHooksFound } from './terminals.mjs';
18
21
  import { clients, launchOf, pinOf, classify, npmCopies, skillDirs, duplicateSkills, treeSha, probeInitialize } from './inventory.mjs';
19
22
 
20
23
  const j = path.join;
21
24
  const MANAGED_SKILLS = new Set(Object.entries(PINS).filter(([, p]) => p.kind === 'skill').map(([k]) => k));
22
25
  const MANAGED_HOOK = /\b(rtk|context-mode|gsd)\b/;
26
+ // A pre-release sorts below its release (#204). shortcut: two pre-releases of one core compare equal, no -beta.2 vs -beta.10 order; upgrade when a pinned tool ships two.
27
+ export const cmpVersion = (a, b) => compare(String(a).split(/[-+]/)[0], String(b).split(/[-+]/)[0]) || (String(b).split('+')[0].includes('-') - String(a).split('+')[0].includes('-')); // build metadata (+x) is ignored (#219)
28
+ // Shell syntax (GSD's `$(for n in ...; done) file.js`) is named after the first script it runs (#202).
29
+ const SHELL_HEAD = /^(\$\(|\(|\{)|^(for|if|while)$/;
30
+ const SCRIPT_PATH = /[^\s"'();|&]+\.(?:[cm]?js|ts|ps1|sh)(?![\w.])/;
31
+ // win32.basename splits both separators, so a Windows path never leaks into a name on macOS or Linux.
32
+ export const cursorHookLabel = (command, argv) => {
33
+ if (!(SHELL_HEAD.test(argv[0]) || (/^(sh|bash)$/.test(argv[0]) && argv[1] === '-c'))) return path.win32.basename(argv[0]);
34
+ const script = command.match(SCRIPT_PATH);
35
+ return script ? path.win32.basename(script[0]) : 'shell';
36
+ };
37
+ // PowerShell -e, -ec, -enc...: the payload is never named or matched; `--encoding` is not one.
38
+ // Bare `-e`/`-ec` only count next to powershell/pwsh: `node -e 1` is not a payload.
39
+ export const cursorEncoded = (command) => /(^|\s)-enc\w*(\s|$)/i.test(command) || (/\b(powershell|pwsh)(\.exe)?\b/i.test(command) && /(^|\s)-ec?(\s|$)/i.test(command));
40
+ // The basename of any argument counts (`npx -y context-mode hook cursor`, `env FOO=1 rtk hook cursor`); a folder never does: `node /opt/rtk-fork/hook.js` is the user's.
41
+ // Flags, URLs and whitespace tokens (`sh -c "echo rtk"`) are arguments, not program names (#235).
42
+ const nameToken = (a) => !/^[A-Za-z_]\w*=/.test(a) && !a.startsWith('-') && !a.includes('://') && !/\s/.test(a);
43
+ export const cursorNameManaged = (command, argv) => argv.some((a) => nameToken(a) && MANAGED_HOOK.test(path.win32.basename(a))) || MANAGED_HOOK.test(cursorHookLabel(command, argv));
23
44
  const MANAGED_PLUGIN = /context-mode|opencode-dcp|opencode-warp|lean-agents/;
24
45
 
25
46
  const readJson = (file) => { try { return parse(fs.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
47
+ const readJsonText = (file) => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
26
48
  const pinVersion = (argv, pin) => {
27
49
  const m = argv.map((a) => new RegExp(`${PINS[pin].source.replace(/[/.]/g, '\\$&')}@(\\d[^\\s/]*)$`).exec(a)).find(Boolean);
28
50
  return m?.[1] ?? null;
@@ -38,8 +60,31 @@ const STOPGAPS = [
38
60
  { rel: ['.config', 'opencode', 'plugins', 'orca-status-tui-shim.js'], by: 'the managed Orca integration (--terminal orca)', needs: { terminals: 'orca' } },
39
61
  ];
40
62
 
63
+ // node:sqlite needs no flag from Node 22.13 and 23.4 (24.x too); a tool Node older than that is not tried.
64
+ export const sqliteOk = (v) => { const [a, b] = minVersion(`>=${v}`); return a >= 24 || (a === 23 && b >= 4) || (a === 22 && b >= 13); };
65
+ const COUNT_SCRIPT = "const{DatabaseSync}=require('node:sqlite');const d=new DatabaseSync(process.argv[1],{readOnly:true});console.log(d.prepare('SELECT count(*) AS n FROM session').get().n)";
66
+
67
+ // Count in a child Node when this one lacks node:sqlite (#201): the tool Node first, then this Node with the flag. null when neither answers.
68
+ export function countInChild(dbCopy, toolNode) {
69
+ const tried = [];
70
+ const cands = [
71
+ ...(toolNode?.node && sqliteOk(toolNode.version) ? [{ node: toolNode.node, flags: [], label: `Node ${toolNode.version}` }] : []),
72
+ { node: process.execPath, flags: ['--experimental-sqlite'], label: `Node ${process.version} --experimental-sqlite` },
73
+ ];
74
+ for (const c of cands) {
75
+ tried.push(c.label);
76
+ try {
77
+ // A real 7 GB db took 6 s to count (#179 PC run): 5 s made backup and --undo refuse. 10 min covers far larger dbs.
78
+ const out = execFileSync(c.node, [...c.flags, '-e', COUNT_SCRIPT, dbCopy], { encoding: 'utf8', timeout: 600000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
79
+ if (/^\d+$/.test(out)) return { sessions: Number(out) }; // empty output is a failure, not 0
80
+ } catch (e) { if (e.code === 'ETIMEDOUT') tried[tried.length - 1] += ' (timed out)'; }
81
+ }
82
+ return { tried };
83
+ }
84
+
41
85
  // OpenCode: major from the config shape (2.x: mcp.servers / plugins; 1.x: flat mcp / plugin), data folder, db size, session count read from a COPY.
42
- export async function opencodeInfo(home, env, fsx = fs) {
86
+ // `opts.toolNode` ({version, node}): where the count runs when this Node lacks node:sqlite; `opts.sqliteImport` lets tests hide node:sqlite.
87
+ export async function opencodeInfo(home, env, fsx = fs, { toolNode = null, sqliteImport = () => import('node:sqlite') } = {}) {
43
88
  const cfgFile = configPath(j(configHome(home), 'opencode'));
44
89
  const cfg = readJson(cfgFile);
45
90
  const major = !cfg ? null : cfg.mcp?.servers || cfg.plugins ? 2 : 1; // VERIFY with `opencode --version` in real-adopt
@@ -48,11 +93,17 @@ export async function opencodeInfo(home, env, fsx = fs) {
48
93
  const dbBytes = dbs.reduce((n, f) => n + fsx.statSync(j(dataDir, f)).size, 0);
49
94
  const out = { major, dataDir, dbBytes, sessions: null };
50
95
  if (!dbs.includes('opencode.db')) return { ...out, note: 'no opencode.db' };
51
- let sqlite;
52
- try { sqlite = await import('node:sqlite'); } catch { return { ...out, note: 'node:sqlite is not available on this Node: sessions not counted' }; }
96
+ let sqlite = null;
97
+ try { sqlite = await sqliteImport(); } catch { /* counted in a child below */ }
53
98
  const tmp = fs.mkdtempSync(j(os.tmpdir(), 'lean-adopt-'));
54
99
  try {
55
100
  for (const f of dbs) fs.copyFileSync(j(dataDir, f), j(tmp, f));
101
+ if (!sqlite) {
102
+ const c = countInChild(j(tmp, 'opencode.db'), toolNode);
103
+ if (c.tried) out.note = `node:sqlite is not available on this Node: sessions not counted (tried ${c.tried.join(', ')})`;
104
+ else out.sessions = c.sessions;
105
+ return out;
106
+ }
56
107
  const db = new sqlite.DatabaseSync(j(tmp, 'opencode.db'), { readOnly: true });
57
108
  try { out.sessions = Number(db.prepare('SELECT count(*) AS n FROM session').get().n); } finally { db.close(); }
58
109
  } catch (e) { out.note = `sessions not counted: ${String(e.message).split('\n')[0]}`; } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
@@ -111,6 +162,29 @@ export async function inventory({ home, env = process.env, platform = process.pl
111
162
  }
112
163
  }
113
164
  }
165
+ // --- Cursor: hooks.json, {version, hooks: {event: [{command}]}} (cursor.com/docs/hooks, read 2026-11-13). Encoded payloads are never printed.
166
+ const cursorHooks = j(home, '.cursor', 'hooks.json');
167
+ const ch = readJson(cursorHooks);
168
+ const orcaFile = orcaHooksFound(home).includes(cursorHooks);
169
+ const seenCursor = new Map();
170
+ for (const [event, hooks] of Object.entries(ch?.hooks && typeof ch.hooks === 'object' ? ch.hooks : {})) {
171
+ for (const h of Array.isArray(hooks) ? hooks : []) {
172
+ if (typeof h?.command !== 'string') continue;
173
+ const argv = (h.command.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((a) => a.replace(/^(["'])(.*)\1$/, '$2'));
174
+ while (argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0])) argv.shift();
175
+ if (!argv.length) continue;
176
+ const encoded = cursorEncoded(h.command);
177
+ // Only an absolute path can carry the mark: a bare `rtk` would resolve against the cwd.
178
+ const script = !encoded && path.isAbsolute(argv[0]) ? argv[0] : null;
179
+ // RTK and GSD write their own Cursor hooks without the mark, so the name match counts too (#199).
180
+ const managed = !encoded && (cursorNameManaged(h.command, argv) || (Boolean(script) && fsx.existsSync(script) && hasMark(readJsonText(script) ?? '')));
181
+ const base = `${event}:${encoded ? 'powershell' : cursorHookLabel(h.command, argv)}`;
182
+ // Same event and label twice (#198): the second gets `#2`, the third `#3`.
183
+ const n = seenCursor.get(base) ?? 0;
184
+ seenCursor.set(base, n + 1);
185
+ add({ client: 'cursor', kind: 'hook', name: n ? `${base}#${n + 1}` : base, file: cursorHooks, keyPath: ['hooks', event], owner: managed ? 'managed' : 'user', extra: encoded && orcaFile ? { note: 'Orca agent status hook' } : undefined });
186
+ }
187
+ }
114
188
  const installed = readJson(j(home, '.claude', 'plugins', 'installed_plugins.json')); // VERIFY: name and shape, proven in real-adopt
115
189
  const have = installed && typeof installed.plugins === 'object' ? installed.plugins : null;
116
190
  for (const [key, on] of Object.entries(cs.enabledPlugins ?? {})) {
@@ -128,7 +202,9 @@ export async function inventory({ home, env = process.env, platform = process.pl
128
202
  try { target = spec.startsWith('file://') ? fileURLToPath(spec) : null; } catch { /* not a local file URL */ }
129
203
  if (target && !fsx.existsSync(target)) status.push('stale');
130
204
  if (/context-mode/.test(spec) && names.has('opencode\0context-mode')) status.push('duplicate'); // plugin and MCP; the MCP row gets the same mark below
131
- add({ client: 'opencode', kind: 'plugin', name: spec.replace(/^file:\/\/.*[\\/]/, 'file:').replace(/\/\/[^/@\s]*@/, '//').replace(/[?#].*$/, ''), file, keyPath: [key], owner: !target && MANAGED_PLUGIN.test(spec) ? 'managed' : 'user', status });
205
+ // a local plugin is named `<folder>/<file>`: two `tui.js` in different folders stay distinct
206
+ const name = target ? `${path.basename(path.dirname(target))}/${path.basename(target)}` : spec.replace(/\/\/[^/@\s]*@/, '//').replace(/[?#].*$/, '');
207
+ add({ client: 'opencode', kind: 'plugin', name, file, keyPath: [key], owner: !target && MANAGED_PLUGIN.test(spec) ? 'managed' : 'user', status, extra: target ? { source: rel(target) } : {} });
132
208
  };
133
209
  for (const [file, keys] of [[ocCfg, ['plugin', 'plugins']], [j(ocDir, 'tui.json'), ['plugin']], [j(ocDir, 'tui.jsonc'), ['plugin']]]) {
134
210
  const c = readJson(file);
@@ -136,6 +212,7 @@ export async function inventory({ home, env = process.env, platform = process.pl
136
212
  }
137
213
  const pdir = j(ocDir, 'plugins');
138
214
  for (const e of fsx.existsSync(pdir) ? fsx.readdirSync(pdir, { withFileTypes: true }) : []) {
215
+ if (e.name.startsWith('.') || e.name === 'node_modules' || (!e.isDirectory() && !/\.[cm]?[jt]s$/.test(e.name))) continue; // package.json and friends are not plugins
139
216
  const f = j(pdir, e.name);
140
217
  let owned = false;
141
218
  if (e.isFile()) { try { owned = hasMark(fs.readFileSync(f, 'utf8')); } catch { /* unreadable: user */ } }
@@ -149,21 +226,38 @@ export async function inventory({ home, env = process.env, platform = process.pl
149
226
 
150
227
  // --- Skills in every folder some agent reads
151
228
  const dirs = [...new Set(['claude', 'opencode', 'cursor', 'copilot'].flatMap((a) => skillDirs(a, home)))];
152
- const dupDirs = new Map();
153
- for (const a of ['claude', 'opencode', 'cursor', 'copilot']) for (const d of duplicateSkills(skillDirs(a, home), fsx)) dupDirs.set(d.name, d);
229
+ // A skill is a duplicate only in the folders one client reads together (#176); links count, a client scanning both paths meets it twice.
230
+ const dupRows = new Map(); // `${folder}\0${name}` -> { clients, copies: { folder: short sha }, differs, linked }
231
+ for (const a of ['claude', 'opencode', 'cursor', 'copilot']) {
232
+ for (const d of duplicateSkills(skillDirs(a, home), fsx, { links: true })) {
233
+ const group = d.dirs.map((x, i) => ({ dir: x, sha: d.shas[i] }));
234
+ for (const g of group) {
235
+ const row = dupRows.get(`${g.dir}\0${d.name}`) ?? { clients: [], copies: {}, differs: false, linked: false };
236
+ if (!row.clients.includes(a)) row.clients.push(a);
237
+ for (const x of group) row.copies[rel(x.dir)] = x.sha === 'unreadable' ? x.sha : x.sha.slice(0, 8);
238
+ row.differs ||= d.differs; row.linked ||= d.linked;
239
+ dupRows.set(`${g.dir}\0${d.name}`, row);
240
+ }
241
+ }
242
+ }
154
243
  for (const d of dirs) {
155
244
  let list = [];
156
245
  try { list = fsx.readdirSync(d).filter((n) => fsx.existsSync(j(d, n, 'SKILL.md'))); } catch { continue; }
157
246
  for (const name of list) {
158
- const dup = dupDirs.get(name);
159
- add({ client: 'skills', kind: 'skill', name, file: j(d, name), owner: MANAGED_SKILLS.has(name) ? 'managed' : 'user', status: dup ? ['duplicate'] : [], extra: dup ? { copies: dup.dirs.map(rel), differs: dup.differs } : {} });
247
+ const dup = dupRows.get(`${d}\0${name}`);
248
+ const fix = dup && `keep one folder (e.g. ~/.agents/skills) and delete the other copy after a backup${dup.linked ? '; the copies are links, so remove the extra link, not the folder it points to' : ''}${Object.keys(dup.copies).includes('~/.claude/skills') ? '; Claude Code reads only ~/.claude/skills' : ''}`;
249
+ add({ client: 'skills', kind: 'skill', name, file: j(d, name), owner: MANAGED_SKILLS.has(name) ? 'managed' : 'user', status: dup ? ['duplicate'] : [], extra: dup ? { copies: Object.keys(dup.copies), hashes: dup.copies, clients: dup.clients.sort(), differs: dup.differs, linked: dup.linked, fix } : {} });
160
250
  }
161
251
  }
162
252
 
253
+ // --- Antigravity IDE folders and VS Code extension: listed, never changed (#216)
254
+ for (const f of antigravityFootprint(home, fsx)) add({ client: 'antigravity', kind: 'ide', name: f.name, file: f.file, owner: 'user' });
255
+
163
256
  // --- npm copies under each nvm Node, and the one Node the tools should use
164
257
  const nvm = findNvm({ env, home, platform, realHome });
165
258
  const copies = nvm ? npmCopies(nvm) : [];
166
- const toolPins = Object.fromEntries([...new Set(items.map((i) => i.pin).filter(Boolean))].map((k) => [k, PINS[k]]));
259
+ // The npm copies count too: a context-mode copy with no context-mode MCP still needs its Node floor (#179 PC run).
260
+ const toolPins = Object.fromEntries([...new Set([...items.map((i) => i.pin), ...copies.map((c) => c.pin)].filter(Boolean))].map((k) => [k, PINS[k]]));
167
261
  // active '0.0.0': the question is which Node the tools should run on, whatever Node runs this command.
168
262
  const r = resolveToolNodes({ pins: toolPins, active: '0.0.0', nvm, latest: null });
169
263
  const ranges = Object.values(toolPins).map((p) => p.node).filter(Boolean);
@@ -176,8 +270,12 @@ export async function inventory({ home, env = process.env, platform = process.pl
176
270
  for (const c of copies) byPin.set(c.pin, [...(byPin.get(c.pin) ?? []), c]);
177
271
  for (const c of copies) {
178
272
  const status = [];
179
- if (PINS[c.pin].version !== c.version) status.push('drift');
180
- if (byPin.get(c.pin).length > 1) status.push('duplicate');
273
+ const cmp = cmpVersion(c.version, PINS[c.pin].version);
274
+ if (cmp < 0) status.push('drift');
275
+ else if (cmp > 0) status.push('newer'); // newer than the pin: nothing to upgrade
276
+ const dup = byPin.get(c.pin).length > 1;
277
+ if (dup) status.push('duplicate');
278
+ if (dup && !satisfies(c.node, PINS[c.pin].node)) status.push('below-floor'); // this copy cannot run: it is a removal, not an upgrade
181
279
  add({ client: 'npm', kind: 'npm', name: `${c.name}@${c.version}`, file: c.prefix, owner: 'managed', status, pin: c.pin, wanted: PINS[c.pin].version, extra: { node: c.node } });
182
280
  }
183
281
 
@@ -189,33 +287,64 @@ export async function inventory({ home, env = process.env, platform = process.pl
189
287
  const s = it.status;
190
288
  if (it.owner === 'user') it.action = s.includes('stale') || s.includes('duplicate') ? 'ask' : 'keep';
191
289
  else if (s.includes('wrong-node')) it.action = 'reinstall';
290
+ else if (s.includes('below-floor')) it.action = 'remove';
192
291
  else if (s.includes('drift')) it.action = 'upgrade';
193
292
  else if (s.includes('stale')) it.action = 'remove';
194
293
  else if (s.includes('duplicate')) it.action = it.kind === 'skill' || it.kind === 'plugin' || it.kind === 'mcp' ? 'ask' : it.kind === 'npm' ? (tn && it.node !== tn.version ? 'remove' : 'keep') : 'remove';
195
294
  }
196
- const oc = await opencodeInfo(home, env, fsx);
197
- const plan = items.filter((i) => i.action !== 'keep').map((i) => `${i.action} ${i.client} ${i.kind} ${i.name} (${i.status.join(', ') || i.owner})`);
295
+ const oc = await opencodeInfo(home, env, fsx, { toolNode: tn });
296
+ // Linked skill copies: --yes skips them (it never deletes a link target), so they are not plan steps (#226).
297
+ const byLink = (i) => i.kind === 'skill' && i.linked && i.status.includes('duplicate');
298
+ const plan = items.filter((i) => i.action !== 'keep' && !byLink(i)).map((i) => `${i.action} ${i.client} ${i.kind} ${i.name} (${i.status.join(', ') || i.owner})`);
198
299
  for (const s of stopgaps) if (s.replaceWith) plan.push(`ask ${s.file}: replace with ${s.replaceWith}`);
199
- return { version: 1, os: platform, toolNode, items, opencode: { ...oc, dataDir: rel(oc.dataDir) }, stopgaps, plan, ok: !items.some((i) => i.action !== 'keep') };
300
+ const links = {};
301
+ for (const i of items.filter(byLink)) for (const c of i.copies) (links[i.name] ??= new Set()).add(c);
302
+ const byHand = Object.entries(links).map(([n, c]) => `skill ${n}: remove the extra link, keep one folder (${[...c].join(', ')})`);
303
+ return { version: 1, os: platform, toolNode, items, opencode: { ...oc, dataDir: rel(oc.dataDir) }, stopgaps, plan, byHand, health: pluginHealth(home, { fsx }), ok: !items.some((i) => i.action !== 'keep') };
200
304
  }
201
305
 
202
306
  export async function adopt(o) {
203
307
  if (o.undo) return adoptUndo(o);
204
308
  if (o.yes && !o.dryRun && !o.json) return adoptApply(o);
205
309
  const r = await inventory(o);
310
+ if (o.probePlugins) r.health.push(...await probePlugins(o.home)); // opt-in: starts a short-lived opencode serve
311
+ // What --yes does (the apply plan, not only the inventory rows): the pin's target Node and the removals, which need a yes (#179 PC run).
312
+ const ap = adoptPlan(r, { home: o.home, env: o.env ?? process.env, platform: o.platform ?? process.platform, realHome: o.realHome ?? os.homedir(), state: readState(o.stateDir ?? j(o.home, '.config', 'lean-agents')) });
313
+ r.apply = applyLines(ap, o.home);
206
314
  if (o.json) { process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); return true; }
207
315
  const by = {};
208
316
  for (const i of r.items) by[`${i.kind}`] = (by[`${i.kind}`] ?? 0) + 1;
209
317
  console.log(`--adopt (dry run: nothing is changed; --yes applies). Found: ${Object.entries(by).map(([k, n]) => `${n} ${k}`).join(', ') || 'nothing'}`);
210
- console.log(`tool Node: ${r.toolNode.range ? `${r.toolNode.range} -> ${r.toolNode.node ?? 'no matching Node installed, nvm not found'} (${r.toolNode.source ?? 'none'})` : 'not needed'}`);
318
+ console.log(`tool Node: ${r.toolNode.range ? `${r.toolNode.range} -> ${r.toolNode.node ?? 'no installed Node meets it (install one with nvm)'} (${r.toolNode.source ?? 'none'})` : 'not needed'}`);
211
319
  console.log(`OpenCode: major ${r.opencode.major ?? 'none'}, ${r.opencode.dbBytes} bytes of db, sessions ${r.opencode.sessions ?? 'unknown'}${r.opencode.note ? ` (${r.opencode.note})` : ''}`);
212
- for (const i of r.items.filter((x) => x.action !== 'keep' || x.owner === 'managed')) console.log(` ${i.action.padEnd(9)} ${i.owner.padEnd(8)} ${i.client} ${i.kind} ${i.name}${i.status.length ? ` [${i.status.join(', ')}]` : ''}`);
320
+ for (const i of r.items.filter((x) => x.action !== 'keep' || x.owner === 'managed' || x.kind === 'hook' || x.kind === 'ide')) {
321
+ console.log(` ${i.action.padEnd(9)} ${i.owner.padEnd(8)} ${i.client} ${i.kind} ${i.name}${i.status.length ? ` [${i.status.join(', ')}]` : ''}${i.note ? ` (${i.note})` : ''} (${i.file})`);
322
+ if (i.kind === 'skill' && i.fix) console.log(` ${i.clients.join(' and ')} loads it twice: ${Object.entries(i.hashes).map(([d, h]) => `${d} ${h}`).join(', ')} (${i.differs ? 'differs' : 'identical'}); ${i.fix}`);
323
+ }
213
324
  console.log(` user-owned items kept untouched: ${r.items.filter((i) => i.owner === 'user' && i.action === 'keep').length}`);
325
+ for (const f of r.health) console.log(` health ${f.plugin || 'probe'} [${f.id}] ${f.line}\n fix: ${f.fix}`);
214
326
  for (const s of r.stopgaps) console.log(` stopgap ${s.file}${s.replaceWith ? `: replace with ${s.replaceWith}` : `: ${s.note}`}`);
215
327
  console.log(r.plan.length ? `Plan (${r.plan.length} steps; add --yes to apply, --confirm-removals to allow the removals):\n${r.plan.map((l) => ` - ${l}`).join('\n')}` : 'Plan: nothing to change.');
328
+ if (r.byHand.length) console.log(`Fix by hand (--yes leaves these):\n${r.byHand.map((l) => ` - ${l}`).join('\n')}`);
329
+ if (r.apply.length) console.log(`--yes does:\n${r.apply.map((l) => ` - ${l}`).join('\n')}`);
216
330
  return true;
217
331
  }
218
332
 
333
+ // One line per action adoptApply takes, in its order.
334
+ function applyLines(p, home) {
335
+ const rel = (f) => (f.startsWith(home) ? `~${f.slice(home.length)}` : f);
336
+ const yes = ' (needs a yes, or --confirm-removals)';
337
+ return [
338
+ ...(p.install ? [`install ${PINS['context-mode'].source}@${PINS['context-mode'].version} into Node ${p.install.node.version}${p.install.have ? ` (now ${p.install.have})` : ''}`] : []),
339
+ ...p.rewritten.map((w) => `re-register ${w.client} ${w.name} on Node ${p.tn.version} (${rel(w.file)})`),
340
+ ...[...p.edits.keys()].filter((f) => !p.rewritten.some((w) => w.file === f)).map((f) => `edit ${rel(f)} (remove stale keys of ours)`),
341
+ ...p.oldCopies.map((c) => `npm uninstall the old ${c.name}@${c.version} under Node ${c.node.version}${yes}`),
342
+ ...p.dupSkills.map((d) => `remove the duplicate skill folder ${rel(d)}${yes}`),
343
+ ...p.stopgaps.map((f) => `remove the stopgap ${rel(f)}${yes}`),
344
+ ...p.notes.map((n) => `note: ${n}`),
345
+ ];
346
+ }
347
+
219
348
  // ---------------------------------------------------------------------------------------------------------------------
220
349
  // Apply and undo (#106). Everything below writes, and only inside `home` and `stateDir`.
221
350
  const ROOT = fileURLToPath(new URL('../../', import.meta.url));
@@ -228,7 +357,7 @@ const relIn = (home, f) => (f.startsWith(home + path.sep) ? path.relative(home,
228
357
  // State file: --adopt adds `adopt` to an existing state.json, or creates one that only holds it (`adoptOnly`).
229
358
  const stateFile = (stateDir) => j(stateDir, 'state.json');
230
359
  const readState = (stateDir) => readJson(stateFile(stateDir));
231
- function saveState(stateDir, adoptState) {
360
+ export function saveState(stateDir, adoptState) {
232
361
  const st = readState(stateDir) ?? {
233
362
  version: JSON.parse(fs.readFileSync(j(ROOT, 'package.json'), 'utf8')).version, installedAt: new Date().toISOString(), pins: pinVersions(), adoptOnly: true,
234
363
  options: { migrateOnly: true, agents: [], tools: [], privacy: 'standard', gh: false, terminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' },
@@ -272,22 +401,34 @@ export function adoptPlan(r, { home, env, platform, realHome, state, fsx = fs })
272
401
  const p = it.kind === 'mcp' ? [...it.keyPath, it.name] : it.kind === 'plugin' && it.keyPath[0] === 'enabledPlugins' ? it.keyPath : null;
273
402
  if (p) addEdit(absOf(home, it.file), { path: p, mode: 'remove' });
274
403
  }
275
- // The pinned package in the tool Node's prefix.
276
- if (tn && out.rewritten.length) {
404
+ // The pinned package in the tool Node's prefix: needed by a rewritten MCP, or by a drift copy planned as `upgrade` (a copy on another Node is then removed below).
405
+ if (tn && (out.rewritten.length || r.items.some((i) => i.kind === 'npm' && i.pin === pin && i.action === 'upgrade'))) {
277
406
  let have = null;
278
407
  try { have = JSON.parse(fsx.readFileSync(j(tn.modules, 'context-mode', 'package.json'), 'utf8')).version; } catch { /* not installed there */ }
279
408
  if (have !== PINS[pin].version) out.install = { have, node: tn };
280
409
  }
410
+ if (!tn && r.toolNode.range && r.items.some((i) => i.kind === 'npm' && i.pin === pin && i.action === 'upgrade')) out.notes.push(`context-mode: no installed Node meets ${r.toolNode.range}; install one with nvm, then run --adopt again`);
281
411
  // (a) old npm copies under another Node; (b) a skill in both folders; stopgaps with their managed replacement installed.
282
- if (tn) for (const it of r.items) if (it.kind === 'npm' && it.status.includes('duplicate') && it.node !== tn.version) { const n = nodes.find((x) => x.version === it.node); if (n) out.oldCopies.push({ node: n, pin: it.pin, name: PINS[it.pin].source, version: it.name.replace(/^.*@/, '') }); }
412
+ // A copy on another Node becomes a duplicate once this run installs the pin into the tool Node: removed now, a second --adopt --yes is refused (#179 PC run).
413
+ // Not a newer copy, and not one a user's own MCP or hook still runs on.
414
+ const userOn = (v) => r.items.find((i) => i.owner === 'user' && i.launch?.nodeVersion === v);
415
+ if (tn) for (const it of r.items) {
416
+ if (it.kind !== 'npm' || it.node === tn.version) continue;
417
+ const replaced = out.install && it.pin === pin && !it.status.includes('newer');
418
+ if (!it.status.includes('duplicate') && !replaced) continue;
419
+ const u = !it.status.includes('duplicate') && userOn(it.node);
420
+ if (u) { out.notes.push(`${it.name} under Node ${it.node} stays: your ${u.client} ${u.name} runs on that Node`); continue; }
421
+ const n = nodes.find((x) => x.version === it.node); if (n) out.oldCopies.push({ node: n, pin: it.pin, name: PINS[it.pin].source, version: it.name.replace(/^.*@/, '') });
422
+ }
283
423
  const shared = j(home, '.agents', 'skills');
284
424
  const claude = j(home, '.claude', 'skills');
285
425
  const otherAgents = fsx.existsSync(j(home, '.cursor')) || fsx.existsSync(envDir(home, 'COPILOT_HOME', j(home, '.copilot')));
286
426
  for (const name of new Set(r.items.filter((i) => i.kind === 'skill' && i.status.includes('duplicate')).map((i) => i.name))) {
287
427
  const drop = j(shared, name);
288
428
  // Keep the copy in ~/.claude/skills (Claude reads only that folder, OpenCode reads both); Cursor and Copilot read only ~/.agents/skills, so with them present nothing is removed.
289
- if (fsx.existsSync(j(claude, name, 'SKILL.md')) && fsx.existsSync(j(drop, 'SKILL.md')) && !otherAgents) out.dupSkills.push(drop);
290
- else out.notes.push(`skill ${name} stays in both folders (${otherAgents ? 'Cursor or Copilot read only ~/.agents/skills' : 'the copies are not the ~/.agents and ~/.claude pair'}); keep one by hand`);
429
+ const linked = r.items.some((i) => i.kind === 'skill' && i.name === name && i.linked);
430
+ if (fsx.existsSync(j(claude, name, 'SKILL.md')) && fsx.existsSync(j(drop, 'SKILL.md')) && !otherAgents && !linked) out.dupSkills.push(drop);
431
+ else out.notes.push(`skill ${name} stays in both folders (${linked ? 'the copies are links to one folder' : otherAgents ? 'Cursor or Copilot read only ~/.agents/skills' : 'the copies are not the ~/.agents and ~/.claude pair'}); keep one by hand`);
291
432
  }
292
433
  const have = (need) => Object.entries(need).every(([k, v]) => (state?.options?.[k] ?? []).includes(v));
293
434
  for (const sg of STOPGAPS) {
@@ -405,7 +546,7 @@ export async function adoptApply(o) {
405
546
  } else console.log(' verify: initialize skipped (--no-exec)');
406
547
  const after = userSnapshot(r, home, new Set());
407
548
  for (const [k, v] of user) if (after.get(k) !== v) bad.push(`a user-owned item changed: ${k.split('\0')[0].replace(home, '~')}`);
408
- const oc = await opencodeInfo(home, env, fs);
549
+ const oc = await opencodeInfo(home, env, fs, { toolNode: p.tn });
409
550
  if (oc.sessions !== sessions) bad.push(`OpenCode sessions ${sessions} -> ${oc.sessions}`);
410
551
  if (bad.length) return fail(bad.join('; '));
411
552
  const dr = doctor({ home, state: readState(stateDir), exec: false, env, platform, json: false });
@@ -466,8 +607,12 @@ export async function adoptUndo(o) {
466
607
  }
467
608
  if (!ok) { console.log(`Undone with problems; the record and backup stay so you can retry: ${a.backupDir ?? '(no backup)'}`); return false; }
468
609
  if (a.backupDir) dropBackups(a.backupDir);
469
- if (st.adoptOnly) fs.rmSync(stateFile(stateDir));
470
- else { delete st.adopt; writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`); }
610
+ delete st.adopt;
611
+ const isBare = st.adoptOnly && (!st.files || st.files.length === 0) && (!st.commands || st.commands.length === 0) && !st.opencode1 && !st.upgrade;
612
+ if (isBare) fs.rmSync(stateFile(stateDir));
613
+ else {
614
+ writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`);
615
+ }
471
616
  try { fs.rmdirSync(stateDir); } catch { /* other lean-agents files live there */ }
472
617
  console.log(ok ? 'Undone.' : 'Undone, with the problems above.');
473
618
  return ok;