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
package/scripts/lean.mjs CHANGED
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import readline from 'node:readline';
8
8
  import tty from 'node:tty';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { plan, apply, undo, describe, writePrivate, privateDir, dropBackups } from './lib/fsops.mjs';
10
+ import { plan, apply, undo, describe, writePrivate, privateDir, dropBackups, renameRetry } from './lib/fsops.mjs';
11
11
  import { loadCore, renderRules, loadProfile, useToolNode } from './lib/render.mjs';
12
12
  import { claudeAdapter } from './lib/adapters/claude.mjs';
13
13
  import { opencodeV1Adapter } from './lib/adapters/opencode-v1.mjs';
@@ -20,20 +20,31 @@ import { projectPlan, projectStateDir } from './lib/project.mjs';
20
20
  import { gsdPlan } from './lib/gsd.mjs';
21
21
  import { MIGRATE_SOURCES, MIGRATE_TARGETS, readSource, detectSources, migratePlan, finishRows, formatTable } from './lib/migrate.mjs';
22
22
  import { adhdCommand } from './lib/adhd.mjs';
23
- import { version as binVersion, gitHint, detectAgents, packageManager, prereqFor, antigravityPrereqs, bunInstall, bunPresent, which, run, quiet, exists, isolate, configHome, envDir } from './lib/system.mjs';
23
+ import { version as binVersion, versionFull, gitHint, detectAgents, packageManager, prereqFor, antigravityPrereqs, bunInstall, bunPathCommand, bunPresent, which, run, quiet, exists, isolate, configHome, envDir } from './lib/system.mjs';
24
24
  import { doctor } from './lib/doctor.mjs';
25
- import { adopt, inventory } from './lib/adopt.mjs';
25
+ import { probePlugins } from './lib/plugin-health.mjs';
26
+ import { adopt, inventory, saveState } from './lib/adopt.mjs';
27
+ import { planPrereqs, pendingPrereqs, everythingAgents, undoArgv, nvmDirExistedBefore } from './lib/prereqs.mjs';
26
28
  import { upgradeInventory, formatUpgrade } from './lib/upgrade.mjs';
27
- import { agentLifecycle } from './lib/agent-lifecycle.mjs';
29
+ import { backupOpencode, backupLayout, listProcesses, opencodeRunning } from './lib/opencode-backup.mjs';
30
+ import { readBackupStamp } from './lib/backup-stamp.mjs';
31
+ import { isActive, failAt, applyPreflight, verifyBackup, configDrift, createSteps, makeCtx, runApply, runUndo, restoreData } from './lib/opencode-upgrade.mjs';
32
+ import { planOpencode1, installOpencode1, removeOpencode1, layout as opencode1Layout } from './lib/opencode1.mjs';
33
+ import { posixPathBlock } from './lib/shell-path.mjs';
34
+ import { agentLifecycle, agentTable, upgradeCommands, undoPlan, undoUpgrades, agentOf, agentStamps, VSCODE_NOTE, AGENT_CLIS } from './lib/agent-lifecycle.mjs';
28
35
  import { copilotUsage } from './lib/copilot-usage.mjs';
29
- import { draftIssue } from './lib/feedback.mjs';
30
- import { pinVersions, behindPins, pinTool, nodeRange, npmSpec } from './lib/pins.mjs';
31
- import { findNvm, resolveToolNodes, nvmLatest, nvmInstallArgv, nvmEnv, toolEnv } from './lib/node-runtime.mjs';
36
+ import { draftIssue, addFiledIssue } from './lib/feedback.mjs';
37
+ import { buildSummary } from './lib/summary-data.mjs';
38
+ import { loginRows } from './lib/logins.mjs';
39
+ import { renderSummary, canOffer, openArgv } from './lib/summary-html.mjs';
40
+ import { planUpdate, changelogNotes, formatUpdatePlan } from './lib/update-plan.mjs';
41
+ import { PINS, pinVersions, behindPins, pinTool, nodeRange, npmSpec } from './lib/pins.mjs';
42
+ import { findNvm, installedNodes, resolveToolNodes, nvmLatest, nvmInstallArgv, nvmEnv, toolEnv, satisfies } from './lib/node-runtime.mjs';
32
43
  import { leanUpdateCommands, coordinateCommands, leanMigrateCommands } from './lib/lean-update.mjs';
33
44
  import { canUseMenus, menuPrompter, menuProgress } from './lib/ui.mjs';
34
45
  import { CATEGORIES, preset, onOff, fromPrivacy, privacyOf, childEnv, shareProxy, proxyReport } from './lib/network.mjs';
35
46
  import { unverifiedItems, notesFile } from './lib/unverified.mjs';
36
- import { detectTerminals, parseTerminal, terminalCommands, terminalPrivacyNotes, orcaEnvSet, gitBashActions, stillNeeded, shellNotice } from './lib/terminals.mjs';
47
+ import { detectTerminals, TERMINALS, parseTerminal, terminalCommands, terminalPrivacyNotes, orcaEnvSet, gitBashActions, stillNeeded, shellNotice } from './lib/terminals.mjs';
37
48
 
38
49
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
39
50
  const ADAPTERS = { claude: claudeAdapter, 'opencode-v1': opencodeV1Adapter, 'opencode-v2': opencodeV2Adapter, 'copilot-cli': copilotAdapter, antigravity: antigravityAdapter };
@@ -42,11 +53,12 @@ const FIXED_PROFILE = { claude: 'claude-subscription', 'copilot-cli': 'github-co
42
53
  Object.assign(ADAPTERS, { 'vscode-copilot': vscodeCopilotAdapter, cursor: cursorAdapter });
43
54
  FIXED_PROFILE['vscode-copilot'] = 'github-copilot';
44
55
  // Extensions cannot be installed silently without admin policy, so the user installs it.
56
+ const CODE_MODE_NOTE = 'Claude Code Code Mode is experimental (Claude Code 2.1.323 or newer, interactive terminal only, a direct Anthropic subscription or Console login; not Vertex, Bedrock or a gateway). A session started with it resumes only with it on; --uninstall turns it off';
45
57
  const EXTENSION_NOTE = 'install the Playwright Extension yourself from https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm . Each session asks you to approve the connection; optional auto-approve: docs/browser-extension.md';
46
58
  const MINIMAL_TOOLS = ['rtk', 'context-mode'];
47
59
  const OPTIONAL_TOOLS = ['serena', 'playwright', 'ponytail', 'caveman', 'i-have-adhd', 'dcp', 'codeburn', 'copilot-usage'];
48
60
  // Asked for one by one and never part of --all-tools.
49
- const OPT_IN_TOOLS = ['gsd', 'autoskills', 'playwright-extension', 'coordinate', 'lean-migrate'];
61
+ const OPT_IN_TOOLS = ['gsd', 'autoskills', 'playwright-extension', 'coordinate', 'lean-migrate', 'code-mode'];
50
62
  const TOOL_INFO = {
51
63
  serena: 'Serena MCP: symbol-level code navigation, so agents read less code',
52
64
  playwright: 'Playwright MCP: lets agents drive a browser to check web UIs',
@@ -60,6 +72,7 @@ const TOOL_INFO = {
60
72
  gsd: 'GSD Core: spec-driven workflow skills and agents (large install)',
61
73
  'lean-migrate': 'lean-migrate skill: guides the OpenCode 1.x to 2.x upgrade through --upgrade-agent opencode (dry run first)',
62
74
  coordinate: 'Coordinate skill: playbook, session prompt and watcher to run several agents in separate git worktrees',
75
+ 'code-mode': 'Claude Code Code Mode (experimental): Claude runs tool calls from small scripts; needs a direct Anthropic login, sessions started with it resume only with it on',
63
76
  autoskills: 'AutoSkills: picks skills per project, run with npx (CC BY-NC 4.0: non-commercial use only)',
64
77
  };
65
78
 
@@ -83,8 +96,10 @@ function parseArgs(argv) {
83
96
  case '--tools': o.tools = [...new Set([...MINIMAL_TOOLS, ...list(next())])]; break;
84
97
  case '--all-tools': o.tools = [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS]; break;
85
98
  case '--no-tools': o.tools = []; break;
99
+ case '--everything': o.everything = true; break;
86
100
  case '--no-core': o.core = false; break;
87
101
  case '--terminal': o.terminals = parseTerminal(next()); break;
102
+ case '--install-terminal': o.installTerminals = parseTerminal(next()); break;
88
103
  case '--bun': o.bun = true; break;
89
104
  case '--no-bun': o.bun = false; break;
90
105
  case '--no-app': o.app = false; break;
@@ -92,6 +107,7 @@ function parseArgs(argv) {
92
107
  case '--gh': o.gh = true; break;
93
108
  case '--no-gh': o.gh = false; break;
94
109
  case '--json': o.json = true; break;
110
+ case '--probe-plugins': o.probePlugins = true; break;
95
111
  case '--feedback-draft': o.command = 'feedback'; break;
96
112
  case '--failed-command': o.failedCommand = next(); break;
97
113
  case '--feedback-kind': o.feedbackKind = next(); break;
@@ -112,19 +128,34 @@ function parseArgs(argv) {
112
128
  case '--update': o.command = 'update'; break;
113
129
  case '--uninstall': o.command = 'uninstall'; break;
114
130
  case '--doctor': o.command = 'doctor'; break;
131
+ case '--summary': o.command = 'summary'; break;
132
+ case '--no-open': o.noOpen = true; break;
133
+ case '--filed-issue': (o.filedIssues ??= []).push(next()); break;
115
134
  case '--adopt': o.command = 'adopt'; break;
116
- case '--upgrade-agent': o.command = 'upgrade-agent'; o.upgradeAgent = next(); if (o.upgradeAgent !== 'opencode') throw new Error('--upgrade-agent takes opencode'); break;
135
+ case '--upgrade-agent': o.command = 'upgrade-agent'; o.upgradeAgent = next(); if (!['opencode', 'vscode-copilot'].includes(o.upgradeAgent)) throw new Error('--upgrade-agent takes opencode or vscode-copilot'); break;
117
136
  case '--undo': o.undo = true; break;
118
137
  case '--keep-backup': o.keepBackup = true; break;
138
+ case '--backup': o.backup = true; break;
139
+ case '--opencode1': o.opencode1 = true; break;
119
140
  case '--confirm-removals': o.confirmRemovals = true; break;
120
- case '--install-agent': case '--uninstall-agent': o.command = 'agent'; o.agentMode = a.slice(2, -6); o.agentList = list(argv[i + 1]?.startsWith('--') ? '' : next() ?? ''); if (!o.agentList.length) throw new Error(`${a} needs an agent list (claude, opencode-v2, copilot-cli, cursor, antigravity)`); break;
141
+ case '--install-agent': case '--uninstall-agent': o.command = 'agent'; o.agentMode = a.slice(2, -6); o.agentList = list(argv[i + 1]?.startsWith('--') ? '' : next() ?? ''); if (!o.agentList.length) throw new Error(`${a} needs an agent list (claude, opencode-v2, copilot-cli, cursor, antigravity, vscode-copilot)`); break;
121
142
  case '--usage': o.command = 'usage'; break;
122
- case '--skip-agents': case '--no-admin': break; // defaults in v1: agents are never installed, nothing needs admin
143
+ case '--skip-agents': case '--no-admin': console.error(`! ${a} does nothing (agents are never installed, nothing needs admin) and will be removed in the next release.`); break;
123
144
  case '--help': case '-h': o.command = 'help'; break;
124
145
  case '--version': o.command = 'version'; break;
125
146
  default: throw new Error(`unknown option ${a} (see --help)`);
126
147
  }
127
148
  }
149
+ if (o.everything && !o.migrate) {
150
+ // Preset for a fresh machine: every default is taken, so the plan is the only question.
151
+ o.tools ??= [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS];
152
+ o.gh ??= true;
153
+ o.bun ??= true;
154
+ o.lang ??= 'en';
155
+ o.profile ??= 'none';
156
+ o.ponytailMode ??= 'lite';
157
+ o.adhdAlways ??= true;
158
+ }
128
159
  if (!o.core && o.tools) o.tools = o.tools.filter((t) => !MINIMAL_TOOLS.includes(t));
129
160
  return o;
130
161
  }
@@ -133,6 +164,8 @@ const HELP = `Usage: lean-agents [options]
133
164
 
134
165
  --dry-run Show every file change and command; change nothing
135
166
  --yes Accept defaults without asking
167
+ --everything Fresh-machine preset: plan the prerequisites (Homebrew, nvm, Node 24, uv, RTK, Bun) and Claude Code +
168
+ OpenCode 2 with every optional tool, show one plan, ask once (--yes accepts; --dry-run --json prints it)
136
169
  --agents a,b ${Object.keys(ADAPTERS).join(', ')}
137
170
  (default: the ones installed)
138
171
  --tools a,b Optional tools on top of rtk and context-mode:
@@ -148,12 +181,16 @@ const HELP = `Usage: lean-agents [options]
148
181
  --terminal warp|orca|both|none
149
182
  Agent integrations for a terminal you already have (default: the detected ones;
150
183
  ignored with --project)
184
+ --install-terminal warp|orca|both
185
+ Install the terminal app and its agent integrations (macOS: Warp requires brew)
151
186
  --gh / --no-gh Install GitHub CLI (gh) if it is missing (default: on; you run gh auth login yourself)
152
187
  --feedback-draft After a failed install: read the error on stdin, print a redacted issue draft as JSON
153
188
  (--feedback-kind update: the text is a finding from an update, not an error)
154
189
  ({"offer":false} when the network preset forbids it). Needs --failed-command <text>;
155
190
  pass --network on|off when nothing is installed yet. Files nothing.
156
- --json With --dry-run or --doctor: print one JSON object on stdout (messages go to stderr)
191
+ --no-exec Run no external command (no installs, no version probes); --uninstall refuses it when commands need undoing
192
+ --probe-plugins With --doctor or --adopt: start a short-lived opencode serve (throwaway state dir, loopback) and check a plugin's command registers
193
+ --json With --dry-run, --doctor or --yes: print one JSON object on stdout (messages go to stderr)
157
194
  --no-app Do not install the Antigravity app (the CLI is still installed when missing)
158
195
  --bun / --no-bun Install Bun for Context Mode (default: on; faster JS, TypeScript)
159
196
  --project <dir> Write the shared team files into one repository
@@ -166,8 +203,14 @@ const HELP = `Usage: lean-agents [options]
166
203
  --shell default|git-bash OpenCode on Windows: set its shell to Git Bash when found (default: git-bash;
167
204
  never overwrites a shell you set yourself; "default" opts out)
168
205
  --update Re-apply with your saved choices
206
+ --update --undo [--yes]
207
+ Put each agent CLI that --update upgraded back on the version it had before its first upgrade
208
+ (plan first, then a confirm; a failed step is reported and the rest run). --uninstall leaves
209
+ upgraded agent CLIs alone; use --uninstall-agent for ones lean-agents installed
169
210
  --uninstall Undo everything lean-agents changed
170
211
  --doctor Check the install
212
+ --summary Write the summary page (summary.html in the state dir; --uninstall removes it) and ask before opening it.
213
+ --filed-issue "item=issue url" records an issue you filed; --no-open only prints the path
171
214
  --adopt List what a hand-built machine already has (MCPs, hooks, plugins, skills, npm copies),
172
215
  classify each (managed, user, stale, duplicate, drift, wrong-node) and print the planned
173
216
  actions; changes nothing (with --json: one JSON object). Always pass --home to try it
@@ -176,11 +219,27 @@ const HELP = `Usage: lean-agents [options]
176
219
  hand-made stopgaps (all backed up; on a terminal a menu asks instead)
177
220
  --keep-backup Keep the backup after a verified --adopt --yes (--adopt --undo needs it to restore bytes)
178
221
  --upgrade-agent opencode Dry run: classify the OpenCode 1.x config as managed, translatable to 2.x or manual and print the
179
- translation table; changes nothing (with --json: one JSON object). Apply and --undo come later
222
+ translation table; changes nothing (with --json: one JSON object)
223
+ --upgrade-agent opencode --yes
224
+ Apply, after --backup --yes made a verified backup: opencode1, install OpenCode 2, translate the
225
+ config, add DCP. Steps are journaled in state.json; a failed step undoes the finished ones
226
+ --upgrade-agent opencode --undo [--yes]
227
+ Back to 1.x: undo each step, move the 2.x db aside, copy the frozen copy back. Never deletes the
228
+ backup or the frozen copy. Plan first; --yes does it
229
+ --upgrade-agent opencode --backup [--dry-run|--yes]
230
+ Permanent sha256-checked backup of the OpenCode 1.x sessions and config, then a frozen copy for
231
+ opencode1; the live data is only read. Plan first (the default); --yes copies. Refuses while
232
+ OpenCode runs or free space is under 2 x size + 1 GB
233
+ --upgrade-agent opencode --opencode1 [--dry-run|--yes]
234
+ After --backup: copy the OpenCode 1.x binary next to the frozen copy and add opencode1, which runs
235
+ 1.x on that copy only (XDG_DATA_HOME + XDG_STATE_HOME), to PATH. --uninstall removes it
180
236
  --undo With --adopt: restore what the last --adopt --yes changed
237
+ --upgrade-agent vscode-copilot
238
+ Report only: VS Code owns the Copilot extension; --update refreshes the files lean-agents wrote
181
239
  --install-agent a,b / --uninstall-agent a,b
182
240
  Install (claude, opencode-v2, copilot-cli, cursor, antigravity) or remove the agent CLIs
183
- lean-agents itself installed; plan first, --yes to run. Never OpenCode 1.x
241
+ lean-agents itself installed; plan first, --yes to run. Never OpenCode 1.x.
242
+ vscode-copilot: configure or remove only the files lean-agents wrote (VS Code owns the extension)
184
243
  --version Print the lean-agents version
185
244
  --usage Print the Copilot credits left (one gh call, no model request)
186
245
  `;
@@ -253,8 +312,14 @@ async function chooseMigration(o, p) {
253
312
  }
254
313
 
255
314
  async function choose(o, saved) {
256
- const p = await prompter(o.yes);
315
+ // --everything answers every question with its default; install() asks the one plan question.
316
+ const p = await prompter(o.yes || o.everything);
257
317
  if (o.migrate) return chooseMigration(o, p);
318
+ if (!o.agents && o.everything) {
319
+ const team = everythingAgents({ platform: process.platform, project: !!o.project, detected: process.platform === 'win32' ? detectAgents() : {} }); // detection only matters for the Windows team preset
320
+ o.agents = team.agents;
321
+ if (team.skipped.length) o.agentNotes = [`not found, skipped: ${team.skipped.join(', ')} (install them, then rerun --everything)`];
322
+ }
258
323
  if (!o.agents) {
259
324
  o.agents = saved?.agents ?? [];
260
325
  if (!saved) {
@@ -292,16 +357,50 @@ async function choose(o, saved) {
292
357
  const resolved = resolveToolNodes({ pins: needs, active: NODE_VERSION, nvm, latest: (major) => nvmLatest(nvm, major, { run: quiet }) });
293
358
  for (const s of resolved.skipped) console.log(s.line);
294
359
  o.tools = o.tools.filter((t) => !resolved.skipped.some((s) => s.tool === t));
360
+ o.deferred = resolved.skipped.map((s) => s.tool);
295
361
  o.toolNode = resolved.toolNode && { ...resolved.toolNode, nvmDir: nvm.dir };
296
362
  if (o.toolNode && o.agents.includes('claude') && o.tools.includes('context-mode')) console.log('Context Mode on Claude Code runs as an MCP server on its own Node: its hooks and skills (the plugin) are not installed.');
297
- if (o.project) o.terminals = [];
298
- else if (!o.terminals) {
299
- // Terminals are never installed, only detected; nothing found means no question.
363
+ if (o.project) {
364
+ o.terminals = [];
365
+ o.installTerminals = [];
366
+ } else if (!o.terminals) {
300
367
  const found = detectTerminals(o.home, { system: o.home === REAL_HOME });
301
368
  o.terminals = saved ? saved.terminals ?? [] : found;
302
- if (!saved && found.length) {
303
- const items = found.map((t) => ({ value: t, label: t, ask: `Add the ${t} agent integration?` }));
304
- o.terminals = await p.multi({ message: 'Terminals found: add their agent integrations', items, defaults: found });
369
+ o.installTerminals = o.installTerminals ?? saved?.installTerminals ?? [];
370
+ if (!saved) {
371
+ const askIntegrate = found.map((t) => ({ value: t, label: `${t} integration (app already installed)`, ask: `Add the ${t} agent integration?` }));
372
+ const missing = TERMINALS.filter((t) => !found.includes(t));
373
+ const askInstall = (o.home === REAL_HOME && (process.platform === 'darwin' || process.platform === 'win32'))
374
+ ? missing.map((t) => ({ value: t, label: `Install ${t} + integration`, ask: `Install the ${t} app and its agent integration?` }))
375
+ : [];
376
+
377
+ if (askIntegrate.length || askInstall.length) {
378
+ const picked = await p.multi({
379
+ message: 'Terminals (Warp, Orca)',
380
+ items: [...askIntegrate, ...askInstall],
381
+ defaults: found,
382
+ });
383
+
384
+ o.installTerminals = [...new Set([...o.installTerminals, ...picked.filter(t => missing.includes(t))])];
385
+ o.terminals = [...new Set([...picked, ...o.installTerminals])];
386
+ } else {
387
+ o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
388
+ }
389
+ } else {
390
+ o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
391
+ }
392
+ } else {
393
+ o.installTerminals = o.installTerminals ?? saved?.installTerminals ?? [];
394
+ o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
395
+ }
396
+ if (o.installTerminals?.length) {
397
+ const isReal = o.home === REAL_HOME;
398
+ const isSupported = process.platform === 'darwin' || process.platform === 'win32';
399
+ if (!isReal || !isSupported) {
400
+ for (const t of o.installTerminals) {
401
+ const reason = !isReal ? 'temp home' : `unsupported platform ${process.platform}`;
402
+ console.log(`! ${t} app: not installed (${reason})`);
403
+ }
305
404
  }
306
405
  }
307
406
  await chooseNetwork(o, saved, p);
@@ -329,6 +428,7 @@ async function choose(o, saved) {
329
428
  const NETWORK_INFO = { telemetry: 'telemetry and error reports', autoUpdate: 'auto-updates', outbound: 'other outbound calls (session sharing, feedback, built-in providers)' };
330
429
 
331
430
  async function chooseNetwork(o, saved, p) {
431
+ let perCategory = null;
332
432
  let base = o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? saved?.network ?? fromPrivacy(saved?.privacy);
333
433
  if (!base && !Object.keys(o.networkFlags).length) {
334
434
  const a = await p.select({
@@ -345,9 +445,12 @@ async function chooseNetwork(o, saved, p) {
345
445
  else if (a === 'choose') {
346
446
  base = {};
347
447
  for (const c of CATEGORIES) base[c] = yesNo(await p.ask(`Keep ${NETWORK_INFO[c]} on?`, 'y')) ? 'on' : 'off';
448
+ perCategory = base;
348
449
  } else throw new Error(`network takes off, on or choose, not "${a}"`);
349
450
  }
350
451
  o.network = { ...(base ?? preset('on')), ...o.networkFlags };
452
+ // Updates the user asked for (flag, per-category menu, or the saved choice) keep the agent's own updater; a plain "on" preset does not.
453
+ o.keepUpdater = o.network.autoUpdate === 'on' && (o.networkFlags.autoUpdate === 'on' || perCategory?.autoUpdate === 'on' || (!o.networkPreset && !!saved?.keepUpdater));
351
454
  o.privacy = privacyOf(o.network);
352
455
  }
353
456
 
@@ -385,7 +488,7 @@ function migrationPlan(o) {
385
488
  return { planned, commands: r.commands, migration: { ...r, rows: finishRows(r.rows, planned, o.exec), base, names } };
386
489
  }
387
490
 
388
- function buildPlan(o) {
491
+ function buildPlan(o, every = null) {
389
492
  if (o.migrate) return migrationPlan(o);
390
493
  if (o.project) {
391
494
  const r = projectPlan(ROOT, o.project, o);
@@ -406,7 +509,7 @@ function buildPlan(o) {
406
509
  commands.push(...leanUpdateCommands(o.agents));
407
510
  if (o.tools.includes('coordinate')) commands.push(...coordinateCommands(o.agents));
408
511
  if (o.tools.includes('lean-migrate')) commands.push(...leanMigrateCommands(o.agents));
409
- commands.push(...terminalCommands({ terminals: o.terminals, agents: o.agents, network: o.network, system: o.home === REAL_HOME }));
512
+ commands.push(...terminalCommands({ home: o.home, terminals: o.terminals, installTerminals: o.installTerminals, agents: o.agents, network: o.network, system: o.home === REAL_HOME, platform: process.platform }));
410
513
  actions.push(...gitBashActions({ home: o.home, terminals: o.terminals, agents: o.agents }));
411
514
  if (o.tools.includes('gsd')) {
412
515
  const r = gsdPlan(ROOT, o.home, o);
@@ -416,6 +519,7 @@ function buildPlan(o) {
416
519
  if (o.bun && o.network.telemetry === 'off') {
417
520
  actions.push({ kind: 'block', toml: true, path: path.join(o.home, '.bunfig.toml'), body: 'telemetry = false' });
418
521
  }
522
+ actions.push(...posixPathActions(o, every));
419
523
  return { planned: plan(actions, writeRoots(o), readState(o.home)?.files), commands };
420
524
  }
421
525
 
@@ -433,8 +537,8 @@ function prereqCommands(o, behind = new Set()) {
433
537
  }
434
538
  const p = prereqFor(t, pm);
435
539
  if (!p || (which(p.bin) && !behind.has(t))) continue;
436
- if (p.install) out.push({ tool: t, desc: `install ${p.bin}`, run: p.install, undo: [], optional: t === 'gh' });
437
- else out.push({ tool: t, desc: `${p.bin} is missing: install it from ${p.manual}`, run: [], undo: [], manual: true, optional: t === 'gh' });
540
+ if (p.install) out.push({ tool: t, desc: `install ${p.bin}`, run: p.install, undo: [], optional: t === 'gh', bin: p.bin });
541
+ else out.push({ tool: t, desc: `${p.bin} is missing: install it from ${p.manual}`, run: [], undo: [], manual: true, optional: t === 'gh', bin: p.bin });
438
542
  }
439
543
  if (o.agents.includes('antigravity')) {
440
544
  for (const c of antigravityPrereqs(pm, process.platform, o.home, o.app)) {
@@ -443,16 +547,52 @@ function prereqCommands(o, behind = new Set()) {
443
547
  }
444
548
  }
445
549
  if (o.bun && o.tools.includes('context-mode') && process.platform !== 'linux' && !which('bun') && bunPresent(o.home)) {
446
- console.log('! Bun is in ~/.bun/bin but not on PATH; Context Mode needs it on PATH here. Add that folder to PATH.');
550
+ if (process.platform === 'win32') out.push(bunPathCommand(o.home));
551
+ else console.log('! Bun is in ~/.bun/bin but not on PATH; Context Mode needs it on PATH here. Add that folder to PATH.');
447
552
  }
448
553
  if (o.bun && o.tools.includes('context-mode') && !bunPresent(o.home)) {
449
554
  const b = bunInstall(o.home, stateDir(o.home), process.platform, pm);
450
555
  if (b) out.push(b);
451
- else console.log('! Bun needs Homebrew here: install it from https://bun.com/docs/installation. Context Mode will run on Node.');
556
+ else if (!o.everything) console.log('! Bun needs Homebrew here: install it from https://bun.com/docs/installation. Context Mode will run on Node.'); // --everything: the planner installs Homebrew, then Bun
452
557
  }
453
558
  return out;
454
559
  }
455
560
 
561
+ // The agents --everything configures whose CLI is missing and that --install-agent can install. Not recorded in state.json:
562
+ // agents.json records them, and --uninstall-agent removes them, like a separate --install-agent run.
563
+ function everythingCliInstalls(o, gitPending) {
564
+ const table = agentTable({ home: o.home, platform: process.platform, dir: stateDir(o.home), realHome: REAL_HOME, gitBash: gitPending ? 'bash.exe' : undefined });
565
+ return o.agents.filter((a) => AGENT_CLIS[a] && table[a] && !table[a].manual && !which(AGENT_CLIS[a])).map((a) => ({
566
+ desc: `install the ${AGENT_CLIS[a]} CLI (${table[a].method}${table[a].version ? ` ${table[a].version}` : ''})`, run: [], undo: [], lifecycle: a, bins: table[a].bins,
567
+ }));
568
+ }
569
+
570
+ // --everything: the planner's steps as engine commands. Probes the machine here; the planner itself stays pure.
571
+ function everythingPrereqs(o, saved) {
572
+ const mac = process.platform === 'darwin';
573
+ const has = {
574
+ brew: !!which('brew'), winget: !!which('winget'), uv: !!which('uv'), rtk: !!which('rtk'), jq: !!which('jq'), bun: bunPresent(o.home), git: !!which('git'),
575
+ clt: mac && quiet(['xcode-select', '-p']).ok, nvm: !!o.nvm, apt: !!which('apt-get'), sudo: !!which('sudo'), unzip: !!which('unzip'),
576
+ };
577
+ const steps = planPrereqs({
578
+ nvmDirExisted: nvmDirExistedBefore(saved?.commands, fs.existsSync(path.join(o.home, '.nvm'))),
579
+ platform: process.platform, arch: process.arch, home: o.home, tmp: stateDir(o.home), execPath: process.execPath, has, root: process.getuid?.() === 0,
580
+ nodeActive: NODE_VERSION, nvmNodes: o.nvm ? installedNodes(o.nvm).map((n) => n.version) : [],
581
+ proxyEnv: proxyReport().map((l) => l.split('=')[0]), done: (saved?.commands ?? []).filter((c) => c.ok && c.resumeKey).map((c) => c.resumeKey),
582
+ needsGit: true, terminals: o.terminals, agents: o.agents,
583
+ });
584
+ const commands = pendingPrereqs(steps).map((s) => s.commands.length
585
+ ? { tool: s.id === 'node-24' ? 'node' : s.id, desc: `prerequisite: ${s.label}`, run: s.commands, undo: s.undo ?? [], optional: s.id === 'bun', resumeKey: s.resumeKey, ...(s.id === 'node-24' && o.nvm && { env: nvmEnv(o.nvm.dir) }) }
586
+ : { tool: s.id, desc: `${s.label} is missing: install it from ${s.manual}`, run: [], undo: [], manual: true, optional: true, resumeKey: s.resumeKey });
587
+ return { steps, commands };
588
+ }
589
+
590
+ function printPrereqs(steps, exec) {
591
+ console.log('\nPrerequisites (installed first, only what is missing; your own Node stays the default):');
592
+ for (const s of steps) console.log(` - ${s.label}: ${s.skipIf ? `skipped (${s.skipIf})` : s.commands.length ? 'will install' : `install it yourself: ${s.manual}`} | ${s.why}`);
593
+ if (!exec) console.log(' (--no-exec: not run)');
594
+ }
595
+
456
596
  function printMigration(o, m, commands) {
457
597
  const rel = (p) => (p.startsWith(o.home) ? `~${p.slice(o.home.length)}` : p.startsWith(m.base) ? `.${p.slice(m.base.length)}` : p);
458
598
  console.log(`\nlean-agents migration: ${m.names.join(', ')} -> ${o.agents.join(', ')}${o.project ? ` (project ${o.project})` : ''}`);
@@ -465,30 +605,52 @@ function printMigration(o, m, commands) {
465
605
  }
466
606
 
467
607
  // Agents parse this instead of scraping the text plan. Paths use ~ so no home directory leaks.
468
- function printJson(o, planned, commands, migration, behind) {
608
+ function printJson(o, planned, commands, migration, behind, prereqs, update) {
469
609
  const rel = (t) => (t.startsWith(o.home + path.sep) || t === o.home ? `~${t.slice(o.home.length)}` : t);
470
610
  const inText = (t) => t.split(o.home).join('~');
471
611
  const plan = {
472
612
  agents: o.agents, tools: o.tools, privacy: o.privacy, lang: o.lang, profile: o.profile ?? null, terminals: o.terminals,
473
- gh: !!o.gh, bun: !!o.bun, network: o.network, migrate: migration ? migration.names : null,
613
+ ...(o.everything && { afterNvm: o.deferred ?? [], agentNotes: o.agentNotes ?? [] }), gh: !!o.gh, bun: !!o.bun, network: o.network, migrate: migration ? migration.names : null,
474
614
  files: planned.map((f) => ({ status: f.status, path: rel(f.path), note: f.note ?? null })),
475
- commands: commands.map((c) => ({ desc: inText(c.desc), agent: c.agent ?? null, run: c.run.map((a) => a.map(inText)) })),
615
+ commands: commands.map((c) => ({ desc: inText(c.desc), agent: c.agent ?? null, run: [...c.run, ...(c.always ?? [])].map((a) => a.map(inText)) })),
476
616
  ...(behind && { behind }),
617
+ ...(update && { update }),
618
+ ...(prereqs && { prereqs: prereqs.map((s) => ({ id: s.id, label: s.label, why: s.why, status: s.skipIf ? 'skip' : s.commands.length ? 'install' : 'manual', skipIf: s.skipIf, manual: s.manual ?? null })) }),
477
619
  };
478
620
  process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
479
621
  }
480
622
 
481
- function printPlan(o, planned, commands) {
623
+ // One JSON object on stdout after a real apply (--json --yes). Field names are a contract: see docs/install-json.md.
624
+ function printApplied(o, files, commands, errors) {
625
+ // The home becomes ~; any other absolute path (a --project dir, node's own) is masked like the files are.
626
+ const inText = (t) => t.split(o.home).join('~').replace(/(^|[\s'"=(])(?:\/|[A-Za-z]:[\\/])[^\s'")]*/g, '$1<outside-home>');
627
+ // Never an absolute path: --project files live outside the home.
628
+ const rel = (t) => { const r = path.relative(o.home, t); return r === '..' || r.startsWith(`..${path.sep}`) || path.isAbsolute(r) ? '<outside-home>' : r.split(path.sep).join('/') || '.'; };
629
+ process.stdout.write(`${JSON.stringify({
630
+ ok: errors.length === 0,
631
+ files: files.map((f) => rel(f.path)),
632
+ commands: commands.map((c) => ({ ...c, desc: inText(c.desc), ...(c.run && { run: c.run.map((a) => a.map(inText)) }) })),
633
+ errors: errors.map(inText),
634
+ version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
635
+ }, null, 2)}\n`);
636
+ }
637
+
638
+ function printPlan(o, planned, commands, behind = new Set()) {
482
639
  console.log(`\nlean-agents plan for ${o.agents.join(', ') || 'no agents'}`);
483
640
  if (o.project) console.log(` project: ${o.project}`);
641
+ for (const n of o.agentNotes ?? []) console.log(` agents ${n}`);
484
642
  console.log(` tools: ${o.tools.join(', ') || 'none'} | privacy: ${o.privacy} | lang: ${o.lang} | profile: ${o.profile ?? 'none'}`);
485
643
  if (o.terminals.length) console.log(` terminals: ${o.terminals.join(', ')}`);
486
644
  if (o.network.telemetry === 'off') for (const n of terminalPrivacyNotes(o.terminals, { orcaEnvSet: orcaEnvSet({ system: o.home === REAL_HOME }) })) console.log(` ${n}`);
645
+ if (o.everything && o.deferred?.length) console.log(` after nvm: run lean-agents --update to add ${o.deferred.join(', ')} (they need Node 24, which the prerequisites install under nvm)`);
487
646
  if (o.tools.includes('context-mode')) console.log(` bun: ${o.bun ? `on${bunPresent(o.home) ? ' (already installed)' : ''}` : 'off'}`);
488
647
  console.log(` network: ${CATEGORIES.map((c) => `${c} ${o.network[c]}`).join(', ')}`);
648
+ const owned = o.agents.filter((a) => /^(claude|copilot-cli|opencode-v[12])$/.test(a));
649
+ if (o.network.autoUpdate === 'on' && !o.keepUpdater && owned.length) console.log(` auto-update: ${owned.join(', ')} keep their own updater off because --update owns updates (--auto-update on leaves it alone)`);
489
650
  const net = proxyReport();
490
651
  if (net.length) console.log(` proxy and CA (passed to every command): ${net.join(' ')}`);
491
652
  if (o.tools.includes('playwright-extension')) console.log(` signed-in browser: ${EXTENSION_NOTE}`);
653
+ if (o.tools.includes('code-mode') && o.agents.includes('claude')) console.log(` code mode: ${CODE_MODE_NOTE}`);
492
654
  if (o.notes.length) console.log(` your notes for undocumented settings (saved, never applied): ${o.notes.map((n) => path.basename(n.path, '.md')).join(', ')}`);
493
655
  console.log('');
494
656
  console.log('Files:');
@@ -496,98 +658,243 @@ function printPlan(o, planned, commands) {
496
658
  if (commands.length) {
497
659
  console.log('\nCommands:');
498
660
  for (const c of commands) {
499
- console.log(` - ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
500
- for (const argv of c.run) console.log(` $ ${argv.join(' ')}`);
661
+ // Same check as the run below: an install already there at its pin is skipped, so do not list its commands.
662
+ const there = !behind.has(c.tool) && ((c.skipIfExists && exists(c.skipIfExists)) || (o.exec && c.skipIfOutput && quiet(c.skipIfOutput.cmd).ok));
663
+ console.log(` - ${c.desc}${c.agent ? ` (${c.agent})` : ''}${there ? ': already there, skipped' : ''}`);
664
+ if (there) continue;
665
+ for (const argv of [...c.run, ...(c.always ?? [])]) console.log(` $ ${argv.join(' ')}`);
501
666
  }
502
667
  }
503
668
  console.log('');
504
669
  }
505
670
 
671
+ // --update: rows `tool: installed -> pin` plus the shipped CHANGELOG sections after the installed lean-agents version.
672
+ function updateInfo(o, saved) {
673
+ const agentsFile = path.join(stateDir(o.home), 'agents.json');
674
+ let owned = [];
675
+ try { owned = Object.keys(JSON.parse(fs.readFileSync(agentsFile, 'utf8')).agents ?? {}); } catch { /* absent or unreadable: no agent is ours */ }
676
+ // --no-exec runs no external command, not even a version probe: the agent rows then show nothing installed.
677
+ let installed = { claude: null, opencode: null, copilot: null };
678
+ if (o.exec) {
679
+ // A scratch HOME: `opencode --version` writes a log under HOME, and a dry run must leave --home untouched.
680
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'lean-probe-'));
681
+ const env = { HOME: scratch, USERPROFILE: scratch };
682
+ const probe = (b) => versionFull(b, ['--version'], env);
683
+ installed = { claude: probe('claude'), opencode: probe('opencode'), copilot: probe('copilot') };
684
+ fs.rmSync(scratch, { recursive: true, force: true });
685
+ }
686
+ // planUpdate compares numeric versions; the raw string (pre-release tag kept) is what an undo reinstalls.
687
+ const numeric = Object.fromEntries(Object.entries(installed).map(([b, v]) => [b, v?.replace(/-.*/, '') ?? null]));
688
+ const raw = { 'claude-code': installed.claude, 'opencode-v2': installed.opencode, 'copilot-cli': installed.copilot };
689
+ const rows = planUpdate({ saved, pins: PINS, owned, installed: numeric }).map((r) => (r.action === 'update' && raw[r.tool] ? { ...r, raw: raw[r.tool] } : r));
690
+ const log = path.join(ROOT, 'CHANGELOG.md');
691
+ const current = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
692
+ return { rows, notes: changelogNotes(fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '', saved.version ?? '0.0.0', current) };
693
+ }
694
+
695
+ // The folders an --everything run installs into, as one marked rc block (#335). Folders already on PATH are left out.
696
+ function posixPathActions(o, every) {
697
+ if (!every || process.platform === 'win32') return [];
698
+ const pending = new Set(pendingPrereqs(every.steps).map((s) => s.id));
699
+ const dirs = [
700
+ ...(o.agents.includes('claude') || pending.has('uv') || pending.has('rtk') ? ['.local/bin'] : []),
701
+ ...(o.agents.includes('opencode-v2') ? ['.opencode/bin'] : []),
702
+ ];
703
+ const brew = pending.has('homebrew') ? (process.arch === 'arm64' ? '/opt/homebrew' : '/usr/local') : null;
704
+ const privateNode = process.execPath.startsWith(path.join(o.home, '.config', 'lean-agents', 'node') + path.sep);
705
+ return posixPathBlock({ home: o.home, platform: process.platform, envPath: process.env.PATH, dirs, brew, privateNode, shell: process.env.SHELL });
706
+ }
707
+
506
708
  async function install(o) {
507
709
  if (o.json && !o.yes) throw new Error('--json needs --yes: the menus would write questions to stdout');
508
710
  const saved = o.command === 'update' ? readState(o.home) : null;
509
- if (o.command === 'update' && !saved) throw new Error('nothing to update: lean-agents is not installed');
510
- if (o.command === 'update' && saved.options.migrateOnly) throw new Error('nothing to update: only --migrate ran here');
711
+ if (o.command === 'update' && !saved) {
712
+ let found = false;
713
+ try { found = (await inventory({ home: o.home, env: process.env, realHome: REAL_HOME })).items.length > 0; } catch { /* the plain message below */ }
714
+ throw new Error(`nothing to update: lean-agents is not installed${found ? '; run --adopt --yes, then install (--everything --yes)' : ''}`);
715
+ }
716
+ if (o.command === 'update' && saved.options.migrateOnly) throw new Error(`nothing to update: only ${saved.adoptOnly ? '--adopt' : '--migrate'} ran here; install first (--everything --yes)`);
511
717
  const p = await choose(o, saved?.options);
512
- const { planned, commands: agentCommands, migration } = buildPlan(o);
513
- if (migration && !migration.rows.length) { p.close(); console.log('Nothing to migrate: no rules, agents, skills, prompts, MCP servers or hooks found.'); return; }
718
+ const every = o.everything && !o.migrate ? everythingPrereqs(o, readState(o.home)) : null;
719
+ const { planned, commands: agentCommands, migration } = buildPlan(o, every);
720
+ if (migration && !migration.rows.length) { p.close(); console.log('Nothing to migrate: no rules, agents, skills, prompts, MCP servers or hooks found.'); return o.json && printApplied(o, [], [], []); }
514
721
  const behind = new Set((saved ? behindPins(saved) : []).map((b) => pinTool(b.tool)));
515
- const commands = [...(o.exec ? prereqCommands(o, behind) : []), ...agentCommands];
722
+ // The planner owns these installs; the per-tool ones below would repeat them.
723
+ const owned = new Set(pendingPrereqs(every?.steps ?? []).map((s) => (s.id === 'node-24' ? 'node' : s.id)));
724
+ const update = saved && (o.dryRun || o.exec) ? updateInfo(o, saved) : null;
725
+ const upgrades = update && o.exec ? upgradeCommands({ rows: update.rows, home: o.home, dir: stateDir(o.home), realHome: REAL_HOME, stamps: agentStamps(stateDir(o.home)) }) : [];
726
+ const commands = [...(o.exec ? [...every?.commands ?? [], ...prereqCommands(o, behind).filter((c) => !owned.has(c.tool))] : []), ...agentCommands, ...upgrades];
727
+ // --everything on a fresh machine: install the agent CLIs it configures (the --install-agent path), after the prerequisites.
728
+ const cliInstalls = every && o.exec ? everythingCliInstalls(o, pendingPrereqs(every.steps).some((s) => s.id === 'git')) : [];
729
+ commands.splice(commands.length - agentCommands.length - upgrades.length, 0, ...cliInstalls);
730
+
731
+ if (o.exec) {
732
+ const missing = new Map();
733
+ for (const c of commands) {
734
+ if (c.agent && AGENT_CLIS[c.agent] && !cliInstalls.some((x) => x.lifecycle === c.agent)) {
735
+ const cli = AGENT_CLIS[c.agent];
736
+ if ((c.run ?? []).some((argv) => argv[0] === cli) && !which(cli)) {
737
+ if (!missing.has(cli)) missing.set(cli, { agent: c.agent, steps: [] });
738
+ missing.get(cli).steps.push(c.desc);
739
+ }
740
+ }
741
+ }
742
+ if (missing.size > 0) {
743
+ for (const [cli, info] of missing) {
744
+ const others = o.agents.filter((a) => a !== info.agent).join(',') || 'none';
745
+ const warn = `! the ${cli} CLI is not on PATH: ${info.steps.length} steps need it (${info.steps.join(', ')}). Install it first (--install-agent ${info.agent}), or leave it out with --agents ${others}`;
746
+ if (o.json) console.error(warn);
747
+ else console.log(warn);
748
+ }
749
+ if (!o.dryRun) {
750
+ p.close();
751
+ console.log('nothing changed');
752
+ process.exitCode = 1;
753
+ return;
754
+ }
755
+ }
756
+ }
757
+
516
758
  const noGit = migration ? null : gitHint(packageManager());
517
759
  if (noGit) console.log(noGit);
518
- if (o.json) {
519
- if (!o.dryRun) throw new Error('--json needs --dry-run (or --doctor)');
760
+ if (o.json && o.dryRun) {
520
761
  p.close();
521
- return printJson(o, planned, commands, migration, saved ? behindPins(saved) : undefined);
762
+ return printJson(o, planned, commands, migration, saved ? behindPins(saved) : undefined, every?.steps, update ?? undefined);
522
763
  }
523
764
  if (migration) printMigration(o, migration, o.exec ? commands : []);
524
- else printPlan(o, planned, commands);
525
- if (saved && behindPins(saved).length) console.log('Pins that will change (old -> new):');
526
- if (saved) for (const b of behindPins(saved)) console.log(`${b.tool}: ${b.installed} -> ${b.pinned}`);
765
+ else {
766
+ if (every) printPrereqs(every.steps, o.exec);
767
+ printPlan(o, planned, commands, behind);
768
+ }
769
+ if (update) { const text = formatUpdatePlan(update.rows, update.notes); if (text) console.log(text); }
770
+ else if (saved) {
771
+ if (behindPins(saved).length) console.log('Pins that will change (old -> new):');
772
+ for (const b of behindPins(saved)) console.log(`${b.tool}: ${b.installed} -> ${b.pinned}`);
773
+ }
527
774
  if (o.dryRun) { p.close(); console.log('Dry run: nothing was changed.'); return; }
528
- if (!yesNo(await p.ask('Apply these changes?', 'y'))) { p.close(); console.log('Cancelled.'); return; }
529
- p.close();
530
- const ui = p.menus ? await menuProgress() : null;
775
+ // The one question of --everything: the choose() prompter answers by default, so ask on a real one.
776
+ const q = o.everything && !o.yes ? await prompter(false) : p;
777
+ if (q !== p) p.close();
778
+ try { if (!yesNo(await q.ask('Apply these changes?', 'y'))) { console.log('Cancelled.'); return; } } finally { q.close(); }
779
+ // A Homebrew that this run installs is not on this process's PATH yet.
780
+ if (every && process.platform === 'darwin' && pendingPrereqs(every.steps).some((s) => s.id === 'homebrew')) process.env.PATH = `/opt/homebrew/bin${path.delimiter}/usr/local/bin${path.delimiter}${process.env.PATH ?? ''}`;
781
+ // Linux: uv and rtk installers put binaries in ~/.local/bin, which only a new shell may have on PATH.
782
+ if (every && process.platform === 'linux' && pendingPrereqs(every.steps).some((s) => s.id === 'uv' || s.id === 'rtk')) process.env.PATH = `${path.join(o.home, '.local', 'bin')}${path.delimiter}${process.env.PATH ?? ''}`;
783
+ // winget --scope user puts command links (uv, rtk, jq) and Git.Git's git.exe here, and on the saved user PATH, which only new terminals see (nightly fresh-machine, 2026-11-20).
784
+ if (every && process.platform === 'win32' && pendingPrereqs(every.steps).some((s) => s.commands.some((argv) => argv[0] === 'winget'))) {
785
+ // Both: winget resolves the profile folder, which differs from LOCALAPPDATA when USERPROFILE is overridden (CI). An elevated shell gets Git under Program Files.
786
+ const locals = [...new Set([path.join(o.home, 'AppData', 'Local'), process.env.LOCALAPPDATA].filter(Boolean))];
787
+ const gitMachine = process.env.ProgramFiles ? [path.join(process.env.ProgramFiles, 'Git', 'cmd')] : [];
788
+ process.env.PATH = [...locals.flatMap((l) => [path.join(l, 'Microsoft', 'WinGet', 'Links'), path.join(l, 'Programs', 'Git', 'cmd')]), process.env.PATH ?? '', ...gitMachine].join(path.delimiter); // Program Files last: only a fallback
789
+ }
790
+ const ui = q.menus ? await menuProgress() : null;
531
791
  Object.assign(process.env, childEnv(o.network));
532
792
 
533
793
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
534
794
  const backupDir = path.join(stateDir(o.home), 'backups', stamp);
535
- const files = apply(planned, backupDir, o.home, writeRoots(o));
795
+ const previous = readState(o.home);
796
+ const files = [];
536
797
  const ran = [];
537
798
  let failed = 0;
799
+ // Saved as the run goes, so an error or a killed command still leaves a state --uninstall can undo.
800
+ // Resume stamps only matter for an interrupted run; once everything finished they would hide a later removal.
801
+ let finished = false;
802
+ const save = () => {
803
+ const state = {
804
+ version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
805
+ installedAt: previous?.installedAt ?? new Date().toISOString(),
806
+ updatedAt: new Date().toISOString(),
807
+ pins: pinVersions(),
808
+ options: o.migrate ? previous?.options ?? { migrateOnly: true, agents: o.agents, tools: [], privacy: o.privacy, network: o.network, gh: false, terminals: [], installTerminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' } : { agents: o.agents, tools: o.chosenTools ?? o.tools, privacy: o.privacy, network: o.network, keepUpdater: !!o.keepUpdater, gh: o.gh, terminals: o.terminals, installTerminals: o.installTerminals, unverified: o.unverified, lang: o.lang, profile: o.profile, adhdAlways: o.adhdAlways, ponytailMode: o.ponytailMode, bun: o.bun, shell: o.shell },
809
+ ...(o.toolNode && { toolNode: { version: o.toolNode.version, installedByLean: !!o.toolNode.install || (previous?.toolNode?.version === o.toolNode.version && !!previous.toolNode.installedByLean) } }),
810
+ files: [...(previous?.files ?? []), ...files],
811
+ ...(previous?.opencode1 && { opencode1: previous.opencode1 }),
812
+ // --adopt --undo reads this; `adoptOnly` is not carried, so --update works after the install.
813
+ ...(previous?.adopt && { adopt: previous.adopt }),
814
+ ...(previous?.upgrade && { upgrade: previous.upgrade }),
815
+ // A command that ran again replaces its earlier record, so --uninstall undoes it once.
816
+ commands: [...(previous?.commands ?? []).filter((c) => !ran.some((r) => r.desc === c.desc)), ...ran].map(({ resumeKey, ...c }) => (finished ? c : { ...c, ...(resumeKey && { resumeKey }) })),
817
+ };
818
+ privateDir(stateDir(o.home), stateDir(o.home));
819
+ writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
820
+ };
821
+ let applied = false;
822
+ try { apply(planned, backupDir, o.home, writeRoots(o), files); applied = true; } catch (e) {
823
+ if (o.json) printApplied(o, files, [], [e.message]);
824
+ throw e;
825
+ } finally { if (applied || files.length) save(); }
826
+ const report = [];
827
+ const errors = [];
538
828
  if (o.exec) {
829
+ const noCli = new Set(); // agents whose CLI install failed above: their steps would only fail again
539
830
  for (const [i, c] of commands.entries()) {
831
+ if (noCli.has(c.agent) && (c.run ?? []).some((argv) => argv[0] === AGENT_CLIS[c.agent])) { console.log(` skipped: ${c.desc} (no ${AGENT_CLIS[c.agent]} CLI)`); continue; }
540
832
  // gh is on by default, so having no installer for it (no brew or winget) must not fail the run.
541
- if (c.manual) { console.log(`! ${c.desc}`); if (!c.optional) failed++; continue; }
833
+ // Planned before the prerequisites ran: --everything may have installed it since (macOS: brew's uv brings uvx). Not for --update's behind tools.
834
+ if (c.bin && !behind.has(c.tool) && which(c.bin)) continue;
835
+ if (c.manual) { console.log(`! ${c.desc}`); if (!c.optional) { failed++; errors.push(c.desc); } continue; }
542
836
  const there = (c.skipIfExists && exists(c.skipIfExists)) || (c.skipIfOutput && quiet(c.skipIfOutput.cmd).ok);
543
837
  if (there) {
544
838
  if (!behind.has(c.tool)) continue;
545
839
  // Installed at an older pin: undo it, then add it again at the new pin.
546
- if (!c.undo.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env }))) {
840
+ if (!c.undo.every((argv) => run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env, json: o.json }))) {
547
841
  console.log(` ! could not remove the old ${c.desc}; left as it is. Fix it by hand, then --update.`);
548
842
  failed++;
843
+ errors.push(`could not remove the old ${c.desc}`);
549
844
  continue;
550
845
  }
551
846
  }
552
847
  if (ui) ui.step(i + 1, commands.length, c.desc);
553
848
  else console.log(`- ${c.desc}`);
554
- const ok = c.run.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env }));
849
+ if (c.lifecycle) {
850
+ await agentLifecycle({ mode: 'install', agents: [c.lifecycle], home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: false, exec: true, yes: true, ask: async (_q, def) => def, yesNo });
851
+ const bin = c.bins.find((b) => fs.existsSync(b));
852
+ // The installer's PATH change reaches new terminals only: put its folder first here so the agent's steps below find it.
853
+ if (bin) process.env.PATH = `${path.dirname(bin)}${path.delimiter}${process.env.PATH ?? ''}`;
854
+ else { failed++; errors.push(c.desc); noCli.add(c.lifecycle); }
855
+ report.push({ desc: c.desc, ok: !!bin, exit: null });
856
+ if (ui) ui.result(!!bin, c.desc);
857
+ continue;
858
+ }
859
+ // Recorded before it runs, so a command killed midway can still be undone.
860
+ const rec = { desc: c.desc, ok: false, undo: c.undo, ...(c.reinstall && { from: c.from, owner: c.owner, reinstall: c.reinstall, reinstallAlways: c.reinstallAlways }), ...(c.env && { env: c.env }), ...(c.resumeKey && { resumeKey: c.resumeKey }) };
861
+ ran.push(rec);
862
+ save();
863
+ const codes = [];
864
+ const ok = c.run.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env, json: o.json, codes }));
865
+ for (const argv of c.always ?? []) run(argv, { dryRun: false, log: console.log, env: c.env, json: o.json });
866
+ report.push({ desc: c.desc, ok, exit: codes.at(-1) ?? null });
867
+ if (!ok && !c.optional) errors.push(c.desc);
555
868
  if (ui) ui.result(ok || c.optional, c.desc);
556
869
  else if (!ok && !c.optional) console.log(` ! failed: ${c.desc}. Run the command above by hand, then --doctor.`);
557
870
  // An optional step (Bun) that fails only means Context Mode runs on Node; nothing to undo.
558
- if (!ok && c.optional) { console.log(c.tool === 'gh' ? '! gh install failed; install it yourself (--no-gh skips it).' : c.tool === 'lean-update' ? '! lean-update skill failed to install; run the command above by hand later.' : '! Bun install failed; Context Mode will run on Node.'); continue; }
871
+ if (!ok && c.optional) { console.log(c.tool === 'gh' ? '! gh install failed; install it yourself (--no-gh skips it).' : c.tool === 'lean-update' ? '! lean-update skill failed to install; run the command above by hand later.' : '! Bun install failed; Context Mode will run on Node.'); ran.pop(); save(); continue; }
559
872
  if (!ok) failed++;
560
- ran.push({ desc: c.desc, ok, undo: c.undo, ...(c.env && { env: c.env }) });
873
+ rec.ok = ok;
874
+ save();
561
875
  }
562
876
  }
563
- const previous = readState(o.home);
564
- const state = {
565
- version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
566
- installedAt: previous?.installedAt ?? new Date().toISOString(),
567
- updatedAt: new Date().toISOString(),
568
- pins: pinVersions(),
569
- options: o.migrate ? previous?.options ?? { migrateOnly: true, agents: o.agents, tools: [], privacy: o.privacy, network: o.network, gh: false, terminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' } : { agents: o.agents, tools: o.chosenTools ?? o.tools, privacy: o.privacy, network: o.network, gh: o.gh, terminals: o.terminals, unverified: o.unverified, lang: o.lang, profile: o.profile, adhdAlways: o.adhdAlways, ponytailMode: o.ponytailMode, bun: o.bun, shell: o.shell },
570
- ...(o.toolNode && { toolNode: { version: o.toolNode.version, installedByLean: !!o.toolNode.install || (previous?.toolNode?.version === o.toolNode.version && !!previous.toolNode.installedByLean) } }),
571
- files: [...(previous?.files ?? []), ...files],
572
- // A command that ran again replaces its earlier record, so --uninstall undoes it once.
573
- commands: [...(previous?.commands ?? []).filter((c) => !ran.some((r) => r.desc === c.desc)), ...ran],
574
- };
575
- privateDir(stateDir(o.home), stateDir(o.home));
576
- writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
577
877
  if (failed) {
578
878
  console.log(`\n${failed} step(s) failed; see the lines marked ! above. Backups: ${backupDir}`);
579
879
  ui?.summary('Summary', [`${failed} of ${commands.length} commands failed`, `Backups: ${backupDir}`], false);
580
880
  process.exitCode = 1;
581
- return;
881
+ return o.json && printApplied(o, files, report, errors);
582
882
  }
883
+ finished = true;
884
+ save();
885
+ if (o.json) printApplied(o, files, report, errors);
583
886
  console.log(`\nDone. Backups: ${backupDir}`);
887
+ if (!o.project) await summaryPage(o, { updated: o.command === 'update' ? report.filter((r) => r.ok).map((r) => r.desc) : [] });
584
888
  if (o.project) return console.log('Next: review and commit these files. Each teammate runs the installer once for the tools (rtk, context-mode, ...).');
585
889
  console.log('Next: restart your agents, log in to your providers, then run --doctor.');
586
890
  const shell = shellNotice();
587
891
  if (shell) console.log(shell.text);
892
+ const rc = files.find((f) => f.id === 'path');
893
+ if (rc) console.log(`Open a new terminal (or run: . ${rc.path}) so the new PATH takes effect.`);
588
894
  const todo = stillNeeded({ home: o.home, terminals: o.terminals, agents: o.agents });
589
895
  if (todo.length) console.log(`Still needed from you:\n${todo.map((t) => ` - ${t.text}`).join('\n')}`);
590
896
  if (o.tools.includes('playwright-extension')) console.log(`Signed-in browser: ${EXTENSION_NOTE}`);
897
+ if (o.tools.includes('code-mode') && o.agents.includes('claude')) console.log(`Code Mode: ${CODE_MODE_NOTE}`);
591
898
  if (o.gh) console.log('GitHub CLI: run `gh auth login` yourself; lean-agents never handles tokens.');
592
899
  for (const n of o.notes) console.log(`Notes saved: ${n.path}. Ask your agent to apply them, showing you each change first.`);
593
900
  if (o.network.telemetry === 'off' && o.agents.includes('claude')) {
@@ -608,29 +915,261 @@ async function install(o) {
608
915
  ui?.summary('Summary', [`${files.length} files written, ${ran.length} commands run`, `Backups: ${backupDir}`], true);
609
916
  }
610
917
 
918
+ // --update --undo (#278): each agent CLI goes back to the version it had before the first upgrade lean-agents ran.
919
+ // Plan first; the answer (or --yes) runs it. A failed step is reported and the rest still run; --uninstall never does this.
920
+ async function undoAgentUpgrades(o) {
921
+ const S = readState(o.home);
922
+ const stamps = agentStamps(stateDir(o.home));
923
+ const todo = undoPlan(S?.commands ?? [], stamps);
924
+ if (!todo.length) { console.log('nothing to undo: no agent CLI upgrade by lean-agents is recorded'); return true; }
925
+ console.log('lean-agents --update --undo plan (the oldest saved version per agent):');
926
+ for (const c of todo) {
927
+ console.log(` - ${agentOf(c)}: back to ${c.from}`);
928
+ for (const argv of [...c.reinstall, ...(c.reinstallAlways ?? [])]) console.log(` $ ${argv.join(' ')}`);
929
+ }
930
+ if (o.dryRun) { console.log('Dry run: nothing was changed.'); return true; }
931
+ if (!o.exec) { console.log('--no-exec: nothing was run. Not done.'); return false; }
932
+ if (!o.yes && !(process.stdin.isTTY && process.stdout.isTTY)) { console.log('No terminal to ask on: --yes runs it. Not done.'); return false; }
933
+ const p = await prompter(o.yes);
934
+ try { if (!yesNo(await p.ask('Reinstall these versions?', o.yes ? 'y' : 'n'))) { console.log('Cancelled.'); return true; } } finally { p.close(); }
935
+ Object.assign(process.env, childEnv(S.options.network));
936
+ const { ok, restored } = undoUpgrades(todo, {}, stamps);
937
+ // A restored agent's records are spent; a failed one keeps them so the next --update --undo retries it.
938
+ S.commands = S.commands.filter((c) => !(c.reinstall && restored.has(agentOf(c))));
939
+ S.updatedAt = new Date().toISOString();
940
+ writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(S, null, 2)}\n`);
941
+ return ok;
942
+ }
943
+
944
+ // The state of a machine where only an upgrade step ran (nothing else installed yet).
945
+ const blankState = () => ({ version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version, installedAt: new Date().toISOString(), pins: {}, options: { agents: [], tools: [], terminals: [], unverified: {}, gh: false, lang: 'en', profile: null, network: {} }, files: [], commands: [] });
946
+
947
+ // The 1.x config the verified backup saved: opencode1 runs on a copy of it, not on the live (2.x) config.
948
+ const snapshot1x = (home) => { const st = readBackupStamp(home); return st ? path.join(st.dir, 'config') : null; };
949
+
950
+ // `opencode1` (P4). The state is saved after every step, so an error midway still leaves something --uninstall can undo.
951
+ function sideBySide(o) {
952
+ const p = planOpencode1({ home: o.home, exec: o.exec, configSnapshot: snapshot1x(o.home) });
953
+ if (!p.ok) { console.log(`refused, nothing changed:\n${p.problems.map((x) => ` - ${x}`).join('\n')}`); return false; }
954
+ const win = process.platform === 'win32';
955
+ console.log(`${o.dryRun || !o.yes ? 'dry run: would set up' : 'setting up'} opencode1 (OpenCode ${p.version}, from ${p.source})`);
956
+ console.log(` binary copy: ${p.binary}\n shim: ${p.actions[0].path}\n PATH: ${win ? `user PATH (HKCU) gets ${p.pathDir}` : `${p.actions.slice(1).map((a) => a.path).join(', ')} gets a marked block`}`);
957
+ console.log(` 1.x reads and writes only ${opencode1Layout(o.home).frozen} and its own config copy in ${opencode1Layout(o.home).config}; the live data and config are not touched`);
958
+ if (o.dryRun || !o.yes) { console.log('dry run: nothing was written'); return true; }
959
+ const previous = readState(o.home);
960
+ const files = [];
961
+ const save = (record) => {
962
+ const state = previous ?? blankState();
963
+ privateDir(stateDir(o.home), stateDir(o.home));
964
+ writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify({ ...state, updatedAt: new Date().toISOString(), files: [...state.files, ...files], opencode1: record }, null, 2)}\n`);
965
+ };
966
+ const ts = new Date().toISOString().replace(/\D/g, '');
967
+ installOpencode1(p, { home: o.home, roots: [...writeRoots(o), opencode1Layout(o.home).root], backupDir: path.join(stateDir(o.home), 'backups', ts), apply, files, onRecord: save });
968
+ console.log('done: run `opencode1 --version` in a new terminal. `--uninstall` removes it; the backup and the frozen copy stay.');
969
+ return true;
970
+ }
971
+
972
+ // `--upgrade-agent opencode --yes` / `--undo` (#80 part 2, P6). The journal is state.json `upgrade`; the steps are in lib/opencode-upgrade.mjs.
973
+ function upgradeDeps(o, S, save, extra) {
974
+ const ts = new Date().toISOString().replace(/\D/g, '');
975
+ const rulesPath = path.join(stateDir(o.home), 'AGENTS.md');
976
+ // The adapter's file and JSON actions only: its commands (npx skill installs, git clones) are not run by an upgrade.
977
+ const adapterFor = (tools) => {
978
+ const saved = S.options ?? {};
979
+ const opts = { tools, network: saved.network ?? {}, keepUpdater: !!saved.keepUpdater, terminals: [], platform: process.platform, env: process.env, shell: 'default', ponytailMode: saved.ponytailMode ?? 'lite', adhdAlways: false };
980
+ const r = opencodeV2Adapter({ home: o.home, core: loadCore(ROOT), profile: null, opts, rulesPath: rulesPath.split(path.sep).join('/') });
981
+ if (r.commands.length) console.log(` ${r.commands.length} adapter command(s) not run by the upgrade; --update runs them`);
982
+ // No rules file (lean-agents never installed the rules here): do not point `instructions` at a missing file.
983
+ return fs.existsSync(rulesPath) ? r : { ...r, actions: r.actions.map((a) => (a.kind === 'json' ? { ...a, edits: a.edits.filter((e) => e.path[0] !== 'instructions') } : a)) };
984
+ };
985
+ const lifecycle = (mode) => agentLifecycle({ mode, fromUpgrade: true, agents: ['opencode-v2'], home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: false, exec: o.exec, yes: true, ask: async (_q, def) => def, yesNo });
986
+ const d = {
987
+ home: o.home, platform: process.platform, log: console.log, state: S, save, roots: writeRoots(o), which,
988
+ tools: { config: (S.options?.tools ?? []).filter((t) => t !== 'dcp'), dcp: ['dcp'] },
989
+ adapterFor, backupDir: (name) => path.join(stateDir(o.home), 'backups', `${ts}-${name}`),
990
+ manual: agentTable({ home: o.home, platform: process.platform, dir: stateDir(o.home), realHome: REAL_HOME })['opencode-v2'].manual,
991
+ plan1: () => planOpencode1({ home: o.home, exec: o.exec, configSnapshot: snapshot1x(o.home) }),
992
+ install1: (p, files, onRecord) => installOpencode1(p, { home: o.home, roots: [...writeRoots(o), opencode1Layout(o.home).root], backupDir: path.join(stateDir(o.home), 'backups', `${ts}-opencode1`), apply, files, onRecord }),
993
+ installAgent: () => lifecycle('install'),
994
+ uninstallAgent: () => lifecycle('uninstall'),
995
+ ...extra,
996
+ };
997
+ return d;
998
+ }
999
+
1000
+ // Temp file then rename: a kill midway never leaves a truncated state.json (it holds the journal --undo needs).
1001
+ function saveJournalState(o, S) {
1002
+ S.updatedAt = new Date().toISOString();
1003
+ const dir = stateDir(o.home);
1004
+ privateDir(dir, dir);
1005
+ const file = path.join(dir, 'state.json');
1006
+ writePrivate(`${file}.tmp`, `${JSON.stringify(S, null, 2)}\n`);
1007
+ renameRetry(`${file}.tmp`, file);
1008
+ }
1009
+
1010
+ const refuse = (problems) => { console.log(`refused, nothing changed:\n${problems.map((x) => ` - ${x}`).join('\n')}`); return false; };
1011
+
1012
+ async function applyUpgrade(o) {
1013
+ const fail = failAt();
1014
+ const S = readState(o.home) ?? blankState();
1015
+ const stamp = readBackupStamp(o.home);
1016
+ const { problems, baseline } = applyPreflight({ home: o.home, stamp, upgrade: S.upgrade, exec: o.exec, list: listProcesses, opencodeRunning });
1017
+ if (problems.length) return refuse(problems);
1018
+ const save = () => saveJournalState(o, S);
1019
+ const inv = upgradeInventory(await inventory({ home: o.home, env: process.env, realHome: REAL_HOME }), { home: o.home });
1020
+ const steps = createSteps(upgradeDeps(o, S, save, { inv, stamp }));
1021
+ S.upgrade = { backup: stamp.dir, baseline };
1022
+ const ctx = makeCtx({ home: o.home, stamp, journal: S.upgrade });
1023
+ console.log(`applying the OpenCode upgrade: verified backup ${stamp.dir} (${stamp.sessions} sessions)`);
1024
+ const ok = await runApply({ steps, journal: S.upgrade, save, ctx, fail, restore: () => restoreData({ home: o.home, backupDir: stamp.dir }) });
1025
+ if (!ok) { process.exitCode = 1; return false; }
1026
+ console.log('done. Start OpenCode 2 once: it migrates the live session db (the backup and the frozen copy hold the 1.x state). `opencode1` runs 1.x on the frozen copy.\n`--upgrade-agent opencode --undo --yes` goes back to 1.x; the backup and the frozen copy are never deleted.');
1027
+ return true;
1028
+ }
1029
+
1030
+ async function undoUpgrade(o) {
1031
+ const S = readState(o.home);
1032
+ const journal = S?.upgrade;
1033
+ if (!isActive(journal)) { console.log('nothing to undo: no OpenCode upgrade is active (the backup and the frozen copy are kept either way)'); return true; }
1034
+ const L = backupLayout(o.home, 'x');
1035
+ // The journal names the backup folder: only one inside lean-agents' own backups folder is used.
1036
+ if (typeof journal.backup !== 'string' || path.dirname(journal.backup) !== path.dirname(L.backup) || !/^opencode1-sessions-\d{8}T\d{6}Z$/.test(path.basename(journal.backup)) || !Array.isArray(journal.steps)) return refuse([`the journal names a backup outside ${path.dirname(L.backup)}: not used`]);
1037
+ const stamp = { dir: journal.backup, frozen: L.frozen };
1038
+ const todo = journal.steps.filter((s) => s.status !== 'undone').reverse().map((s) => s.id);
1039
+ console.log(`undo: ${todo.length ? todo.join(', ') : 'no step left to undo'}, then the 1.x data comes back from ${L.frozen} (the 2.x db is moved aside, never deleted)`);
1040
+ if (o.dryRun || !o.yes) { console.log('dry run: nothing was changed (--yes does it)'); return true; }
1041
+ const problems = [];
1042
+ try { if (opencodeRunning(listProcesses())) problems.push('an opencode process is running (the 1.x app or the 2.x background service): close it first; lean-agents did not start it'); } catch (e) { problems.push(`cannot list the running processes (${String(e.message).split('\n')[0]}): not safe to continue`); }
1043
+ const bad = verifyBackup(stamp.dir);
1044
+ if (bad.length) problems.push(`the backup does not match its manifest (${bad[0]}): not used; see ${path.join(stamp.dir, 'RESTORE.md')}`);
1045
+ if (!o.exec) problems.push('--no-exec: undo may run the OpenCode 2 uninstall and a `--version` probe');
1046
+ if (problems.length) return refuse(problems);
1047
+ const save = () => saveJournalState(o, S);
1048
+ const steps = createSteps(upgradeDeps(o, S, save, { stamp, inv: { items: [] } }));
1049
+ const ctx = makeCtx({ home: o.home, stamp, journal });
1050
+ const ok = await runUndo({ steps, journal, save, ctx, restore: () => restoreData({ home: o.home, backupDir: stamp.dir }) });
1051
+ if (!ok) { process.exitCode = 1; return false; }
1052
+ const drift = configDrift(L, stamp.dir);
1053
+ if (drift.length) console.log(`! these config files differ from the 1.x snapshot in the backup (left as they are): ${drift.join(', ')}`);
1054
+ const kept2x = journal.steps?.find((x) => x.id === 'install2x')?.kept2x;
1055
+ console.log(`undone: OpenCode 1.x data${kept2x ? ' is back; OpenCode 2 stays (see the ! line above)' : ' and binary are back'}. The backup (${stamp.dir}) and the frozen copy (${L.frozen}) are kept.`);
1056
+ return true;
1057
+ }
1058
+
1059
+ // --uninstall after an applied upgrade: undo the files the opencode1, config and dcp steps wrote (same entry undo as --undo, roots
1060
+ // checked there). No 1.x restore, no 2.x uninstall, no data restore: the journal is archived right after.
1061
+ async function revertUpgradeFiles(o, S) {
1062
+ const steps = createSteps(upgradeDeps(o, S, () => {}, { stamp: {}, inv: { items: [] } }));
1063
+ const recs = Array.isArray(S.upgrade.steps) ? S.upgrade.steps : [];
1064
+ for (const rec of [...recs].reverse()) {
1065
+ const step = ['opencode1', 'config', 'dcp'].includes(rec?.id) && rec.status !== 'undone' ? steps.find((x) => x.id === rec.id) : null;
1066
+ if (step) await step.undo(rec, null);
1067
+ }
1068
+ }
1069
+
1070
+ // The finish-step page (#181): an owned file in the state dir (--uninstall removes it). Returns its path, or null when nothing was written.
1071
+ async function summaryPage(o, { updated = [] } = {}) {
1072
+ const state = readState(o.home);
1073
+ if (!state) return null;
1074
+ const rows = [];
1075
+ doctor({ home: o.home, state, exec: o.exec, nodeVersion: NODE_VERSION, collect: rows });
1076
+ const network = state.options.network ?? o.network;
1077
+ const lang = o.lang ?? state.options.lang ?? 'en';
1078
+ const model = buildSummary({
1079
+ state, rows, updated, home: [o.home, os.homedir()], lang,
1080
+ applied: { ok: true, version: state.version, files: state.files.map((f) => f.path), commands: state.commands.map((c) => ({ desc: c.desc, ok: c.ok })), errors: [] },
1081
+ logins: loginRows({ agents: state.options.agents, gh: !!state.options.gh, exec: o.exec, outbound: network.outbound }),
1082
+ });
1083
+ const file = path.join(stateDir(o.home), 'summary.html');
1084
+ const content = renderSummary({ model, filed: state.filedIssues, network, home: [o.home, os.homedir()] });
1085
+ const [planned] = plan([{ kind: 'file', path: file, content }], writeRoots(o), state.files);
1086
+ if (planned.status === 'skip') { console.log(`Summary page not written: ${file} ${planned.note}.`); return null; }
1087
+ const [entry] = apply([planned], path.join(stateDir(o.home), 'backups', 'summary'), o.home, writeRoots(o));
1088
+ if (entry) {
1089
+ // A rewrite keeps the first record (created, backup), so --uninstall still removes the file.
1090
+ const first = state.files.find((f) => f.path === file);
1091
+ state.files = [...state.files.filter((f) => f !== first), { ...entry, ...(first && { created: first.created, backup: first.backup }) }];
1092
+ writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
1093
+ }
1094
+ console.log(`Summary page: ${file}`);
1095
+ if (canOffer({ noOpen: o.noOpen, yes: o.yes, json: o.json, tty: process.stdin.isTTY && process.stdout.isTTY })) {
1096
+ const p = await prompter(false);
1097
+ try { if (yesNo(await p.ask('Open it in your browser?', 'n'))) quiet(openArgv(process.platform, file), 15000); } finally { p.close(); }
1098
+ }
1099
+ return file;
1100
+ }
1101
+
1102
+ // --summary: rebuild the page from state.json, after recording the issues the verify prompt filed (--filed-issue "item=url").
1103
+ async function summaryCommand(o) {
1104
+ const state = readState(o.home);
1105
+ if (!state) { console.log('lean-agents is not installed: nothing to summarize.'); process.exitCode = 1; return; }
1106
+ if (o.filedIssues?.length) {
1107
+ const home = [o.home, os.homedir()];
1108
+ for (const f of o.filedIssues) {
1109
+ const at = f.lastIndexOf('=');
1110
+ if (at < 1) throw new Error('--filed-issue takes "item=issue url"');
1111
+ state.filedIssues = addFiledIssue(state.filedIssues, { item: f.slice(0, at), title: f.slice(0, at), url: f.slice(at + 1) }, { home });
1112
+ }
1113
+ writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
1114
+ }
1115
+ if (!(await summaryPage(o))) process.exitCode = 1;
1116
+ }
1117
+
611
1118
  async function uninstall(o) {
612
1119
  const state = readState(o.home);
613
1120
  if (!state) { console.log('lean-agents is not installed.'); return; }
1121
+ // A settled upgrade (`applied` never moves on by itself) must not block --uninstall for a user who stays on 2.x. Any other live
1122
+ // status is a half-done apply or undo: finish it with --undo first. --uninstall archives the journal, so --undo is gone after it.
1123
+ const up = state.upgrade;
1124
+ if (isActive(up) && up.status !== 'applied') throw new Error(`an OpenCode upgrade is ${up.status}: run --upgrade-agent opencode --undo first (it restores your 1.x data), then --uninstall`);
1125
+ if (isActive(up)) {
1126
+ const kept = typeof up.backup === 'string' ? `the 1.x backup (${up.backup}, see RESTORE.md in it)` : 'the 1.x backup';
1127
+ console.log(`! the OpenCode 2 upgrade stays: --uninstall does not go back to 1.x, and its journal is archived, so --undo is no longer available afterwards.\n Removed: what the upgrade added (the opencode1 shim and PATH block, the managed 2.x config and DCP edits).\n Kept: your data (the live 2.x sessions), ${kept}, the frozen copy and the OpenCode 2 install. To go back to 1.x, run --upgrade-agent opencode --undo --yes first.`);
1128
+ }
614
1129
  const p = await prompter(o.yes);
615
1130
  console.log(`This restores ${state.files.length} files and undoes ${state.commands.length} commands.`);
1131
+ if (o.dryRun) {
1132
+ for (const c of [...state.commands].reverse()) {
1133
+ if (c.undo?.length) console.log(` - undo: ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
1134
+ }
1135
+ }
616
1136
  if (o.dryRun || !yesNo(await p.ask('Uninstall?', o.yes ? 'y' : 'n'))) { p.close(); console.log('Nothing changed.'); return; }
617
1137
  p.close();
618
1138
  if (!o.exec && state.commands.length) throw new Error('--no-exec cannot undo the commands this install ran; run --uninstall without it');
1139
+ const failed = new Map();
619
1140
  if (o.exec) {
620
1141
  for (const c of [...state.commands].reverse()) {
621
- for (const argv of c.undo ?? []) {
622
- if (!run(argv, { dryRun: false, log: console.log, env: c.env })) {
1142
+ const bad = (c.undo ?? []).filter((argv) => !run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env }));
1143
+ if (bad.length) {
1144
+ if (c.ok === false) {
1145
+ console.log(' (it did not finish, so there may be nothing to remove)');
1146
+ } else {
623
1147
  console.log(' ! failed. Run the command above by hand.');
624
1148
  process.exitCode = 1;
1149
+ failed.set(c, bad);
625
1150
  }
626
1151
  }
627
1152
  }
628
1153
  }
629
1154
  if (state.toolNode?.installedByLean) console.log(`Kept Node v${state.toolNode.version} (lean-agents never removes a Node); remove it with \`nvm uninstall ${state.toolNode.version}\`.`);
1155
+ if (isActive(up)) await revertUpgradeFiles(o, state);
630
1156
  const report = undo(state.files, writeRoots(o));
1157
+ if (state.opencode1) report.push(...removeOpencode1(state.opencode1, { home: o.home }));
631
1158
  for (const [what, file] of report) console.log(` ${what.padEnd(20)} ${file}`);
632
1159
  if (report.some(([what]) => what === 'left (symlink)')) console.log(' ! Paths marked "left (symlink)" were not touched; remove our lines there by hand.');
633
- fs.renameSync(path.join(stateDir(o.home), 'state.json'), path.join(stateDir(o.home), `state.uninstalled-${Date.now()}.json`));
1160
+ const stateFile = path.join(stateDir(o.home), 'state.json');
1161
+ if (failed.size) {
1162
+ // Files are already restored; keep only the failed undo argvs, so a second --uninstall retries them.
1163
+ const commands = state.commands.filter((c) => failed.has(c)).map((c) => ({ ...c, undo: failed.get(c) }));
1164
+ writePrivate(stateFile, `${JSON.stringify({ ...state, files: [], commands, opencode1: undefined, upgrade: undefined }, null, 2)}\n`);
1165
+ console.log(`Not finished: ${failed.size} undo command(s) failed and stay recorded. Fix the cause (or run them by hand), then run --uninstall again.`);
1166
+ return;
1167
+ }
1168
+ renameRetry(stateFile, path.join(stateDir(o.home), `state.uninstalled-${Date.now()}.json`));
1169
+ if (state.adopt) {
1170
+ saveState(stateDir(o.home), state.adopt);
1171
+ console.log(' kept: the --adopt record; undo it with --adopt --undo');
1172
+ }
634
1173
  // Backups are the only undo for edits we cannot revert, so they stay unless the user says yes (--yes keeps them).
635
1174
  const backups = path.join(stateDir(o.home), 'backups');
636
1175
  const q = await prompter(o.yes);
@@ -640,6 +1179,43 @@ async function uninstall(o) {
640
1179
  console.log(drop ? 'Uninstalled. Backups deleted.' : `Uninstalled. Backups are kept in ${backups}.`);
641
1180
  }
642
1181
 
1182
+ // --install-agent / --uninstall-agent vscode-copilot: the engine's own install, and an undo scoped to this adapter's files.
1183
+ function vscodeHooks(o) {
1184
+ const configured = () => !!readState(o.home)?.options.agents.includes('vscode-copilot');
1185
+ const configure = () => {
1186
+ const saved = readState(o.home);
1187
+ // Tools and terminals stay as chosen before (none on a first run): this verb adds the agent only, so it asks nothing about them.
1188
+ return install({ ...o, command: 'install', yes: o.yes || o.dryRun, agents: [...new Set([...(saved?.options.agents ?? []), 'vscode-copilot'])], tools: o.tools ?? saved?.options.tools ?? [], terminals: o.terminals ?? saved?.options.terminals ?? [] });
1189
+ };
1190
+ const uninstallScoped = async () => {
1191
+ const state = readState(o.home);
1192
+ const core = loadCore(ROOT);
1193
+ const planned = vscodeCopilotAdapter({ home: o.home, core, profile: loadProfile(ROOT, FIXED_PROFILE['vscode-copilot']), opts: state.options, rules: '', adhdCommand: adhdCommand(o.home) });
1194
+ const mine = new Set(planned.actions.map((a) => a.path));
1195
+ const files = state.files.filter((f) => mine.has(f.path));
1196
+ const commands = state.commands.filter((c) => c.agent === 'vscode-copilot');
1197
+ console.log(`This restores ${files.length} files and undoes ${commands.length} commands, all written for vscode-copilot.`);
1198
+ if (o.dryRun) {
1199
+ for (const c of [...commands].reverse()) {
1200
+ if (c.undo?.length) console.log(` - undo: ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
1201
+ }
1202
+ }
1203
+ const p = await prompter(o.yes);
1204
+ const ok = !o.dryRun && yesNo(await p.ask('Remove the vscode-copilot config?', o.yes ? 'y' : 'n'));
1205
+ p.close();
1206
+ if (!ok) { console.log('Nothing changed.'); return; }
1207
+ if (!o.exec && commands.length) throw new Error('--no-exec cannot undo the commands this install ran; run it without --no-exec');
1208
+ for (const c of o.exec ? [...commands].reverse() : []) {
1209
+ for (const argv of c.undo ?? []) if (!run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env })) { console.log(' ! failed. Run the command above by hand.'); process.exitCode = 1; }
1210
+ }
1211
+ for (const [what, file] of undo(files, writeRoots(o))) console.log(` ${what.padEnd(20)} ${file}`);
1212
+ const file = path.join(stateDir(o.home), 'state.json');
1213
+ writePrivate(file, `${JSON.stringify({ ...state, options: { ...state.options, agents: state.options.agents.filter((a) => a !== 'vscode-copilot') }, files: state.files.filter((f) => !mine.has(f.path)), commands: state.commands.filter((c) => c.agent !== 'vscode-copilot') }, null, 2)}\n`);
1214
+ console.log('vscode-copilot: removed. Your other config and the extension were not touched.');
1215
+ };
1216
+ return { configured, install: configure, uninstall: uninstallScoped };
1217
+ }
1218
+
643
1219
  // The agent files the issue itself, and only after the user said yes; this only drafts.
644
1220
  function feedback(o) {
645
1221
  if (!o.failedCommand) throw new Error('--feedback-draft needs --failed-command <text>');
@@ -650,8 +1226,24 @@ function feedback(o) {
650
1226
  process.stdout.write(`${JSON.stringify(draft ?? { offer: false })}\n`);
651
1227
  }
652
1228
 
1229
+ // Below the engines floor, read-only paths still report; anything that writes or runs commands stops.
1230
+ function checkNodeFloor(o) {
1231
+ const floor = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).engines.node;
1232
+ // LEAN_AGENTS_NODE may fake a lower version for tests, never a higher one (#229).
1233
+ // A malformed or prerelease override (`abc`, `22.20.0-rc.1`) is cleaned or ignored (#235).
1234
+ const fake = (process.env.LEAN_AGENTS_NODE ?? '').replace(/-.*/, '');
1235
+ const override = /^v?\d+(\.\d+){0,2}$/.test(fake) ? fake.replace(/^v/, '').split('.').concat('0', '0').slice(0, 3).join('.') : null;
1236
+ const running = [process.versions.node, override].find((v) => v && !satisfies(v, floor));
1237
+ if (!running) return;
1238
+ const readOnly = ['help', 'version', 'doctor', 'usage', 'feedback'].includes(o.command) || (o.command === 'upgrade-agent' && !o.yes) || o.dryRun || (o.command === 'adopt' && !o.yes && !o.undo);
1239
+ const allow = process.env.LEAN_AGENTS_ALLOW_OLD_NODE === '1';
1240
+ console.error(`lean-agents: Node ${running} is older than ${floor.replace(/^>=/, '')}, which lean-agents needs. Fix: nvm install 22 && nvm use 22, or run install.sh.${readOnly || allow ? '' : ' Set LEAN_AGENTS_ALLOW_OLD_NODE=1 to run anyway.'}`);
1241
+ if (!readOnly && !allow) process.exit(1);
1242
+ }
1243
+
653
1244
  async function main() {
654
1245
  const o = parseArgs(process.argv.slice(2));
1246
+ checkNodeFloor(o);
655
1247
  // A repository gets files only: tools and agents stay per user.
656
1248
  if (o.project && o.agents?.length && !o.migrate) throw new Error('--project writes repository files only: run --agents in a separate install');
657
1249
  if (o.project) { project = o.project; if (!o.migrate) { o.agents = []; o.exec = false; } }
@@ -661,16 +1253,42 @@ async function main() {
661
1253
  shareProxy();
662
1254
  if (o.command === 'help') return console.log(HELP);
663
1255
  if (o.command === 'version') return console.log(JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version);
664
- if (o.command === 'doctor') return process.exit(doctor({ home: o.home, state: readState(o.home), exec: o.exec, nodeVersion: NODE_VERSION, json: o.json }) ? 0 : 1);
1256
+ if (o.command === 'doctor') {
1257
+ const state = readState(o.home);
1258
+ const probe = o.probePlugins && state?.options.agents.some((a) => a.startsWith('opencode')) ? await probePlugins(o.home) : [];
1259
+ return process.exit(doctor({ home: o.home, state, exec: o.exec, nodeVersion: NODE_VERSION, json: o.json, probe }) ? 0 : 1);
1260
+ }
1261
+ if (o.command === 'upgrade-agent' && o.upgradeAgent === 'vscode-copilot') {
1262
+ if (o.backup || o.opencode1 || o.undo) throw new Error('--upgrade-agent vscode-copilot takes no other flags');
1263
+ console.log(`vscode-copilot: ${VSCODE_NOTE}\nNothing to upgrade here. To refresh the files lean-agents wrote (rules, agents, mcp.json), run --update.`);
1264
+ return;
1265
+ }
665
1266
  if (o.command === 'upgrade-agent') {
666
- if (o.undo || (o.yes && !o.dryRun)) throw new Error('--upgrade-agent opencode apply and --undo are not in this release yet; it only lists (dry run)');
1267
+ if (o.backup) {
1268
+ if (o.undo) throw new Error('--upgrade-agent opencode --backup has no --undo: the backup is permanent and lean-agents never deletes it');
1269
+ const r = backupOpencode({ home: o.home, dryRun: o.dryRun || !o.yes });
1270
+ return process.exit(r.ok ? 0 : 1);
1271
+ }
1272
+ if (o.opencode1) {
1273
+ if (o.undo) throw new Error('--upgrade-agent opencode --opencode1 has no --undo yet: run --uninstall');
1274
+ return process.exit(sideBySide(o) ? 0 : 1);
1275
+ }
1276
+ if (o.undo) return process.exit((await undoUpgrade(o)) ? 0 : 1);
1277
+ if (o.yes && !o.dryRun) return process.exit((await applyUpgrade(o)) ? 0 : 1);
667
1278
  const env = process.env;
668
1279
  const inv = await inventory({ home: o.home, env, realHome: REAL_HOME });
669
1280
  const bin = which('opencode');
670
- const r = upgradeInventory(inv, { home: o.home, binary: { path: bin, version: bin && o.exec ? binVersion('opencode') : null } });
1281
+ // With --home elsewhere, `opencode --version` would still run the real agent (it writes logs): report it as not probed.
1282
+ const norm = (p) => (process.platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p));
1283
+ const own = norm(o.home) === norm(REAL_HOME);
1284
+ const binVer = bin && o.exec ? (own ? binVersion('opencode') : 'not probed (--home)') : null;
1285
+ const r = upgradeInventory(inv, { home: o.home, binary: { path: bin, version: binVer } });
671
1286
  if (o.json) process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); else console.log(formatUpgrade(r));
672
1287
  return process.exit(0);
673
1288
  }
1289
+ if (o.backup) throw new Error('--backup goes with --upgrade-agent opencode');
1290
+ if (o.command === 'update' && o.undo && o.json) throw new Error('--update --undo has no --json output: the plan and the results are text');
1291
+ if (o.command === 'update' && o.undo) return process.exit((await undoAgentUpgrades(o)) ? 0 : 1);
674
1292
  if ((o.undo || o.keepBackup || o.confirmRemovals) && o.command !== 'adopt') throw new Error('--undo, --keep-backup and --confirm-removals go with --adopt');
675
1293
  if (o.command === 'adopt') {
676
1294
  // Removals outside the JSON edits need a yes: a menu on a terminal, --confirm-removals without one.
@@ -687,9 +1305,10 @@ async function main() {
687
1305
  }
688
1306
  if (o.command === 'agent') {
689
1307
  const p = await prompter(o.yes);
690
- try { return await agentLifecycle({ mode: o.agentMode, agents: o.agentList, home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: o.dryRun, exec: o.exec, yes: o.yes, ask: p.ask, yesNo }); } finally { p.close(); }
1308
+ try { return await agentLifecycle({ mode: o.agentMode, agents: o.agentList, home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: o.dryRun, exec: o.exec, yes: o.yes, ask: p.ask, yesNo, vscode: vscodeHooks(o) }); } finally { p.close(); }
691
1309
  }
692
1310
  if (o.command === 'feedback') return feedback(o);
1311
+ if (o.command === 'summary') return summaryCommand(o);
693
1312
  if (o.command === 'uninstall') return uninstall(o);
694
1313
  return install(o);
695
1314
  }