lean-agents 0.0.0-stage → 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 (148) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/LICENSE +21 -0
  3. package/README.es.md +560 -0
  4. package/README.md +559 -2
  5. package/core/AGENTS.es.md +60 -0
  6. package/core/AGENTS.md +60 -0
  7. package/core/README.md +8 -0
  8. package/core/agents/debug.md +14 -0
  9. package/core/agents/explore.md +13 -0
  10. package/core/agents/planner.md +14 -0
  11. package/core/agents/research.md +13 -0
  12. package/core/agents/review.md +13 -0
  13. package/core/copilot-usage-tui.js +189 -0
  14. package/core/mcp.json +38 -0
  15. package/core/pins.json +39 -0
  16. package/core/tiers.json +4 -0
  17. package/node_modules/@clack/core/LICENSE +9 -0
  18. package/node_modules/@clack/core/README.md +22 -0
  19. package/node_modules/@clack/core/dist/index.d.mts +503 -0
  20. package/node_modules/@clack/core/dist/index.mjs +1003 -0
  21. package/node_modules/@clack/core/package.json +63 -0
  22. package/node_modules/@clack/prompts/LICENSE +9 -0
  23. package/node_modules/@clack/prompts/README.md +396 -0
  24. package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
  25. package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
  26. package/node_modules/@clack/prompts/package.json +67 -0
  27. package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
  28. package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
  29. package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
  30. package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
  31. package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
  32. package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
  33. package/node_modules/fast-string-truncated-width/license +21 -0
  34. package/node_modules/fast-string-truncated-width/package.json +35 -0
  35. package/node_modules/fast-string-truncated-width/readme.md +59 -0
  36. package/node_modules/fast-string-width/dist/index.d.ts +4 -0
  37. package/node_modules/fast-string-width/dist/index.js +14 -0
  38. package/node_modules/fast-string-width/license +21 -0
  39. package/node_modules/fast-string-width/package.json +34 -0
  40. package/node_modules/fast-string-width/readme.md +42 -0
  41. package/node_modules/fast-wrap-ansi/LICENSE +23 -0
  42. package/node_modules/fast-wrap-ansi/README.md +26 -0
  43. package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
  44. package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
  45. package/node_modules/fast-wrap-ansi/package.json +51 -0
  46. package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
  47. package/node_modules/jsonc-parser/LICENSE.md +21 -0
  48. package/node_modules/jsonc-parser/README.md +364 -0
  49. package/node_modules/jsonc-parser/SECURITY.md +41 -0
  50. package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
  51. package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
  52. package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
  53. package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
  54. package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
  55. package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
  56. package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
  57. package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
  58. package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
  59. package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
  60. package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
  61. package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
  62. package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
  63. package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
  64. package/node_modules/jsonc-parser/package.json +37 -0
  65. package/node_modules/sisteransi/license +21 -0
  66. package/node_modules/sisteransi/package.json +34 -0
  67. package/node_modules/sisteransi/readme.md +113 -0
  68. package/node_modules/sisteransi/src/index.js +58 -0
  69. package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
  70. package/package.json +30 -4
  71. package/profiles/README.md +10 -0
  72. package/profiles/anthropic-api/gsd-defaults.json +26 -0
  73. package/profiles/anthropic-api.json +18 -0
  74. package/profiles/antigravity.json +12 -0
  75. package/profiles/claude-subscription/gsd-defaults.json +26 -0
  76. package/profiles/claude-subscription.json +17 -0
  77. package/profiles/github-copilot/gsd-defaults.json +26 -0
  78. package/profiles/github-copilot.json +17 -0
  79. package/profiles/openai-api/gsd-defaults.json +26 -0
  80. package/profiles/openai-api.json +17 -0
  81. package/profiles/opencode-go/gsd-defaults.json +26 -0
  82. package/profiles/opencode-go.json +17 -0
  83. package/profiles/vertex-gemini/gsd-defaults.json +26 -0
  84. package/profiles/vertex-gemini.json +18 -0
  85. package/scripts/adhd-skill.mjs +12 -0
  86. package/scripts/behavior-diff.sh +47 -0
  87. package/scripts/bump-pins.mjs +115 -0
  88. package/scripts/check-private.sh +52 -0
  89. package/scripts/check-readme.mjs +131 -0
  90. package/scripts/ci-download.sh +20 -0
  91. package/scripts/ci-install-opencode-v2.sh +6 -0
  92. package/scripts/ci-latest-report.mjs +38 -0
  93. package/scripts/ci-timing.mjs +61 -0
  94. package/scripts/copilot-context-mode.mjs +33 -0
  95. package/scripts/labels.sh +56 -0
  96. package/scripts/lean.mjs +1319 -0
  97. package/scripts/lib/adapters/antigravity.mjs +83 -0
  98. package/scripts/lib/adapters/claude.mjs +127 -0
  99. package/scripts/lib/adapters/copilot-cli.mjs +82 -0
  100. package/scripts/lib/adapters/cursor.mjs +60 -0
  101. package/scripts/lib/adapters/opencode-v1.mjs +79 -0
  102. package/scripts/lib/adapters/opencode-v2.mjs +216 -0
  103. package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
  104. package/scripts/lib/adhd.mjs +28 -0
  105. package/scripts/lib/adopt.mjs +619 -0
  106. package/scripts/lib/agent-lifecycle.mjs +280 -0
  107. package/scripts/lib/backup-stamp.mjs +25 -0
  108. package/scripts/lib/copilot-usage.mjs +49 -0
  109. package/scripts/lib/doctor.mjs +279 -0
  110. package/scripts/lib/feedback.mjs +48 -0
  111. package/scripts/lib/fsops.mjs +319 -0
  112. package/scripts/lib/gsd.mjs +42 -0
  113. package/scripts/lib/inventory.mjs +196 -0
  114. package/scripts/lib/lean-update.mjs +30 -0
  115. package/scripts/lib/logins.mjs +28 -0
  116. package/scripts/lib/migrate.mjs +407 -0
  117. package/scripts/lib/network.mjs +119 -0
  118. package/scripts/lib/node-runtime.mjs +85 -0
  119. package/scripts/lib/opencode-backup.mjs +204 -0
  120. package/scripts/lib/opencode-upgrade.mjs +441 -0
  121. package/scripts/lib/opencode1.mjs +203 -0
  122. package/scripts/lib/parallel.mjs +270 -0
  123. package/scripts/lib/pins-diff.mjs +33 -0
  124. package/scripts/lib/pins.mjs +52 -0
  125. package/scripts/lib/plugin-health.mjs +191 -0
  126. package/scripts/lib/prereqs.mjs +203 -0
  127. package/scripts/lib/project.mjs +38 -0
  128. package/scripts/lib/redact.mjs +30 -0
  129. package/scripts/lib/render.mjs +101 -0
  130. package/scripts/lib/shell-path.mjs +22 -0
  131. package/scripts/lib/summary-data.mjs +30 -0
  132. package/scripts/lib/summary-html.mjs +159 -0
  133. package/scripts/lib/system.mjs +269 -0
  134. package/scripts/lib/terminals.mjs +316 -0
  135. package/scripts/lib/ui.mjs +34 -0
  136. package/scripts/lib/unverified.mjs +49 -0
  137. package/scripts/lib/update-plan.mjs +60 -0
  138. package/scripts/lib/upgrade.mjs +231 -0
  139. package/scripts/lib/verify-commit.mjs +16 -0
  140. package/scripts/lib/verify-prompt.mjs +46 -0
  141. package/scripts/lib/verify-sha256.mjs +20 -0
  142. package/scripts/lint-workflows.mjs +25 -0
  143. package/scripts/models-refresh.mjs +58 -0
  144. package/scripts/parallel.mjs +59 -0
  145. package/scripts/pins-latest.mjs +66 -0
  146. package/scripts/release.mjs +71 -0
  147. package/scripts/verify-pins.mjs +36 -0
  148. package/scripts/version-watch.mjs +124 -0
@@ -0,0 +1,280 @@
1
+ // --install-agent / --uninstall-agent: opt-in install of an agent CLI and an undo that removes only what we recorded.
2
+ // Installer scripts are pinned in core/pins.json (url + sha256, checked by verify-sha256.mjs before they run).
3
+ // Install snapshots the install dirs before and after and records the new files with their sha256 in <state>/agents.json.
4
+ // Uninstall deletes a recorded file only while its sha256 still matches, or runs `npm uninstall -g` for npm installs.
5
+ // It never runs an agent's own uninstaller (`opencode uninstall` may delete user data) and never installs OpenCode 1.x (#79).
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { PINS } from './pins.mjs';
10
+ import { sha256 } from './verify-sha256.mjs';
11
+ import { run, which, version, antigravityPrereqs, packageManager, agyCandidates, BREW_AGY_LIMIT } from './system.mjs';
12
+ import { writePrivate, privateDir } from './fsops.mjs';
13
+ import { winPathDefault } from './opencode1.mjs';
14
+ import { gitBashPath } from './terminals.mjs';
15
+
16
+ const VERIFY = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
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).';
22
+
23
+ // Pinned installer script: curl, verify, run. `args` go to the script (a version for Claude and OpenCode).
24
+ function script(pinKey, dir, args = [], ext = '.sh') {
25
+ const p = PINS[pinKey];
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]] };
28
+ }
29
+
30
+ // One row per agent for this OS: how it is installed, where its binary lands and which dirs the install may write to.
31
+ // `manual` is a reason, not a command: that agent/OS route is not proven yet (VERIFY in docs/compatibility.md).
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;
36
+ const posix = platform !== 'win32';
37
+ const cmds = AGENT_CLIS;
38
+ const local = path.join(home, '.local');
39
+ const bin = (...n) => n.map((x) => path.join(local, 'bin', x));
40
+ const prefix = home === realHome ? [] : ['--prefix', local];
41
+ const t = {};
42
+ t.claude = posix
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;
46
+ t['opencode-v2'] = posix
47
+ // --no-modify-path: the installer must not edit ~/.bashrc, which we could not undo.
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' });
56
+ t['copilot-cli'] = {
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]],
59
+ bins: prefix.length ? (posix ? [path.join(local, 'bin', 'copilot')] : [path.join(local, 'copilot.cmd')]) : [], dirs: [],
60
+ };
61
+ t.cursor = posix
62
+ ? { method: 'script', ...script('cursor-installer', dir), bins: bin('agent', 'cursor-agent'), dirs: [path.join(local, 'bin'), path.join(local, 'share', 'cursor-agent'), path.join(home, '.cursor')] }
63
+ : { manual: 'Cursor CLI on Windows (cursor.com/install): not proven yet. VERIFY' };
64
+ if (platform === 'darwin' && packageManager() === 'brew') {
65
+ // The engine's own Antigravity install (antigravityPrereqs); brew removes what it installed.
66
+ const c = antigravityPrereqs('brew', platform, home, false).find((x) => x.run.length);
67
+ t.antigravity = { method: 'brew', version: null, run: c?.run ?? [], uninstall: [['brew', 'uninstall', '--cask', 'antigravity-cli']], bins: [], dirs: [], unpinned: BREW_AGY_LIMIT };
68
+ } else {
69
+ t.antigravity = posix
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')] }
71
+ : { manual: 'Antigravity CLI on Windows (Google.AntigravityCLI): no documented scope, install it from https://antigravity.google/docs/getting-started. VERIFY' };
72
+ }
73
+ for (const [a, row] of Object.entries(t)) row.cmd = cmds[a];
74
+ return t;
75
+ }
76
+
77
+ // {files: Map(path -> {sha256} | {link}), dirs: Set} of everything under the given roots.
78
+ export function snapshot(roots) {
79
+ const files = new Map();
80
+ const dirs = new Set();
81
+ const walk = (p) => {
82
+ const st = fs.lstatSync(p, { throwIfNoEntry: false });
83
+ if (!st) return;
84
+ if (st.isSymbolicLink()) files.set(p, { link: fs.readlinkSync(p) });
85
+ else if (st.isDirectory()) { dirs.add(p); for (const n of fs.readdirSync(p)) walk(path.join(p, n)); } else if (st.isFile()) files.set(p, { sha256: sha256(p) });
86
+ };
87
+ for (const r of roots) walk(r);
88
+ return { files, dirs };
89
+ }
90
+
91
+ const inside = (home, p) => { const r = path.relative(home, p); return r && !r.startsWith('..') && !path.isAbsolute(r); };
92
+ const same = (a, b) => a && b && a.sha256 === b.sha256 && a.link === b.link;
93
+
94
+ export function diffSnapshots(before, after) {
95
+ return {
96
+ files: [...after.files].filter(([p]) => !before.files.has(p)).map(([p, v]) => ({ path: p, ...v })),
97
+ dirs: [...after.dirs].filter((d) => !before.dirs.has(d)),
98
+ };
99
+ }
100
+
101
+ // Removes the recorded files that still match, then the recorded dirs that are now empty. Returns [what, path] rows.
102
+ export function removeRecorded(home, rec) {
103
+ const rows = [];
104
+ for (const f of rec.files) {
105
+ if (!inside(home, f.path)) { rows.push(['skipped (outside home)', f.path]); continue; }
106
+ const st = fs.lstatSync(f.path, { throwIfNoEntry: false });
107
+ if (!st) { rows.push(['already gone', f.path]); continue; }
108
+ const now = st.isSymbolicLink() ? { link: fs.readlinkSync(f.path) } : st.isFile() ? { sha256: sha256(f.path) } : null;
109
+ if (!same(now, f)) { rows.push(['kept (changed)', f.path]); continue; }
110
+ fs.unlinkSync(f.path);
111
+ rows.push(['removed', f.path]);
112
+ }
113
+ for (const d of [...rec.dirs].sort((a, b) => b.length - a.length)) {
114
+ if (inside(home, d) && fs.existsSync(d) && !fs.readdirSync(d).length) fs.rmdirSync(d);
115
+ }
116
+ return rows;
117
+ }
118
+
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
+ }
131
+ const readAgents = (stateDir) => (fs.existsSync(stateFile(stateDir)) ? JSON.parse(fs.readFileSync(stateFile(stateDir), 'utf8')) : { agents: {} });
132
+
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 }
145
+ export async function agentLifecycle(o) {
146
+ const log = console.log;
147
+ const winPath = o.winPath ?? winPathDefault;
148
+ for (const a of o.agents) {
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)');
150
+ if (!LIFECYCLE_AGENTS.includes(a)) throw new Error(`cannot ${o.mode} "${a}" (available: ${LIFECYCLE_AGENTS.join(', ')})`);
151
+ }
152
+ if (o.agents.includes(VSCODE)) await vscodeLifecycle(o);
153
+ const agents = o.agents.filter((a) => a !== VSCODE);
154
+ const state = readAgents(o.stateDir);
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 });
157
+ const todo = [];
158
+ for (const a of agents) {
159
+ const row = table[a];
160
+ const mine = state.agents[a];
161
+ if (o.mode === 'install') {
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.`);
165
+ else if (row.manual) log(`${a}: ${row.manual}`);
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.');
169
+ else todo.push(a);
170
+ } else if (!mine) log(`${a}: not installed by lean-agents; nothing done.`);
171
+ else todo.push(a);
172
+ }
173
+ if (!todo.length) return;
174
+ log(`\nlean-agents ${o.mode}-agent plan:`);
175
+ for (const a of todo) {
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' : ''})`}`);
177
+ for (const argv of o.mode === 'install' ? table[a].run : state.agents[a].uninstall ?? []) log(` $ ${argv.join(' ')}`);
178
+ }
179
+ for (const a of todo) if (o.mode === 'install' && table[a].unpinned) log(` ! ${a}: ${table[a].unpinned}`);
180
+ if (o.dryRun || !o.exec) { log(o.dryRun ? 'Dry run: nothing was changed.' : '--no-exec: nothing was run.'); 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; }
183
+ privateDir(o.stateDir, o.stateDir);
184
+ fs.mkdirSync(o.stateDir, { recursive: true });
185
+ const env = {};
186
+ for (const a of todo) {
187
+ if (o.mode === 'install') {
188
+ const row = table[a];
189
+ const before = snapshot(row.dirs);
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 } }));
197
+ if (row.download) fs.rmSync(row.download, { force: true });
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
+ }
211
+ if (!ok) {
212
+ log(` ! ${a}: install failed. Run the commands above by hand.`);
213
+ process.exitCode = 1;
214
+ // Keep what a half-run installer left, so --uninstall-agent can clean it.
215
+ if (!rec.files.length && !rec.dirs.length && !pathEntry) continue;
216
+ }
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;
219
+ log(`${a}: installed; ${rec.files.length} files recorded.`);
220
+ } else {
221
+ const rec = state.agents[a];
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; }
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
+ }
227
+ delete state.agents[a];
228
+ log(`${a}: removed. Your config and data were not touched.`);
229
+ }
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.');
278
+ }
279
+ return { ok: plan.every((c) => restored.has(agentOf(c))), restored };
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
+ }
@@ -0,0 +1,49 @@
1
+ // One-line Copilot premium-request allowance from `gh api copilot_internal/user` (undocumented endpoint,
2
+ // the one VS Code's meter uses). Any failure is "unavailable", never zero. Dollars: 1 credit = $0.01, an estimate.
3
+ import { quiet } from './system.mjs';
4
+ import { OWNED_MARK } from './fsops.mjs';
5
+
6
+ const money = (credits) => `$${(credits / 100).toFixed(2)}`;
7
+ const n = (v) => String(Math.round(v));
8
+
9
+ export function formatUsage(user) {
10
+ const p = user?.quota_snapshots?.premium_interactions;
11
+ if (!p) return 'unavailable';
12
+ if (p.unlimited) return 'Unlimited premium requests';
13
+ if (![p.entitlement, p.remaining, p.percent_remaining].every(Number.isFinite)) return 'unavailable';
14
+ return `${n(p.remaining)} of ${n(p.entitlement)} credits left (${Math.floor(p.percent_remaining)}%), about ${money(p.remaining)} of ${money(p.entitlement)}, resets ${user.quota_reset_date}`;
15
+ }
16
+
17
+ // Claude Code status line: a standalone Node script built from the formatter above (same source, so it cannot drift).
18
+ // gh runs at most once per 5 minutes (cache in the temp dir); a failure prints `unavailable`, never zero.
19
+ export const statuslineScript = () => `// ${OWNED_MARK}
20
+ // Claude Code status line: Copilot credits left. One gh call (cached 5 minutes), never a model request.
21
+ import { execFileSync } from 'node:child_process';
22
+ import fs from 'node:fs';
23
+ import os from 'node:os';
24
+ import path from 'node:path';
25
+
26
+ const money = ${money};
27
+ const n = ${n};
28
+ ${formatUsage}
29
+
30
+ const cache = path.join(os.tmpdir(), 'lean-copilot-usage-statusline.txt');
31
+ try {
32
+ if (Date.now() - fs.statSync(cache).mtimeMs < 300000) { process.stdout.write(fs.readFileSync(cache, 'utf8')); process.exit(0); }
33
+ } catch {}
34
+ let line;
35
+ try {
36
+ const out = execFileSync('gh', ['api', 'copilot_internal/user'], { timeout: 15000, encoding: 'utf8', windowsHide: true, shell: process.platform === 'win32', stdio: ['ignore', 'pipe', 'ignore'] });
37
+ line = 'Copilot: ' + formatUsage(JSON.parse(out)) + '\\n';
38
+ } catch { line = 'Copilot: ' + formatUsage(null) + '\\n'; }
39
+ // Shared /tmp: never follow a planted symlink; 'wx' (O_EXCL) refuses any existing path.
40
+ try { fs.rmSync(cache, { force: true }); fs.writeFileSync(cache, line, { flag: 'wx' }); } catch {}
41
+ process.stdout.write(line);
42
+ `;
43
+
44
+ // No leading slash: Git Bash rewrites it into a Windows path.
45
+ export function copilotUsage(run = quiet) {
46
+ const r = run(['gh', 'api', 'copilot_internal/user'], 15000);
47
+ if (!r.ok) return formatUsage(null);
48
+ try { return formatUsage(JSON.parse(r.out)); } catch { return formatUsage(null); }
49
+ }
@@ -0,0 +1,279 @@
1
+ // Doctor: compares what lean-agents installed with what is on disk and what the agents load.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { sha } from './fsops.mjs';
5
+ import { PINS, npmSpec, behindPins, nodeRange } from './pins.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';
9
+ import { mcpLaunches, classify, duplicateSkills, skillDirs } from './inventory.mjs';
10
+ import { stillNeeded, shellNotice } from './terminals.mjs';
11
+ import { adhdSkillFiles } from './adhd.mjs';
12
+ import { proxyReport, childEnv, fromPrivacy } from './network.mjs';
13
+ import { leftovers } from './parallel.mjs';
14
+ import { pluginHealth } from './plugin-health.mjs';
15
+
16
+ const CORE_AGENTS = ['debug', 'explore', 'planner', 'research', 'review'];
17
+ const SECRET_KEY = /(key|token|secret|password|auth)/i;
18
+
19
+ export function redact(value) {
20
+ if (Array.isArray(value)) return value.map(redact);
21
+ if (value && typeof value === 'object') {
22
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY.test(k) ? '[redacted]' : redact(v)]));
23
+ }
24
+ return value;
25
+ }
26
+
27
+ // OpenCode 2 prints a JSON array of config sources ({type, path, info}); 1.x printed one object.
28
+ export function resolvedOpenCodeConfig(text) {
29
+ const start = text.search(/^[[{]/m);
30
+ const data = JSON.parse(text.slice(start).trim());
31
+ if (!Array.isArray(data)) return data;
32
+ const merged = {};
33
+ for (const src of data) if (src.type === 'document' && src.info) Object.assign(merged, src.info);
34
+ return merged;
35
+ }
36
+
37
+ function checkCopilot(o, add, q, withMcp) {
38
+ const mcp = withMcp ? q(['copilot', 'mcp', 'list', '--json']) : { ok: false, out: '' };
39
+ for (const s of ['serena', 'playwright', 'playwright-extension', 'context-mode'].filter((t) => withMcp && o.tools.includes(t))) {
40
+ add(`copilot mcp ${s}`, mcp.ok && mcp.out.includes(`"${s}"`) ? 'ok' : 'error', mcp.ok ? '' : 'copilot mcp list failed');
41
+ }
42
+ const rules = q(['copilot', 'instruction', 'list']);
43
+ add('copilot rules loaded', rules.ok && rules.out.includes('copilot-instructions.md') ? 'ok' : 'error');
44
+ }
45
+
46
+ function checkCursor(o, add, q) {
47
+ // `mcp list` starts every server, and Serena through uvx can take longer than 30s.
48
+ const mcp = q(['cursor-agent', 'mcp', 'list'], 120000);
49
+ for (const s of ['serena', 'playwright', 'playwright-extension', 'context-mode'].filter((t) => o.tools.includes(t))) {
50
+ add(`cursor mcp ${s}`, mcp.ok && mcp.out.includes(s) ? 'ok' : 'error', mcp.ok ? '' : 'cursor-agent mcp list failed');
51
+ }
52
+ }
53
+
54
+ function checkAntigravity(o, core, add, q, withMcp, agy = 'agy') {
55
+ const agents = q([agy, 'agents']).out;
56
+ add('agy subagents loaded', core.every((a) => agents.includes(a)) ? 'ok' : 'error');
57
+ const mcp = withMcp ? q([agy, 'mcp', 'list']) : { ok: false, out: '' };
58
+ for (const s of ['serena', 'playwright'].filter((t) => withMcp && o.tools.includes(t))) {
59
+ add(`agy mcp ${s}`, mcp.ok && mcp.out.includes(s) ? 'ok' : 'error', mcp.ok ? '' : 'agy mcp list failed');
60
+ }
61
+ const plugins = q([agy, 'plugin', 'list', '--json']).out;
62
+ for (const t of ['rtk'].filter((p) => o.tools.includes(p))) {
63
+ add(`agy plugin ${t}`, plugins.includes(`"${t}"`) ? 'ok' : 'error');
64
+ }
65
+ }
66
+
67
+ // Which Node runs each registered MCP command of a pinned tool, and skills that two folders of one agent both hold.
68
+ // Read-only, and it also covers machines lean-agents did not set up (#104 points 4-5, #132).
69
+ function checkInventory({ home, exec, run, env, platform, fsx }, add) {
70
+ const rel = (p) => (p && p.startsWith(home) ? `~${p.slice(home.length)}` : p);
71
+ const nodes = mcpLaunches(home, { env, platform, fsx }).map((m) => {
72
+ let nodeVersion = m.launch.nodeVersion;
73
+ // Only with exec: a symlink or PATH Node has no version in its path, so ask it.
74
+ if (!nodeVersion && exec && m.launch.node) nodeVersion = /\d+\.\d+\.\d+/.exec(run([m.launch.node, '--version'], 20000).out ?? '')?.[0] ?? null;
75
+ const launch = { ...m.launch, nodeVersion };
76
+ const v = classify(launch, m.pin);
77
+ const status = v.status === 'wrong-node' ? 'error' : v.status === 'unknown' ? 'note' : 'ok';
78
+ const where = `${m.client} mcp ${m.name}`;
79
+ const major = minVersion(v.range)[0];
80
+ const detail = v.status === 'wrong-node'
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)`
82
+ : v.status === 'unknown' ? `${m.pin} needs Node ${v.range}; the Node behind this ${launch.style} entry could not be read`
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' : ''}`;
84
+ add(`node for ${where}`, status, detail);
85
+ return { client: m.client, name: m.name, pin: m.pin, style: launch.style, node: rel(launch.node), nodeVersion, range: v.range, status };
86
+ });
87
+ const ORCA = new Set(['orca-cli', 'orchestration', 'computer-use']);
88
+ const bySkill = new Map();
89
+ for (const agent of ['claude', 'opencode', 'cursor', 'copilot']) {
90
+ for (const d of duplicateSkills(skillDirs(agent, home), fsx)) {
91
+ const k = `${d.name}\0${d.dirs.join('\0')}`;
92
+ bySkill.set(k, { ...(bySkill.get(k) ?? { name: d.name, dirs: d.dirs.map(rel), differs: d.differs, unreadable: d.unreadable, winner: d.winner, agents: [] }), agents: [...(bySkill.get(k)?.agents ?? []), agent] });
93
+ }
94
+ }
95
+ const skills = [...bySkill.values()];
96
+ for (const s of skills) {
97
+ const orca = ORCA.has(s.name) ? ' Orca installs this skill in both folders on purpose.' : '';
98
+ add(`duplicate skill ${s.name}`, s.differs ? 'changed' : 'note',
99
+ `in ${s.dirs.join(' and ')} (read by ${s.agents.join(', ')}); ${s.unreadable ? 'a copy is unreadable, so they could not be compared' : `the copies ${s.differs ? 'differ' : 'are identical'}`}; winner: ${s.winner}. Keep one folder.${orca}`);
100
+ }
101
+ return { nodes, skills };
102
+ }
103
+
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 }) {
139
+ const rows = [];
140
+ const add = (item, status, detail = '') => rows.push({ item, status, detail });
141
+ if (!state) {
142
+ add('lean-agents', 'missing', 'not installed (run the installer)');
143
+ } else {
144
+ const o = { ...state.options };
145
+ const network = o.network ?? fromPrivacy(o.privacy) ?? {};
146
+ const q = (argv, timeout) => run(argv, timeout, childEnv(network));
147
+ // `mcp list` starts every server (Serena through uvx git, Playwright), which is outbound traffic.
148
+ const withMcp = network.outbound !== 'off';
149
+ // A saved toolNode means Context Mode runs on its own Node, so the active one does not matter.
150
+ const nodeNote = o.tools.includes('context-mode') && !state.toolNode && !satisfies(nodeVersion, nodeRange('context-mode')) ? nodeSkipLine('context-mode', nodeRange('context-mode'), nodeVersion) : '';
151
+ if (nodeNote) o.tools = o.tools.filter((t) => t !== 'context-mode');
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);
156
+ if (nodeNote) add('context-mode', 'note', nodeNote);
157
+ if (o.agents.includes('opencode-v1')) add('OpenCode 1.x: supported; lean-agents will not upgrade it', 'ok');
158
+ const shell = shellNotice();
159
+ if (shell) add('shell', shell.ok ? 'ok' : 'note', shell.text);
160
+ if (o.terminals?.length) add('terminals', 'ok', `integrations for ${o.terminals.join(', ')} (commands listed below; app settings are yours)`);
161
+ for (const t of stillNeeded({ home, terminals: o.terminals ?? [], agents: o.agents, exec })) {
162
+ add('still needed', t.check?.() ? 'ok' : 'note', t.text);
163
+ }
164
+ const latest = [...new Map(state.files.map((f) => [f.path, f])).values()];
165
+ for (const f of latest) {
166
+ const rel = f.path.startsWith(home) ? `~${f.path.slice(home.length)}` : f.path;
167
+ if (!fs.existsSync(f.path)) { add(rel, 'error', 'missing'); continue; }
168
+ const same = sha(fs.readFileSync(f.path, 'utf8')) === f.hash;
169
+ add(rel, same ? 'ok' : 'changed', same ? '' : 'edited since install (fine if on purpose)');
170
+ }
171
+ // Drift: the installer pinned other versions than core/pins.json lists now (a newer lean-agents, or an edited pin).
172
+ const drift = Object.entries(state.pins ?? {}).filter(([k, v]) => PINS[k] && PINS[k].version !== v);
173
+ for (const [k, v] of drift) add(`pin ${k}`, 'changed', `installed ${v}, core/pins.json has ${PINS[k].version} (run --update)`);
174
+ if (state.pins && !drift.length) add('pinned versions', 'ok', `${Object.keys(state.pins).length} pins match core/pins.json`);
175
+ for (const c of state.commands) add(c.desc, c.ok ? 'ok' : 'error', c.ok ? '' : 'failed at install time');
176
+ if (o.tools.includes('i-have-adhd')) {
177
+ const reset = adhdSkillFiles(home).filter((f) => fs.readFileSync(f, 'utf8').includes('disable-model-invocation: true'));
178
+ if (reset.length) add('i-have-adhd skill', 'changed', 'a plugin update reset it; run --update');
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');
181
+ if (exec) {
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']]) {
183
+ const needed = o.agents.includes(tool) || o.tools.includes(tool);
184
+ if (!needed) continue;
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');
199
+ }
200
+ for (const [bin, agent] of [['code', 'vscode-copilot'], ['cursor-agent', 'cursor']]) {
201
+ if (!o.agents.includes(agent)) continue;
202
+ const v = version(bin, undefined, childEnv(network));
203
+ add(`${bin} on PATH`, v ? 'ok' : 'error', v ?? 'not found');
204
+ }
205
+ if (!withMcp && ['claude', 'cursor', 'copilot-cli', 'antigravity'].some((a) => o.agents.includes(a))) add('mcp servers', 'skipped', 'network off (outbound off): `mcp list` not run');
206
+ if (o.agents.includes('cursor') && withMcp) checkCursor(o, add, q);
207
+ if (o.agents.includes('claude') && withMcp) {
208
+ const mcp = q(['claude', 'mcp', 'list']);
209
+ for (const s of ['serena', 'playwright'].filter((t) => o.tools.includes(t))) {
210
+ add(`claude mcp ${s}`, mcp.ok && mcp.out.includes(s) ? 'ok' : 'error', mcp.ok ? '' : 'claude mcp list failed');
211
+ }
212
+ }
213
+ if (o.agents.some((a) => a.startsWith('opencode'))) checkOpenCode(o, add, q);
214
+ if (o.agents.includes('copilot-cli')) checkCopilot(o, add, q, withMcp);
215
+ if (o.agents.includes('antigravity')) checkAntigravity(o, CORE_AGENTS, add, q, withMcp, findAgy(home, platform, env) ?? 'agy');
216
+ // npx may have to download, which takes longer than a local check.
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
+ }
225
+ }
226
+ }
227
+ checkAntigravityIde(home, add, fsx);
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
+ }
233
+ const left = leftovers(process.cwd());
234
+ if (left.length) add('parallel workers', 'changed', `left in this repo: ${left.join(', ')} (merge them, then run scripts/parallel.mjs clean)`);
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);
238
+ const ok = !rows.some((r) => r.status === 'error' || r.status === 'missing');
239
+ const behind = state ? behindPins(state) : [];
240
+ if (json) process.stdout.write(`${JSON.stringify({ ok, behind, nodes, skills, rows }, null, 2)}\n`);
241
+ else if (collect) collect.push(...rows);
242
+ else print(rows);
243
+ return ok;
244
+ }
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
+
252
+ function checkOpenCode(o, add, q) {
253
+ const r = q(['opencode', 'debug', 'config']);
254
+ if (!r.ok) return add('opencode resolved config', 'error', '`opencode debug config` failed');
255
+ let cfg;
256
+ try { cfg = resolvedOpenCodeConfig(r.out); } catch { return add('opencode resolved config', 'changed', 'could not parse output; check by hand'); }
257
+ cfg = redact(cfg);
258
+ const servers = cfg.mcp?.servers ?? cfg.mcp ?? {};
259
+ const v1 = o.agents.includes('opencode-v1');
260
+ for (const s of ['context-mode', 'serena', 'playwright', 'playwright-extension'].filter((t) => o.tools.includes(t) && !(v1 && t === 'context-mode'))) {
261
+ add(`opencode mcp ${s}`, servers[s] ? 'ok' : 'error', servers[s] ? '' : 'not in resolved config');
262
+ }
263
+ const plugins = [...(cfg.plugins ?? []), ...(cfg.plugin ?? [])].map(String);
264
+ if (v1 && o.tools.includes('context-mode')) {
265
+ const loaded = plugins.some((p) => p.includes('context-mode'));
266
+ add('opencode plugin context-mode', loaded ? 'ok' : 'error', loaded ? '' : 'not in resolved config');
267
+ }
268
+ if (plugins.some((p) => p.includes('context-mode')) && servers['context-mode']) {
269
+ add('context-mode duplicate', 'error', 'enabled as plugin and MCP; keep one');
270
+ }
271
+ if (plugins.some((p) => p.includes('oh-my-openagent'))) add('oh-my-openagent', 'error', 'present; lean-agents does not support it');
272
+ const instr = (cfg.instructions ?? []).some((i) => String(i).includes('lean-agents'));
273
+ add('opencode rules loaded', instr ? 'ok' : 'error', instr ? '' : 'instructions entry missing');
274
+ }
275
+
276
+ function print(rows) {
277
+ const w = Math.min(48, Math.max(...rows.map((r) => r.item.length)));
278
+ for (const r of rows) console.log(`${r.status.padEnd(8)} ${r.item.padEnd(w)} ${r.detail}`);
279
+ }