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
@@ -6,40 +6,56 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { PINS, npmSpec } from './pins.mjs';
9
+ import { PINS } from './pins.mjs';
10
10
  import { sha256 } from './verify-sha256.mjs';
11
- import { run, which, version, antigravityPrereqs, packageManager } from './system.mjs';
11
+ import { run, which, version, antigravityPrereqs, packageManager, agyCandidates, BREW_AGY_LIMIT } from './system.mjs';
12
12
  import { writePrivate, privateDir } from './fsops.mjs';
13
+ import { winPathDefault } from './opencode1.mjs';
14
+ import { gitBashPath } from './terminals.mjs';
13
15
 
14
16
  const VERIFY = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
15
- export const LIFECYCLE_AGENTS = ['claude', 'opencode-v2', 'copilot-cli', 'cursor', 'antigravity'];
17
+ export const LIFECYCLE_AGENTS = ['claude', 'opencode-v2', 'copilot-cli', 'cursor', 'antigravity', 'vscode-copilot'];
18
+ export const AGENT_CLIS = { claude: 'claude', 'opencode-v2': 'opencode', 'copilot-cli': 'copilot', cursor: 'agent', antigravity: 'agy' };
19
+ const VSCODE = 'vscode-copilot';
20
+ // VS Code owns the extension, so for vscode-copilot "install" only writes the adapter's files (the engine does it through o.vscode).
21
+ export const VSCODE_NOTE = 'VS Code owns the GitHub Copilot extension: lean-agents never installs, updates or removes it. Install the extension and update it from VS Code (Extensions view).';
16
22
 
17
23
  // Pinned installer script: curl, verify, run. `args` go to the script (a version for Claude and OpenCode).
18
- function script(pinKey, dir, args = []) {
24
+ function script(pinKey, dir, args = [], ext = '.sh') {
19
25
  const p = PINS[pinKey];
20
- const file = path.join(dir, `${pinKey}.sh`);
21
- return { version: null, download: file, run: [['curl', '-fsSL', '-o', file, p.url], [process.execPath, VERIFY, file, p.sha256], ['bash', file, ...args]] };
26
+ const file = path.join(dir, `${pinKey}${ext}`);
27
+ return { version: null, download: file, run: [[ext === '.ps1' ? 'curl.exe' : 'curl', '-fsSL', '-o', file, p.url], [process.execPath, VERIFY, file, p.sha256], ext === '.ps1' ? ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', file, ...args] : ['bash', file, ...args]] };
22
28
  }
23
29
 
24
30
  // One row per agent for this OS: how it is installed, where its binary lands and which dirs the install may write to.
25
31
  // `manual` is a reason, not a command: that agent/OS route is not proven yet (VERIFY in docs/compatibility.md).
26
- export function agentTable({ home, platform, dir, realHome }) {
32
+ // `ver`: version per pin key to install instead of the release pin (the saved previous version, for an undo).
33
+ // gitBash: plan as if Git Bash were there (--everything installs Git first; the run builds the table again with the real path).
34
+ export function agentTable({ home, platform, dir, realHome, ver = {}, env = process.env, gitBash }) {
35
+ const at = (key) => ver[key] ?? PINS[key].version;
27
36
  const posix = platform !== 'win32';
28
- const cmds = { claude: 'claude', 'opencode-v2': 'opencode', 'copilot-cli': 'copilot', cursor: 'agent', antigravity: 'agy' };
37
+ const cmds = AGENT_CLIS;
29
38
  const local = path.join(home, '.local');
30
39
  const bin = (...n) => n.map((x) => path.join(local, 'bin', x));
31
40
  const prefix = home === realHome ? [] : ['--prefix', local];
32
41
  const t = {};
33
42
  t.claude = posix
34
- ? { method: 'script', ...script('claude-installer', dir, [PINS['claude-code'].version]), bins: bin('claude'), dirs: [path.join(local, 'bin'), path.join(local, 'share', 'claude'), path.join(home, '.claude', 'downloads')] }
35
- : { manual: 'Claude Code on Windows (claude.ai/install.ps1): not proven yet. VERIFY' };
43
+ ? { method: 'script', ...script('claude-installer', dir, [at('claude-code')]), bins: bin('claude'), dirs: [path.join(local, 'bin'), path.join(local, 'share', 'claude'), path.join(home, '.claude', 'downloads')] }
44
+ : { method: 'script', ...script('claude-installer-win', dir, [at('claude-code')], '.ps1'), bins: bin('claude.exe'), dirs: [path.join(local, 'bin'), path.join(local, 'share', 'claude'), path.join(home, '.claude', 'downloads')], pathDir: path.join(local, 'bin') };
45
+ const bashExe = gitBashPath({ platform, env }) ?? gitBash;
36
46
  t['opencode-v2'] = posix
37
47
  // --no-modify-path: the installer must not edit ~/.bashrc, which we could not undo.
38
- ? { method: 'script', ...script('opencode-installer', dir, ['--version', PINS['opencode-v2'].version, '--no-modify-path']), bins: [path.join(home, '.opencode', 'bin', 'opencode')], dirs: [path.join(home, '.opencode')] }
39
- : { manual: 'OpenCode 2 on Windows (Git Bash installer): install-dir and PATH not proven yet. VERIFY' };
48
+ ? { method: 'script', ...script('opencode-installer', dir, ['--version', at('opencode-v2'), '--no-modify-path']), bins: [path.join(home, '.opencode', 'bin', 'opencode')], dirs: [path.join(home, '.opencode')] }
49
+ : (bashExe ? (() => {
50
+ const sc = script('opencode-installer', dir, ['--version', at('opencode-v2'), '--no-modify-path']);
51
+ sc.run[0][0] = 'curl.exe';
52
+ sc.run[2][0] = bashExe;
53
+ // Git Bash takes HOME from the environment, which can differ from --home: the installer writes to $HOME/.opencode.
54
+ return { method: 'script', ...sc, env: { HOME: home }, bins: [path.join(home, '.opencode', 'bin', 'opencode.exe')], dirs: [path.join(home, '.opencode')], pathDir: path.join(home, '.opencode', 'bin'), pathFirst: true };
55
+ })() : { manual: 'OpenCode 2 on Windows needs Git for Windows (Git Bash): install it, then run this again' });
40
56
  t['copilot-cli'] = {
41
- method: 'npm', version: PINS['copilot-cli'].version,
42
- run: [['npm', 'install', '-g', ...prefix, npmSpec('copilot-cli')]], uninstall: [['npm', 'uninstall', '-g', ...prefix, PINS['copilot-cli'].source]],
57
+ method: 'npm', version: at('copilot-cli'),
58
+ run: [['npm', 'install', '-g', ...prefix, `${PINS['copilot-cli'].source}@${at('copilot-cli')}`]], uninstall: [['npm', 'uninstall', '-g', ...prefix, PINS['copilot-cli'].source]],
43
59
  bins: prefix.length ? (posix ? [path.join(local, 'bin', 'copilot')] : [path.join(local, 'copilot.cmd')]) : [], dirs: [],
44
60
  };
45
61
  t.cursor = posix
@@ -48,7 +64,7 @@ export function agentTable({ home, platform, dir, realHome }) {
48
64
  if (platform === 'darwin' && packageManager() === 'brew') {
49
65
  // The engine's own Antigravity install (antigravityPrereqs); brew removes what it installed.
50
66
  const c = antigravityPrereqs('brew', platform, home, false).find((x) => x.run.length);
51
- t.antigravity = { method: 'brew', version: null, run: c?.run ?? [], uninstall: [['brew', 'uninstall', '--cask', 'antigravity-cli']], bins: [], dirs: [] };
67
+ t.antigravity = { method: 'brew', version: null, run: c?.run ?? [], uninstall: [['brew', 'uninstall', '--cask', 'antigravity-cli']], bins: [], dirs: [], unpinned: BREW_AGY_LIMIT };
52
68
  } else {
53
69
  t.antigravity = posix
54
70
  ? { method: 'script', ...script('antigravity-installer', dir), bins: bin('agy'), dirs: [path.join(local, 'bin'), path.join(local, 'share'), path.join(home, '.antigravity'), path.join(home, '.gemini')] }
@@ -101,26 +117,55 @@ export function removeRecorded(home, rec) {
101
117
  }
102
118
 
103
119
  const stateFile = (stateDir) => path.join(stateDir, 'agents.json');
120
+ // agent -> installedAt of its agents.json entry: the stamp an upgrade record is tied to (#284).
121
+ export const agentStamps = (stateDir) => Object.fromEntries(Object.entries(readAgents(stateDir).agents).map(([a, r]) => [a, r.installedAt ?? '']));
122
+ // --install-agent / --uninstall-agent end the version history of an agent: its upgrade records would undo onto a stale install.
123
+ function dropUpgradeRecords(stateDir, a) {
124
+ const file = path.join(stateDir, 'state.json');
125
+ if (!fs.existsSync(file)) return;
126
+ const s = JSON.parse(fs.readFileSync(file, 'utf8'));
127
+ if (!s.commands?.some((c) => c.reinstall && agentOf(c) === a)) return;
128
+ s.commands = s.commands.filter((c) => !(c.reinstall && agentOf(c) === a));
129
+ writePrivate(file, `${JSON.stringify(s, null, 2)}\n`);
130
+ }
104
131
  const readAgents = (stateDir) => (fs.existsSync(stateFile(stateDir)) ? JSON.parse(fs.readFileSync(stateFile(stateDir), 'utf8')) : { agents: {} });
105
132
 
106
- // o: { mode: 'install'|'uninstall', agents, home, realHome, platform, stateDir, dryRun, exec, yes, ask, yesNo }
133
+ // vscode-copilot: configure or remove the adapter's files only. o.vscode = { configured(), install(), uninstall() } comes from the engine.
134
+ async function vscodeLifecycle(o) {
135
+ const log = console.log;
136
+ log(`${VSCODE}: ${VSCODE_NOTE}`);
137
+ if (o.mode === 'install') {
138
+ if (o.vscode.configured()) log(`${VSCODE}: already configured by lean-agents; run --update to refresh it. Nothing done.`);
139
+ else await o.vscode.install();
140
+ } else if (!o.vscode.configured()) log(`${VSCODE}: not configured by lean-agents; nothing done.`);
141
+ else await o.vscode.uninstall();
142
+ }
143
+
144
+ // o: { mode: 'install'|'uninstall', fromUpgrade (only --upgrade-agent may install 2.x next to 1.x), agents, home, realHome, platform, stateDir, dryRun, exec, yes, ask, yesNo, vscode }
107
145
  export async function agentLifecycle(o) {
108
146
  const log = console.log;
147
+ const winPath = o.winPath ?? winPathDefault;
109
148
  for (const a of o.agents) {
110
149
  if (a === 'opencode-v1') throw new Error('opencode-v1 is never installed or removed by lean-agents (work PCs run 1.x on purpose, #79)');
111
150
  if (!LIFECYCLE_AGENTS.includes(a)) throw new Error(`cannot ${o.mode} "${a}" (available: ${LIFECYCLE_AGENTS.join(', ')})`);
112
151
  }
152
+ if (o.agents.includes(VSCODE)) await vscodeLifecycle(o);
153
+ const agents = o.agents.filter((a) => a !== VSCODE);
113
154
  const state = readAgents(o.stateDir);
114
- const table = o.table ?? agentTable({ home: o.home, platform: o.platform ?? process.platform, dir: o.stateDir, realHome: o.realHome });
155
+ const platform = o.platform ?? process.platform;
156
+ const table = o.table ?? agentTable({ home: o.home, platform, dir: o.stateDir, realHome: o.realHome, env: o.env ?? process.env });
115
157
  const todo = [];
116
- for (const a of o.agents) {
158
+ for (const a of agents) {
117
159
  const row = table[a];
118
160
  const mine = state.agents[a];
119
161
  if (o.mode === 'install') {
120
162
  if (mine) log(`${a}: already installed by lean-agents (${mine.method}); nothing to do.`);
163
+ // #211: a working agy outside PATH (Windows installer folders) counts too; never installed over.
164
+ else if (a === 'antigravity' && agyCandidates(o.home, platform, o.home === o.realHome ? process.env : {}).some((c) => fs.existsSync(c))) log(`${a}: already installed, not by lean-agents; left alone.`);
121
165
  else if (row.manual) log(`${a}: ${row.manual}`);
122
- else if (row.bins.some((b) => fs.existsSync(b)) || ((o.home === o.realHome || row.method === 'brew') && which(row.cmd))) log(`${a}: already installed, not by lean-agents; left alone.`);
123
- else if (a === 'opencode-v2' && version('opencode')?.startsWith('1.')) log('opencode-v2: OpenCode 1.x is on PATH; lean-agents never installs 2.x next to it here (#79). Nothing done.');
166
+ // --upgrade-agent installs 2.x over a 1.x it already copied out and sha256-checked, so the 1.x binary being there is expected.
167
+ else if (!(o.fromUpgrade && a === 'opencode-v2') && (row.bins.some((b) => fs.existsSync(b)) || ((o.home === o.realHome || row.method === 'brew') && which(row.cmd)))) log(`${a}: already installed, not by lean-agents; left alone.`);
168
+ else if (a === 'opencode-v2' && !o.fromUpgrade && version('opencode')?.startsWith('1.')) log('opencode-v2: OpenCode 1.x is on PATH; lean-agents never installs 2.x next to it here (#79). Nothing done.');
124
169
  else todo.push(a);
125
170
  } else if (!mine) log(`${a}: not installed by lean-agents; nothing done.`);
126
171
  else todo.push(a);
@@ -131,8 +176,10 @@ export async function agentLifecycle(o) {
131
176
  log(` - ${a}${o.mode === 'install' ? ` (${table[a].method}${table[a].version ? ` ${table[a].version}` : ''})` : ` (${state.agents[a].files.length} recorded files${state.agents[a].uninstall ? ', npm/brew uninstall' : ''})`}`);
132
177
  for (const argv of o.mode === 'install' ? table[a].run : state.agents[a].uninstall ?? []) log(` $ ${argv.join(' ')}`);
133
178
  }
179
+ for (const a of todo) if (o.mode === 'install' && table[a].unpinned) log(` ! ${a}: ${table[a].unpinned}`);
134
180
  if (o.dryRun || !o.exec) { log(o.dryRun ? 'Dry run: nothing was changed.' : '--no-exec: nothing was run.'); return; }
135
- if (!o.yesNo(await o.ask(o.mode === 'install' ? 'Download and run these installers?' : 'Remove these agents?', o.yes ? 'y' : 'n'))) { log('Cancelled.'); return; }
181
+ const unpinned = o.mode === 'install' && todo.some((a) => table[a].unpinned);
182
+ if (!o.yesNo(await o.ask(o.mode === 'install' ? `Download and run these installers${unpinned ? ' (some are not pinned, see above)' : ''}?` : 'Remove these agents?', o.yes ? 'y' : 'n'))) { log('Cancelled.'); return; }
136
183
  privateDir(o.stateDir, o.stateDir);
137
184
  fs.mkdirSync(o.stateDir, { recursive: true });
138
185
  const env = {};
@@ -140,24 +187,94 @@ export async function agentLifecycle(o) {
140
187
  if (o.mode === 'install') {
141
188
  const row = table[a];
142
189
  const before = snapshot(row.dirs);
143
- const ok = row.run.every((argv) => run(argv, { dryRun: false, log, env }));
190
+ let pathDir = null;
191
+ let pathAbsent = false;
192
+ if (platform === 'win32' && row.pathDir) {
193
+ pathDir = row.pathDir;
194
+ pathAbsent = winPath('has', pathDir) === 'absent';
195
+ }
196
+ const ok = row.run.every((argv) => run(argv, { dryRun: false, log, env: { ...env, ...row.env } }));
144
197
  if (row.download) fs.rmSync(row.download, { force: true });
145
198
  const rec = diffSnapshots(before, snapshot(row.dirs));
199
+ let pathEntry = false;
200
+ if (pathDir && pathAbsent && winPath('has', pathDir) === 'present') {
201
+ pathEntry = true;
202
+ // The Windows installers (Claude bootstrap.ps1, OpenCode under Git Bash) do not put their bin folder on PATH (#179, 2026-11-19).
203
+ } else if (ok && pathDir && pathAbsent && row.bins.some((b) => fs.existsSync(b))) {
204
+ let added = false;
205
+ try { added = winPath(row.pathFirst ? 'prepend' : 'add', pathDir) === 'changed'; } catch (e) { log(` ! could not add ${pathDir} to your user PATH (${e.message.split('\n')[0]}); add it by hand`); }
206
+ if (added) {
207
+ pathEntry = true;
208
+ log(` ${'added to PATH'.padEnd(24)} ${pathDir} (open a new terminal)`);
209
+ }
210
+ }
146
211
  if (!ok) {
147
212
  log(` ! ${a}: install failed. Run the commands above by hand.`);
148
213
  process.exitCode = 1;
149
214
  // Keep what a half-run installer left, so --uninstall-agent can clean it.
150
- if (!rec.files.length && !rec.dirs.length) continue;
215
+ if (!rec.files.length && !rec.dirs.length && !pathEntry) continue;
151
216
  }
152
217
  state.agents[a] = { method: row.method, version: row.version, installedAt: new Date().toISOString(), uninstall: row.uninstall ?? null, ...rec };
218
+ if (pathEntry) state.agents[a].pathEntryDir = pathDir;
153
219
  log(`${a}: installed; ${rec.files.length} files recorded.`);
154
220
  } else {
155
221
  const rec = state.agents[a];
156
222
  if (rec.uninstall && !rec.uninstall.every((argv) => run(argv, { dryRun: false, log, env }))) { log(` ! ${a}: uninstall failed. Run the command above by hand.`); process.exitCode = 1; continue; }
157
223
  for (const [what, file] of removeRecorded(o.home, rec)) log(` ${what.padEnd(24)} ${file}`);
224
+ if (rec.pathEntryDir && platform === 'win32') {
225
+ if (winPath('remove', rec.pathEntryDir) === 'changed') log(` ${'removed from PATH'.padEnd(24)} ${rec.pathEntryDir}`);
226
+ }
158
227
  delete state.agents[a];
159
228
  log(`${a}: removed. Your config and data were not touched.`);
160
229
  }
161
230
  writePrivate(stateFile(o.stateDir), `${JSON.stringify(state, null, 2)}\n`);
231
+ dropUpgradeRecords(o.stateDir, a);
232
+ }
233
+ }
234
+
235
+ // --update (#182): the commands that move an agent CLI lean-agents installed to the release pin, one per plan row with
236
+ // action 'update' (planUpdate already holds OpenCode 1.x, other majors and CLIs the user installed). `reinstall` is the same
237
+ // installer at the version it had, saved in state.json next to the command; undoUpgrades() runs it.
238
+ // Cursor and Antigravity have no version pin, so they never get a row and are not moved (VERIFY in docs/compatibility.md).
239
+ const UPGRADE = { 'claude-code': 'claude', 'opencode-v2': 'opencode-v2', 'copilot-cli': 'copilot-cli' };
240
+ export function upgradeCommands({ rows, home, platform = process.platform, dir, realHome, stamps = {}, env = process.env }) {
241
+ const out = [];
242
+ for (const r of rows) {
243
+ const a = UPGRADE[r.tool];
244
+ if (!a || r.action !== 'update') continue;
245
+ const argvs = (ver) => { const row = agentTable({ home, platform, dir, realHome, ver: { [r.tool]: ver }, env })[a]; return row.manual ? null : row; };
246
+ const to = argvs(r.pinned);
247
+ const raw = r.raw ?? r.installed;
248
+ const from = { raw, row: argvs(raw) };
249
+ if (!to) { console.log(`! ${a}: ${agentTable({ home, platform, dir, realHome, env })[a].manual}`); continue; }
250
+ // The downloaded installer is removed by a final step that runs even when an earlier step failed.
251
+ const cleanup = (row) => (row.download ? [[process.execPath, '-e', "require('fs').rmSync(process.argv[1],{force:true})", row.download]] : []);
252
+ out.push({ tool: r.tool, desc: `upgrade ${a} ${from.raw} -> ${r.pinned}`, run: to.run, always: cleanup(to), undo: [], from: from.raw, owner: stamps[a] ?? null, reinstall: from.row.run, reinstallAlways: cleanup(from.row) });
253
+ }
254
+ return out;
255
+ }
256
+
257
+ // --update --undo: the first saved reinstall per agent. Commands are in run order, so that is the version before the oldest
258
+ // upgrade; replaying every record forward would end on the newest "previous" version. The agent is the 2nd word of the desc.
259
+ export const agentOf = (c) => c.desc.split(' ')[1];
260
+ // `stamps`: agentStamps(). A record keeps `owner`, the agents.json stamp when it was made (null: the user's own install). It
261
+ // replays only while that is still true: an agent lean-agents uninstalled or reinstalled since must not be brought back, but an
262
+ // upgrade of a CLI the user already had stays undoable. Records from before `owner` existed fall back to membership.
263
+ export function undoPlan(commands, stamps = null) {
264
+ const seen = new Set();
265
+ const current = (c) => (!stamps || ('owner' in c ? (c.owner ?? null) === (stamps[agentOf(c)] ?? null) : agentOf(c) in stamps));
266
+ return commands.filter((c) => c.reinstall && current(c) && !seen.has(agentOf(c)) && seen.add(agentOf(c)));
267
+ }
268
+
269
+ // Runs each plan step (a failed one is reported and the rest still run). Returns { ok, restored: agents back on their old version }.
270
+ export function undoUpgrades(commands, env = {}, stamps = null) {
271
+ const restored = new Set();
272
+ const plan = undoPlan(commands, stamps);
273
+ for (const c of plan) {
274
+ console.log(`- reinstall ${c.from} (undo of: ${c.desc})`);
275
+ const ok = c.reinstall.every((argv) => run(argv, { dryRun: false, log: console.log, env }));
276
+ for (const argv of c.reinstallAlways ?? []) run(argv, { dryRun: false, log: console.log, env });
277
+ if (ok) restored.add(agentOf(c)); else console.log(' ! failed. Run the command above by hand.');
162
278
  }
279
+ return { ok: plan.every((c) => restored.has(agentOf(c))), restored };
163
280
  }
@@ -0,0 +1,25 @@
1
+ // The verified-backup stamp that gates --upgrade-agent opencode apply (#80 part 2).
2
+ // `--backup` (opencode-backup.mjs) writes STAMP.json into the finished backup folder as its very last step, after the sha256, count and frozen-copy checks passed:
3
+ // a folder without it (a half-made or older backup) never opens the gate. `apply` re-verifies the files before it trusts the stamp.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { backupLayout, STAMP_FILE } from './opencode-backup.mjs';
7
+
8
+ const j = path.join;
9
+ const NAME = STAMP_FILE;
10
+
11
+ // Newest complete stamp for `home`, or null. { verified: true, ts, sessions, dir, frozen }.
12
+ export function readBackupStamp(home, fsx = fs) {
13
+ const L = backupLayout(home, 'x');
14
+ const root = path.dirname(L.backup);
15
+ let names = [];
16
+ try { names = fsx.readdirSync(root).filter((n) => /^opencode1-sessions-\d{8}T\d{6}Z$/.test(n)).sort(); } catch { return null; }
17
+ for (const n of names.reverse()) {
18
+ const dir = j(root, n);
19
+ let s;
20
+ try { s = JSON.parse(fsx.readFileSync(j(dir, NAME), 'utf8')); } catch { continue; }
21
+ if (s?.verified !== true || !fsx.existsSync(j(dir, 'MANIFEST.sha256')) || !fsx.existsSync(j(L.frozen, 'opencode', 'opencode.db'))) continue;
22
+ return { ...s, dir, frozen: L.frozen };
23
+ }
24
+ return null;
25
+ }
@@ -3,13 +3,15 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { sha } from './fsops.mjs';
5
5
  import { PINS, npmSpec, behindPins, nodeRange } from './pins.mjs';
6
- import { version, quiet } from './system.mjs';
7
- import { satisfies, nodeSkipLine, minVersion } from './node-runtime.mjs';
6
+ import { version, quiet, findAgy, antigravityFootprint } from './system.mjs';
7
+ import { redactText } from './redact.mjs';
8
+ import { satisfies, compare, nodeSkipLine, minVersion, findNvm, nodeAt } from './node-runtime.mjs';
8
9
  import { mcpLaunches, classify, duplicateSkills, skillDirs } from './inventory.mjs';
9
10
  import { stillNeeded, shellNotice } from './terminals.mjs';
10
11
  import { adhdSkillFiles } from './adhd.mjs';
11
12
  import { proxyReport, childEnv, fromPrivacy } from './network.mjs';
12
13
  import { leftovers } from './parallel.mjs';
14
+ import { pluginHealth } from './plugin-health.mjs';
13
15
 
14
16
  const CORE_AGENTS = ['debug', 'explore', 'planner', 'research', 'review'];
15
17
  const SECRET_KEY = /(key|token|secret|password|auth)/i;
@@ -49,14 +51,14 @@ function checkCursor(o, add, q) {
49
51
  }
50
52
  }
51
53
 
52
- function checkAntigravity(o, core, add, q, withMcp) {
53
- const agents = q(['agy', 'agents']).out;
54
+ function checkAntigravity(o, core, add, q, withMcp, agy = 'agy') {
55
+ const agents = q([agy, 'agents']).out;
54
56
  add('agy subagents loaded', core.every((a) => agents.includes(a)) ? 'ok' : 'error');
55
- const mcp = withMcp ? q(['agy', 'mcp', 'list']) : { ok: false, out: '' };
57
+ const mcp = withMcp ? q([agy, 'mcp', 'list']) : { ok: false, out: '' };
56
58
  for (const s of ['serena', 'playwright'].filter((t) => withMcp && o.tools.includes(t))) {
57
59
  add(`agy mcp ${s}`, mcp.ok && mcp.out.includes(s) ? 'ok' : 'error', mcp.ok ? '' : 'agy mcp list failed');
58
60
  }
59
- const plugins = q(['agy', 'plugin', 'list', '--json']).out;
61
+ const plugins = q([agy, 'plugin', 'list', '--json']).out;
60
62
  for (const t of ['rtk'].filter((p) => o.tools.includes(p))) {
61
63
  add(`agy plugin ${t}`, plugins.includes(`"${t}"`) ? 'ok' : 'error');
62
64
  }
@@ -78,7 +80,7 @@ function checkInventory({ home, exec, run, env, platform, fsx }, add) {
78
80
  const detail = v.status === 'wrong-node'
79
81
  ? `${m.pin} needs Node ${v.range} but this entry runs Node ${nodeVersion} (${launch.style}); run --update to register an absolute Node ${major}+ command (docs/manual-install.md)`
80
82
  : v.status === 'unknown' ? `${m.pin} needs Node ${v.range}; the Node behind this ${launch.style} entry could not be read`
81
- : `Node ${nodeVersion} (${launch.style})${v.fragile ? '; follows nvm use or PATH, so it can change' : ''}`;
83
+ : `Node ${nodeVersion} (${launch.style})${v.fragile ? '; follows nvm use or PATH, so it can change, and VS Code or Cursor started outside this shell can resolve another Node' : ''}`;
82
84
  add(`node for ${where}`, status, detail);
83
85
  return { client: m.client, name: m.name, pin: m.pin, style: launch.style, node: rel(launch.node), nodeVersion, range: v.range, status };
84
86
  });
@@ -99,7 +101,41 @@ function checkInventory({ home, exec, run, env, platform, fsx }, add) {
99
101
  return { nodes, skills };
100
102
  }
101
103
 
102
- export function doctor({ home, state, exec, nodeVersion = process.versions.node, json = false, run = quiet, env = process.env, platform = process.platform, fsx = fs }) {
104
+ // Redacted: npm error lines can carry proxy credentials or tokens, and doctor output gets pasted into issues.
105
+ export function npxFailDetail(out, opts) {
106
+ const raw = (out ?? '').split('\n').find((l) => /error/i.test(l))?.trim();
107
+ if (!raw) return '';
108
+ const line = redactText(raw, opts).slice(0, 200);
109
+ // npm prints `code ENOENT` first and the _npx path on a later line, so look at the whole output for the folder.
110
+ const npx = /enoent/i.test(out) && out.match(/[^\s'"]*_npx[\\/][0-9a-f]+/i)?.[0];
111
+ if (npx) return `${line} (broken npx cache entry: delete ${redactText(npx, opts)}, then run again)`;
112
+ return line;
113
+ }
114
+
115
+ // The active Node against the nearest package.json engines.node, from cwd up to home (or the root).
116
+ export function projectNode({ cwd, home, nodeVersion, fsx = fs }) {
117
+ for (let dir = path.resolve(cwd); ; dir = path.dirname(dir)) {
118
+ const pkg = path.join(dir, 'package.json');
119
+ if (fsx.existsSync(pkg)) {
120
+ let range;
121
+ try { range = JSON.parse(fsx.readFileSync(pkg, 'utf8')).engines?.node; } catch { return null; }
122
+ if (typeof range !== 'string' || !range.trim()) return null;
123
+ const rel = pkg.startsWith(home) ? `~${pkg.slice(home.length).replaceAll('\\', '/')}` : pkg;
124
+ const gui = '; VS Code or Cursor started outside this shell can resolve another Node';
125
+ // shortcut: only an exact version and >=a.b.c are checked; ^, ~, x and || ranges get a note, add a parser when a real project needs one.
126
+ let fits;
127
+ try { fits = /^\d+\.\d+\.\d+$/.test(range.trim()) ? compare(nodeVersion, range.trim()) === 0 : satisfies(nodeVersion, range); } catch {
128
+ return { item: 'project Node', status: 'note', detail: `Node ${nodeVersion} is active; ${rel} asks for engines.node ${range}, which lean-agents does not check${gui}` };
129
+ }
130
+ return fits
131
+ ? { item: 'project Node', status: 'ok', detail: `Node ${nodeVersion} fits engines.node ${range} in ${rel}${gui}` }
132
+ : { item: 'project Node', status: 'note', detail: `Node ${nodeVersion} is active but ${rel} asks for engines.node ${range}: run nvm use (or your version manager) in this project${gui}` };
133
+ }
134
+ if (dir === path.resolve(home) || path.dirname(dir) === dir) return null;
135
+ }
136
+ }
137
+
138
+ export function doctor({ home, state, exec, nodeVersion = process.versions.node, json = false, run = quiet, env = process.env, platform = process.platform, fsx = fs, cwd = process.cwd(), probe = [], collect = null }) {
103
139
  const rows = [];
104
140
  const add = (item, status, detail = '') => rows.push({ item, status, detail });
105
141
  if (!state) {
@@ -114,6 +150,9 @@ export function doctor({ home, state, exec, nodeVersion = process.versions.node,
114
150
  const nodeNote = o.tools.includes('context-mode') && !state.toolNode && !satisfies(nodeVersion, nodeRange('context-mode')) ? nodeSkipLine('context-mode', nodeRange('context-mode'), nodeVersion) : '';
115
151
  if (nodeNote) o.tools = o.tools.filter((t) => t !== 'context-mode');
116
152
  add('lean-agents', 'ok', `v${state.version}, agents: ${o.agents.join(', ')}, privacy: ${o.privacy}`);
153
+ const active = (exec && /\d+\.\d+\.\d+/.exec(version('node') ?? '')?.[0]) || nodeVersion;
154
+ const pn = projectNode({ cwd, home, nodeVersion: active, fsx });
155
+ if (pn) add(pn.item, pn.status, pn.detail);
117
156
  if (nodeNote) add('context-mode', 'note', nodeNote);
118
157
  if (o.agents.includes('opencode-v1')) add('OpenCode 1.x: supported; lean-agents will not upgrade it', 'ok');
119
158
  const shell = shellNotice();
@@ -138,12 +177,25 @@ export function doctor({ home, state, exec, nodeVersion = process.versions.node,
138
177
  const reset = adhdSkillFiles(home).filter((f) => fs.readFileSync(f, 'utf8').includes('disable-model-invocation: true'));
139
178
  if (reset.length) add('i-have-adhd skill', 'changed', 'a plugin update reset it; run --update');
140
179
  }
180
+ if (o.agents.includes('vscode-copilot')) add('Copilot extension', 'skipped', 'managed by VS Code, not lean-agents: install and update it from the Extensions view');
141
181
  if (exec) {
142
182
  for (const [bin, tool] of [['claude', 'claude'], ['opencode', 'opencode-v1'], ['opencode', 'opencode-v2'], ['copilot', 'copilot-cli'], ['agy', 'antigravity'], ['rtk', 'rtk'], ['context-mode', 'context-mode'], ['uvx', 'serena']]) {
143
183
  const needed = o.agents.includes(tool) || o.tools.includes(tool);
144
184
  if (!needed) continue;
145
- const v = version(bin, undefined, childEnv(network));
146
- add(`${bin} on PATH`, v ? 'ok' : 'error', v ?? 'not found');
185
+ if (bin === 'context-mode' && state.toolNode?.version) {
186
+ const nvm = findNvm({ env, home, platform, realHome: env.HOME || env.USERPROFILE || home });
187
+ if (nvm) {
188
+ const dir = nvm.win ? path.join(nvm.dir, `v${state.toolNode.version}`) : path.join(nvm.dir, 'versions', 'node', `v${state.toolNode.version}`);
189
+ const n = nodeAt(nvm, dir, state.toolNode.version);
190
+ const cli = path.join(n.modules, 'context-mode', 'package.json');
191
+ const found = fsx.existsSync(cli);
192
+ add(`context-mode on Node ${state.toolNode.version}`, found ? 'ok' : 'error', found ? cli : `not found: ${cli}`);
193
+ continue;
194
+ }
195
+ }
196
+ const at = bin === 'agy' ? findAgy(home, platform, env) ?? bin : bin;
197
+ const v = version(at, undefined, childEnv(network));
198
+ add(at === bin ? `${bin} on PATH` : `${bin} found outside PATH`, v ? 'ok' : 'error', v ?? 'not found');
147
199
  }
148
200
  for (const [bin, agent] of [['code', 'vscode-copilot'], ['cursor-agent', 'cursor']]) {
149
201
  if (!o.agents.includes(agent)) continue;
@@ -160,23 +212,43 @@ export function doctor({ home, state, exec, nodeVersion = process.versions.node,
160
212
  }
161
213
  if (o.agents.some((a) => a.startsWith('opencode'))) checkOpenCode(o, add, q);
162
214
  if (o.agents.includes('copilot-cli')) checkCopilot(o, add, q, withMcp);
163
- if (o.agents.includes('antigravity')) checkAntigravity(o, CORE_AGENTS, add, q, withMcp);
215
+ if (o.agents.includes('antigravity')) checkAntigravity(o, CORE_AGENTS, add, q, withMcp, findAgy(home, platform, env) ?? 'agy');
164
216
  // npx may have to download, which takes longer than a local check.
165
- if (o.tools.includes('codeburn')) add('codeburn runs', q(['npx', '-y', npmSpec('codeburn'), '--version'], 120000).ok ? 'ok' : 'error');
166
- if (o.tools.includes('autoskills')) add('autoskills runs', q(['npx', '-y', npmSpec('autoskills'), '--help'], 120000).ok ? 'ok' : 'error');
217
+ if (o.tools.includes('codeburn')) {
218
+ const r = q(['npx', '-y', npmSpec('codeburn'), '--version'], 120000);
219
+ add('codeburn runs', r.ok ? 'ok' : 'error', r.ok ? '' : npxFailDetail(r.out, { home, env }));
220
+ }
221
+ if (o.tools.includes('autoskills')) {
222
+ const r = q(['npx', '-y', npmSpec('autoskills'), '--help'], 120000);
223
+ add('autoskills runs', r.ok ? 'ok' : 'error', r.ok ? '' : npxFailDetail(r.out, { home, env }));
224
+ }
167
225
  }
168
226
  }
227
+ checkAntigravityIde(home, add, fsx);
169
228
  const { nodes, skills } = checkInventory({ home, exec, run, env, platform, fsx }, add);
229
+ // #212: config listing a plugin is not proof it loads. Read-only; `probe` holds findings of the opt-in --probe-plugins server run.
230
+ if (state?.options.agents.some((a) => a.startsWith('opencode'))) {
231
+ for (const f of [...pluginHealth(home, { fsx }), ...probe]) add(`plugin ${f.plugin || 'probe'} ${f.id}`, ['deps-incomplete', 'command-missing'].includes(f.id) ? 'error' : 'changed', `${f.line}. Fix: ${f.fix}`);
232
+ }
170
233
  const left = leftovers(process.cwd());
171
234
  if (left.length) add('parallel workers', 'changed', `left in this repo: ${left.join(', ')} (merge them, then run scripts/parallel.mjs clean)`);
172
- for (const line of proxyReport()) add('network env', 'ok', line);
235
+ const netRows = proxyReport();
236
+ for (const name of ['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'NODE_USE_SYSTEM_CA']) if (!netRows.some((l) => l.startsWith(`${name}=`))) netRows.push(`${name}=not set`);
237
+ for (const line of netRows) add('network env', 'ok', line);
173
238
  const ok = !rows.some((r) => r.status === 'error' || r.status === 'missing');
174
239
  const behind = state ? behindPins(state) : [];
175
240
  if (json) process.stdout.write(`${JSON.stringify({ ok, behind, nodes, skills, rows }, null, 2)}\n`);
241
+ else if (collect) collect.push(...rows);
176
242
  else print(rows);
177
243
  return ok;
178
244
  }
179
245
 
246
+ // Read-only (#216): a row only when the IDE folders or the extension exist.
247
+ function checkAntigravityIde(home, add, fsx) {
248
+ const found = antigravityFootprint(home, fsx);
249
+ if (found.length) add('antigravity ide', 'ok', found.map((f) => f.name).join(', '));
250
+ }
251
+
180
252
  function checkOpenCode(o, add, q) {
181
253
  const r = q(['opencode', 'debug', 'config']);
182
254
  if (!r.ok) return add('opencode resolved config', 'error', '`opencode debug config` failed');
@@ -10,16 +10,17 @@ export function draftIssue({ network, home, env = process.env, versions = {}, co
10
10
  if (!feedbackAllowed(network)) return null;
11
11
  const clean = (t) => redactText(t, { home, env });
12
12
  const update = kind === 'update';
13
+ const verify = kind === 'verify';
13
14
  const versionLines = Object.entries(versions).map(([k, v]) => `- ${k}: ${clean(v)}`);
14
15
  return {
15
- title: clean(`${update ? 'Update finding' : 'Install failed'}: ${command}`).slice(0, 100),
16
+ title: clean(`${update ? 'Update finding' : verify ? 'Verify finding' : 'Install failed'}: ${command}`).slice(0, 100),
16
17
  body: [
17
- update ? '## What the update found' : '## What failed',
18
+ update ? '## What the update found' : verify ? '## What the check found' : '## What failed',
18
19
  `- OS: ${platform}`,
19
20
  ...versionLines,
20
- `- ${update ? 'Tool' : 'Command'}: \`${clean(command)}\``,
21
+ `- ${update || verify ? 'Tool' : 'Command'}: \`${clean(command)}\``,
21
22
  '',
22
- update ? '## Details' : '## Error',
23
+ update || verify ? '## Details' : '## Error',
23
24
  '```',
24
25
  clean(error).trim(),
25
26
  '```',
@@ -28,3 +29,20 @@ export function draftIssue({ network, home, env = process.env, versions = {}, co
28
29
  ].join('\n'),
29
30
  };
30
31
  }
32
+
33
+ // A doctor row `{ item, status, detail }` as an issue draft. Unlike draftIssue it always returns the redacted text, so a
34
+ // strict or offline user can copy it; `canFile` says whether the agent may offer to file it (feedbackAllowed).
35
+ export function draftFromRow({ network, row, ...rest }) {
36
+ const draft = draftIssue({ ...rest, network: { outbound: 'on' }, command: row.item, error: `${row.status}: ${row.detail ?? ''}`, kind: 'verify' });
37
+ return { ...draft, canFile: feedbackAllowed(network) };
38
+ }
39
+
40
+ const ISSUE_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/\d+$/;
41
+
42
+ // state.json `filedIssues`: [{ item, title, url, filedAt }], one entry per issue the user said yes to. Pure: returns the new list.
43
+ export function addFiledIssue(list = [], { item, title, url, filedAt = new Date().toISOString() }, { home, env = process.env } = {}) {
44
+ if (!ISSUE_URL.test(url)) throw new Error(`not a GitHub issue URL: ${url}`);
45
+ if (list.some((f) => f.url === url)) return list;
46
+ const clean = (t) => redactText(t, { home, env });
47
+ return [...list, { item: clean(item), title: clean(title), url, filedAt }];
48
+ }