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
@@ -10,6 +10,7 @@ import { which } from './system.mjs';
10
10
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
11
11
  const LOG_TAIL_BYTES = 2000;
12
12
 
13
+ const NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
13
14
  // User-facing tier names; profiles call the cheapest one "fast".
14
15
  export const TIERS = { cheap: 'fast', balanced: 'balanced', strong: 'strong' };
15
16
  const ROLE_TIER = { plan: 'strong', build: 'balanced', explore: 'cheap', research: 'cheap' };
@@ -30,7 +31,7 @@ function gitOrThrow(cwd, args) {
30
31
  export function parseTask(file) {
31
32
  const text = fs.readFileSync(file, 'utf8');
32
33
  const name = path.basename(file).replace(/\.md$/, '');
33
- if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new Error(`task file name "${name}" must be lowercase letters, digits and dashes`);
34
+ if (!NAME_RE.test(name)) throw new Error(`task file name "${name}" must be lowercase letters, digits and dashes`);
34
35
  const meta = {};
35
36
  let body = text;
36
37
  const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
@@ -96,8 +97,12 @@ export function repoInfo(cwd) {
96
97
 
97
98
  const workersFile = (stateDir) => path.join(stateDir, 'workers.json');
98
99
 
100
+ // A worker name becomes a path (clean removes stateDir/<name>), so a hand-edited workers.json is checked like a task file name.
99
101
  export function loadWorkers(stateDir) {
100
- try { return JSON.parse(fs.readFileSync(workersFile(stateDir), 'utf8')); } catch { return { base: null, workers: [] }; }
102
+ let data;
103
+ try { data = JSON.parse(fs.readFileSync(workersFile(stateDir), 'utf8')); } catch { return { base: null, workers: [] }; }
104
+ if (!Array.isArray(data?.workers) || data.workers.some((w) => typeof w?.name !== 'string' || !NAME_RE.test(w.name))) throw new Error(`${workersFile(stateDir)} is not a valid worker list (names are lowercase letters, digits and dashes); fix or delete the file`);
105
+ return data;
101
106
  }
102
107
 
103
108
  function saveWorkers(stateDir, data) {
@@ -0,0 +1,33 @@
1
+ // Diffs two core/pins.json documents for the release notes. Pure: no I/O, no network.
2
+
3
+ const MARKS = { added: 'new', removed: 'removed' };
4
+
5
+ // Rows for every pin whose version changed, appeared or disappeared, sorted by name. `prev` may be null (no earlier release).
6
+ export function diffPins(prev, next) {
7
+ if (!prev?.pins) return [];
8
+ const a = prev.pins;
9
+ const b = next.pins ?? {};
10
+ return [...new Set([...Object.keys(a), ...Object.keys(b)])].sort().flatMap((name) => {
11
+ const was = a[name];
12
+ const now = b[name];
13
+ if (was && now && was.version === now.version) return [];
14
+ const p = now ?? was;
15
+ return [{
16
+ name,
17
+ from: was?.version ?? null,
18
+ to: now?.version ?? null,
19
+ kind: p.kind,
20
+ change: !was ? 'added' : !now ? 'removed' : 'bumped',
21
+ held: Boolean(p.hold),
22
+ ciOnly: Boolean(p.ciOnly),
23
+ }];
24
+ });
25
+ }
26
+
27
+ // Markdown table, or '' when nothing changed.
28
+ export function toolVersionsTable(rows) {
29
+ if (!rows.length) return '';
30
+ const note = (r) => [MARKS[r.change], r.held && 'held', r.ciOnly && 'CI only'].filter(Boolean).join(', ');
31
+ const lines = rows.map((r) => `| ${r.name} | ${r.from ?? '-'} | ${r.to ?? '-'} | ${note(r)} |`);
32
+ return ['| Tool | From | To | Note |', '| --- | --- | --- | --- |', ...lines].join('\n');
33
+ }
@@ -25,9 +25,14 @@ export const pinSpec = (key) => (pin(key).kind === 'git' ? gitSpec(key) : npmSpe
25
25
  // The `engines.node` range the pinned npm version declares (">=24.15.0"), or undefined when it declares none.
26
26
  export const nodeRange = (key) => pin(key).node;
27
27
  export const bunPin = () => pin('bun');
28
+ export const rtkPin = () => pin('rtk');
28
29
  export const skillsCli = () => npmSpec('skills-cli');
29
- // `download` pins (Bun) are verified by SHA256 at install time and not tracked in state.json.
30
- const tracked = (p) => !p.ciOnly && p.kind !== 'download';
30
+ // `download` pins (Bun) are verified by SHA256 at install time; `tool` (rtk, uv, gh) and `cask` (Antigravity) pins are
31
+ // package-manager installs we cannot pin, so they are a minimum and a known-good version, not something state.json records.
32
+ const tracked = (p) => !p.ciOnly && !['download', 'tool', 'cask'].includes(p.kind);
33
+ // [{ key, source, via, version, min }] for the tools the update plan reports against: rtk, uv, gh, the Antigravity cask and Bun.
34
+ export const toolPins = () => Object.entries(PINS).filter(([, p]) => ['tool', 'cask'].includes(p.kind) || p.tagPrefix)
35
+ .map(([key, p]) => ({ key, source: p.source, via: p.via ?? p.kind, version: p.version, min: p.min ?? null }));
31
36
  export const pinVersions = () => Object.fromEntries(Object.entries(PINS).filter(([, p]) => tracked(p)).map(([k, p]) => [k, p.version]));
32
37
 
33
38
  // Pin keys that differ from the tool name lean-agents saves in state.json options.tools.
@@ -0,0 +1,191 @@
1
+ // OpenCode plugin health (#212): a plugin listed in config is not proof it loads. Read-only: findings with a suggested fix, never a repair.
2
+ // Cache layout (VERIFY, upstream source not readable when written, 2026-11): `<cache>/packages/<pkg>@<spec>/node_modules/<pkg>` with the
3
+ // wrapper's package.json and lockfile beside it; older docs say `<cache>/node_modules/<pkg>`. Both are searched.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import net from 'node:net';
8
+ import { spawn, spawnSync } from 'node:child_process';
9
+ import { parse } from 'jsonc-parser';
10
+ import { configHome, envDir } from './system.mjs';
11
+ import { configPath } from './adapters/opencode-v2.mjs';
12
+ import { PINS } from './pins.mjs';
13
+
14
+ // Plugins whose slash command proves they registered on a fresh server.
15
+ export const COMMANDS = { '@tarquinen/opencode-dcp': 'dcp-compress' };
16
+
17
+ export function splitSpec(spec) {
18
+ const at = spec.lastIndexOf('@');
19
+ return at > 0 ? { name: spec.slice(0, at), version: spec.slice(at + 1) } : { name: spec, version: '' };
20
+ }
21
+
22
+ const readJson = (file, fsx) => { try { return parse(fsx.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
23
+ const cacheDir = (home) => path.join(envDir(home, 'XDG_CACHE_HOME', path.join(home, '.cache')), 'opencode');
24
+
25
+ // npm plugin specs per config file: `plugin` / `plugins` entries, string or [spec, options]. Local paths are not packages.
26
+ export function readSpecs(home, fsx = fs) {
27
+ const dir = path.join(configHome(home), 'opencode');
28
+ const out = [];
29
+ for (const [file, keys] of [[configPath(dir), ['plugin', 'plugins']], [path.join(dir, 'tui.json'), ['plugin']], [path.join(dir, 'tui.jsonc'), ['plugin']]]) {
30
+ const cfg = readJson(file, fsx);
31
+ for (const k of keys) for (const e of Array.isArray(cfg?.[k]) ? cfg[k] : []) {
32
+ const spec = String(Array.isArray(e) ? e[0] : e);
33
+ if (/^(file:|\.|\/|~|[A-Za-z]:[\\/])/.test(spec)) continue;
34
+ out.push({ file: path.basename(file), ...splitSpec(spec), spec });
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+
40
+ // Same package with different version specs in the server config and tui.json. Each process reads its own file, so neither spec "wins".
41
+ export function reconcileSpecs(entries, pins = {}) {
42
+ const byName = new Map();
43
+ for (const e of entries) byName.set(e.name, [...(byName.get(e.name) ?? []), e]);
44
+ const out = [];
45
+ for (const [name, list] of byName) {
46
+ if (new Set(list.map((e) => e.version)).size < 2) continue;
47
+ const seen = list.map((e) => `${e.file} ${e.version || 'unpinned'}`).join(' vs ');
48
+ const want = pins[name] ? `${name}@${pins[name]}` : 'one exact version';
49
+ out.push({ id: 'spec-mismatch', plugin: name, line: `${name}: ${seen}; the server and the TUI each load their own spec, so they can run different versions`,
50
+ fix: `set both files to ${want} by hand (your pin stays yours); then restart OpenCode` });
51
+ }
52
+ return out;
53
+ }
54
+
55
+ // Dependencies of a package that do not resolve from it, the way Node walks node_modules up to the cache root. Optional and peer dependencies are the host's or the user's business.
56
+ function missingDeps(pkgDir, root, fsx, seen = new Set(), depth = 0) {
57
+ const pkg = readJson(path.join(pkgDir, 'package.json'), fsx);
58
+ if (!pkg || depth > 4) return [];
59
+ const miss = [];
60
+ for (const dep of Object.keys(pkg.dependencies ?? {})) {
61
+ let found = null;
62
+ for (let d = pkgDir; ; d = path.dirname(d)) {
63
+ const cand = path.join(d, 'node_modules', dep);
64
+ if (fsx.existsSync(path.join(cand, 'package.json'))) { found = cand; break; }
65
+ if (d === root || d === path.dirname(d)) break;
66
+ }
67
+ if (!found) { miss.push(dep); continue; }
68
+ if (!seen.has(found)) { seen.add(found); miss.push(...missingDeps(found, root, fsx, seen, depth + 1)); }
69
+ }
70
+ return [...new Set(miss)];
71
+ }
72
+
73
+ // Cached wrapper folders of a package: flat `packages/<name>@<spec>` or, for a scoped name, `packages/<scope>/<base>@<spec>` (VERIFY which one OpenCode writes).
74
+ function wrapperDirs(root, name, fsx) {
75
+ const [scope, base] = name.startsWith('@') ? name.split('/') : [null, name];
76
+ const out = [];
77
+ for (const [dir, prefix] of [[path.join(root, 'packages'), `${name}@`], ...(scope ? [[path.join(root, 'packages', scope), `${base}@`]] : [])]) {
78
+ try {
79
+ for (const e of fsx.readdirSync(dir, { withFileTypes: true })) if (e.isDirectory() && e.name.startsWith(prefix)) out.push(path.join(dir, e.name));
80
+ } catch { /* no such folder */ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ // Cached wrapper(s) of `name` whose dependency tree is incomplete. No cached copy: nothing to report.
86
+ // A name from config is joined into a path: no `..` segment and nothing absolute (POSIX or drive letter).
87
+ export const safePluginName = (name) => !path.posix.isAbsolute(name) && !path.win32.isAbsolute(name) && !name.split(/[\\/]/).includes('..');
88
+
89
+ // `specs`: the versions the config asks for ('' = unpinned = the `latest` folder). Given, only the wrapper folders OpenCode loads for
90
+ // them are checked: a leftover folder of an older spec (for example `@latest` after the user pinned an exact version) is not loaded.
91
+ export function checkDepTree(home, name, fsx = fs, specs = null) {
92
+ if (!safePluginName(name)) return [];
93
+ const root = cacheDir(home);
94
+ const wanted = specs && new Set([...specs].map((v) => v || 'latest'));
95
+ const used = (d) => !wanted || wanted.has(path.basename(d).slice(path.basename(d).indexOf('@') + 1));
96
+ const wrappers = [path.join(root, 'node_modules'), ...wrapperDirs(root, name, fsx).filter(used).map((d) => path.join(d, 'node_modules'))];
97
+ const out = [];
98
+ for (const nm of wrappers) {
99
+ const pkgDir = path.join(nm, ...name.split('/'));
100
+ const pkg = readJson(path.join(pkgDir, 'package.json'), fsx);
101
+ if (!pkg) continue;
102
+ const miss = missingDeps(pkgDir, root, fsx);
103
+ if (miss.length) out.push({ id: 'deps-incomplete', plugin: name, line: `${name}@${pkg.version ?? '?'} cached in ${path.relative(root, path.dirname(nm)) || '.'}: missing ${miss.join(', ')}; the plugin cannot load even though config lists it`,
104
+ fix: 'close OpenCode, move that cache folder aside (do not delete it yet), start OpenCode so it installs again; or pin an exact version in both config files' });
105
+ }
106
+ return out;
107
+ }
108
+
109
+ // Static findings (no process started) for every npm plugin in the user's OpenCode config.
110
+ const PIN_VERSIONS = Object.fromEntries(Object.values(PINS).filter((p) => p.kind === 'npm').map((p) => [p.source, p.version]));
111
+
112
+ export function pluginHealth(home, { pins = PIN_VERSIONS, fsx = fs } = {}) {
113
+ const entries = readSpecs(home, fsx);
114
+ const names = [...new Set(entries.map((e) => e.name))];
115
+ return [...reconcileSpecs(entries, pins), ...names.flatMap((n) => checkDepTree(home, n, fsx, entries.filter((e) => e.name === n).map((e) => e.version)))];
116
+ }
117
+
118
+ const freePort = () => new Promise((resolve, reject) => {
119
+ const s = net.createServer().on('error', reject).listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); });
120
+ });
121
+
122
+ // Copies of the user's config and cache are capped: a runaway node_modules must not fill the disk of a read-only check.
123
+ const COPY_CAP_BYTES = 256 * 1024 * 1024;
124
+ const capped = (fsx) => { let bytes = 0; return (src) => { try { bytes += fsx.lstatSync(src).size; } catch { /* the copy reports it */ } if (bytes > COPY_CAP_BYTES) throw new Error('copy exceeds the size cap'); return true; }; };
125
+
126
+ // Windows children need these to start at all; the rest points at the throwaway dir. SystemRoot and ComSpec are the OS's, not the user's.
127
+ const winEnv = (tmp, env) => ({ SystemRoot: env.SystemRoot, ComSpec: env.ComSpec, APPDATA: tmp, LOCALAPPDATA: tmp, TEMP: tmp, TMP: tmp });
128
+
129
+ // Opt-in (--probe-plugins): a short-lived `opencode serve` on loopback with a throwaway state dir. It gets COPIES of the user's OpenCode config and
130
+ // of the cached wrapper of each plugin we know a command for, so nothing of the user's is written. GET /command (1.x) or /api/command (2.x) must list it.
131
+ // Windows: `cmd /c` runs an npm `.cmd` shim, and taskkill /T ends the grandchildren that child.kill() would leave.
132
+ export async function probePlugins(home, { bin = 'opencode', fsx = fs, spawnFn = spawn, spawnSyncFn = spawnSync, fetchFn = fetch, timeoutMs = 30000, env = process.env, platform = process.platform } = {}) {
133
+ const wanted = [...new Set(readSpecs(home, fsx).map((e) => e.name))].filter((n) => COMMANDS[n]);
134
+ if (!wanted.length) return [];
135
+ const win = platform === 'win32';
136
+ const tmp = fsx.mkdtempSync(path.join(os.tmpdir(), 'lean-probe-'));
137
+ const xdg = { XDG_CONFIG_HOME: path.join(tmp, 'config'), XDG_CACHE_HOME: path.join(tmp, 'cache'), XDG_DATA_HOME: path.join(tmp, 'data'), XDG_STATE_HOME: path.join(tmp, 'state') };
138
+ const stop = (c) => {
139
+ if (win && c.pid) { try { const r = spawnSyncFn('taskkill', ['/pid', String(c.pid), '/T', '/F'], { stdio: 'ignore' }); if (!r?.error && !r?.status) return; } catch { /* fall back to kill */ } }
140
+ c.kill();
141
+ };
142
+ let child;
143
+ try {
144
+ try {
145
+ const filter = capped(fsx);
146
+ fsx.cpSync(path.join(configHome(home), 'opencode'), path.join(xdg.XDG_CONFIG_HOME, 'opencode'), { recursive: true, filter });
147
+ const root = cacheDir(home);
148
+ for (const n of wanted) for (const d of wrapperDirs(root, n, fsx)) fsx.cpSync(d, path.join(xdg.XDG_CACHE_HOME, 'opencode', path.relative(root, d)), { recursive: true, filter });
149
+ } catch (e) {
150
+ return [{ id: 'probe-failed', plugin: '', line: `could not copy the config or plugin cache for the probe (${e.code ?? e.message}), so the command check was skipped`, fix: 'check for broken symlinks or a very large node_modules in the OpenCode cache; then run --doctor --probe-plugins again' }];
151
+ }
152
+ const port = await freePort();
153
+ const password = `probe-${process.pid}-${port}`;
154
+ const serve = ['serve', '--hostname', '127.0.0.1', '--port', String(port)];
155
+ child = spawnFn(win ? env.ComSpec ?? 'cmd.exe' : bin, win ? ['/d', '/c', bin, ...serve] : serve, {
156
+ cwd: tmp, stdio: 'ignore', env: { PATH: env.PATH, HOME: tmp, USERPROFILE: tmp, ...(win ? winEnv(tmp, env) : {}), ...xdg, OPENCODE_SERVER_PASSWORD: password },
157
+ });
158
+ let spawnError = null;
159
+ child.on?.('error', (e) => { spawnError = e; }); // opencode not on PATH: a finding, not a crash
160
+ const auth = `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`;
161
+ const names = async () => {
162
+ for (const route of ['/command', '/api/command']) {
163
+ try {
164
+ const r = await fetchFn(`http://127.0.0.1:${port}${route}`, { headers: { authorization: auth } });
165
+ if (!r.ok) continue;
166
+ const j = await r.json();
167
+ return (Array.isArray(j) ? j : j.data ?? []).map((c) => c.name);
168
+ } catch { /* not up yet, or the other route */ }
169
+ }
170
+ return null;
171
+ };
172
+ // The first answer can come before plugins register, so keep asking until every command is listed or the deadline passes.
173
+ const end = Date.now() + timeoutMs;
174
+ let got = null;
175
+ for (;;) {
176
+ const now = await names();
177
+ if (now !== null) got = now;
178
+ if ((got !== null && wanted.every((n) => got.includes(COMMANDS[n]))) || spawnError || Date.now() >= end) break;
179
+ await new Promise((r) => setTimeout(r, 500));
180
+ }
181
+ if (got === null) return [{ id: 'probe-failed', plugin: '', line: spawnError ? `could not start ${bin}: ${spawnError.code ?? spawnError.message}, so the command check was skipped` : 'a short-lived `opencode serve` did not answer in time, so the command check was skipped', fix: 'run --doctor --probe-plugins again; if it repeats, start `opencode serve` by hand and GET /command' }];
182
+ return wanted.filter((n) => !got.includes(COMMANDS[n])).map((n) => ({ id: 'command-missing', plugin: n, line: `${n}: a fresh server does not list /${COMMANDS[n]}; the plugin is configured but not operational`,
183
+ fix: 'check the dependency finding above, or pin an exact older version in both config files; then restart OpenCode' }));
184
+ } finally {
185
+ // wait for the exit so the server cannot write into the folder while it is removed
186
+ if (child?.on && child.exitCode === null && child.signalCode === null) {
187
+ await new Promise((r) => { child.on('exit', r); setTimeout(r, 3000); try { stop(child); } catch { r(); } });
188
+ } else { try { if (child) stop(child); } catch { /* already gone */ } }
189
+ try { fsx.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ }
190
+ }
191
+ }
@@ -0,0 +1,203 @@
1
+ // Prerequisite planner for a fresh machine (#179, PR1). Pure: from an injected probe it returns the ordered steps a fresh
2
+ // Mac, Windows or Linux needs (Xcode CLT, Homebrew, git, nvm, Node 24, uv, rtk, bun). It never runs a command, never reads
3
+ // the real env or disk; the caller (the engine, later PRs) probes, shows the plan, asks once and runs `commands`.
4
+ // Every URL, flag and version without a pin in core/pins.json is marked VERIFY and listed in docs/compatibility.md.
5
+
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { PINS } from './pins.mjs';
9
+ import { bunInstall, rtkInstall } from './system.mjs';
10
+ import { satisfies, compare, minVersion, nvmInstallArgv } from './node-runtime.mjs';
11
+
12
+ const VERIFY_SHA = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
13
+
14
+ // nvm-sh install script and nvm-windows setup: versions and the setup hash come from tests/ci-downloads.json (checked 2026-11-11).
15
+ // The install.sh hash is not pinned anywhere yet. VERIFY
16
+ const NVM_VERSION = 'v0.41.0';
17
+ const NVM_INSTALL_URL = `https://raw.githubusercontent.com/nvm-sh/nvm/${NVM_VERSION}/install.sh`;
18
+ const NVM_WIN = {
19
+ url: 'https://github.com/coreybutler/nvm-windows/releases/download/v2.0.1/nvm-2.0.1-x64-setup.exe',
20
+ sha256: '2ba6ab6290fdc7d1e608e76c97577ca6e1df772b2d59ab8ebc01e10788de8e57',
21
+ };
22
+ // The setup just ran, so this process has no nvm on PATH: read NVM_HOME and NVM_SYMLINK from the saved user or machine environment (nightly fresh-machine, 2026-11-20).
23
+ const NVM_WIN_INSTALL_24 = ['powershell', '-NoProfile', '-NonInteractive', '-Command',
24
+ "foreach ($n in 'NVM_HOME', 'NVM_SYMLINK') { $v = [Environment]::GetEnvironmentVariable($n, 'User'); if (-not $v) { $v = [Environment]::GetEnvironmentVariable($n, 'Machine') }; if ($v) { Set-Item \"env:$n\" $v } }; " +
25
+ "if (-not $env:NVM_HOME) { Write-Error 'NVM_HOME is not set: nvm-windows did not install'; exit 1 }; & (Join-Path $env:NVM_HOME 'nvm.exe') install 24; exit $LASTEXITCODE"];
26
+ // Homebrew installer: commit and sha256 pinned in core/pins.json. VERIFY (unattended behaviour).
27
+ // The uv installer is unpinned (current script). VERIFY
28
+ const BREW = PINS['homebrew-installer'];
29
+ const UV_INSTALL_URL = 'https://astral.sh/uv/install.sh';
30
+
31
+ // Newest `engines.node` floor among the pinned tools; Node 24 is installed under nvm only when nothing meets it.
32
+ const toolFloor = () => ['context-mode', 'gsd-core'].map((k) => PINS[k]?.node).filter(Boolean)
33
+ .reduce((a, b) => (compare(minVersion(b), minVersion(a)) > 0 ? b : a));
34
+ const floorText = (range) => minVersion(range).join('.');
35
+
36
+ // nvm's undo is planned only when ~/.nvm did not exist before this run (`nvmDirExisted`), and runs later: it removes exactly the ~/.nvm
37
+ // of the home the state recorded, and only when every Node under it is one lean-agents installs (the floor's major, v24) and none
38
+ // holds a global package beyond npm, corepack and the npm tools lean-agents installs; otherwise it stays and says why. The Node is a
39
+ // placeholder the engine swaps for the Node running it at undo time (`undoArgv`): no bare `node` on PATH, no path stored.
40
+ export const UNDO_NODE = '<lean-node>';
41
+ export const undoArgv = (argv, execPath = process.execPath) => (argv[0] === UNDO_NODE ? [execPath, ...argv.slice(1)] : argv);
42
+ // Did ~/.nvm exist before this run? A resumed run still owns a ~/.nvm that an earlier, unfinished nvm step created (its recorded
43
+ // undo is not empty); one an earlier run recorded with an empty undo existed before lean-agents and stays the user's.
44
+ export const nvmDirExistedBefore = (savedCommands, dirExists) => !(savedCommands ?? []).some((c) => c.resumeKey === 'prereq:nvm' && c.undo?.length) && dirExists;
45
+ // Runs under `node -e`: argv is [dir, home, major, recorded packages as JSON].
46
+ const NVM_UNDO = [
47
+ "const fs=require('fs'),p=require('path'),[d,h,m,a]=process.argv.slice(1),ok=new Set(['npm','corepack',...JSON.parse(a)]);",
48
+ "const keep=w=>{console.log('kept '+d+': '+w);process.exit()};",
49
+ "if(p.resolve(d)!==p.resolve(h,'.nvm'))keep('it is not the .nvm of the home this install recorded');",
50
+ "let s;try{s=fs.lstatSync(d)}catch{process.exit()}",
51
+ "if(!s.isDirectory())keep('it is not a plain directory');",
52
+ "const ls=x=>{try{return fs.readdirSync(x,{withFileTypes:true})}catch{return[]}},v=p.join(d,'versions','node'),vs=ls(v).filter(e=>e.isDirectory()).map(e=>e.name);",
53
+ "const o=vs.filter(n=>!new RegExp('^v'+m+'[.]').test(n));",
54
+ "if(o.length)keep('it holds Node versions lean-agents did not install ('+o.join(', ')+')');",
55
+ "const g=[];for(const n of vs){const nm=p.join(v,n,'lib','node_modules');for(const e of ls(nm).filter(e=>e.name[0]!=='.')){const q=e.name.startsWith('@')?ls(p.join(nm,e.name)).map(c=>e.name+'/'+c.name):[e.name];for(const x of q)if(!ok.has(x))g.push(x+' ('+n+')')}}",
56
+ "if(g.length)keep('a Node under it has global packages lean-agents did not install ('+g.join(', ')+')');",
57
+ 'fs.rmSync(d,{recursive:true,force:true})',
58
+ ].join('');
59
+ // The npm tools lean-agents may install globally under that Node (CI-only agent pins excluded).
60
+ const recordedPackages = () => Object.values(PINS).filter((p) => p.kind === 'npm' && !p.ciOnly).map((p) => p.source);
61
+ const nvmUndo = (dir, home, major) => [[UNDO_NODE, '-e', NVM_UNDO, dir, home, String(major), JSON.stringify(recordedPackages())]];
62
+
63
+ // The agents --everything configures: Claude Code and OpenCode 2 everywhere; on Windows the team preset adds the ones found
64
+ // (Copilot CLI, VS Code Copilot, Antigravity) and lists the missing ones so the plan says what it skipped.
65
+ export const TEAM_AGENTS = ['copilot-cli', 'vscode-copilot', 'antigravity'];
66
+ export function everythingAgents({ platform, detected = {}, project = false }) {
67
+ const base = ['claude', 'opencode-v2'];
68
+ if (platform !== 'win32') return { agents: base, skipped: [] };
69
+ const team = TEAM_AGENTS.filter((a) => !(project && a === 'antigravity')); // Antigravity has no project scope
70
+ return { agents: [...base, ...team.filter((a) => detected[a])], skipped: team.filter((a) => !detected[a]) };
71
+ }
72
+
73
+ // winget ids, brew formulas `rtk` and `uv`, and `--scope user` for Git.Git are unverified on a fresh machine. VERIFY
74
+ const WINGET = (id) => ['winget', 'install', '--id', id, '-e', '--scope', 'user', '--accept-source-agreements', '--accept-package-agreements'];
75
+
76
+ // probe: { platform, arch, home, tmp, execPath, has: { brew, winget, uv, rtk, bun, git, clt, nvm, jq }, nodeActive: '22.20.0' | null,
77
+ // nvmNodes: ['24.15.0'], nvmDirExisted: true (~/.nvm was there before this run, so its undo is empty), proxyEnv: ['HTTPS_PROXY'] (names only), needsGit: false, done: ['prereq:nvm'] (resume stamps), bunInstall, rtkInstall: stubs for tests }
78
+ export function planPrereqs(probe) {
79
+ const { platform, arch = 'x64', home, has = {}, nodeActive = null, nvmNodes = [], nvmDirExisted = false, proxyEnv = [], needsGit = false, done = [], terminals = [], agents = [] } = probe;
80
+ const win = platform === 'win32', mac = platform === 'darwin';
81
+ const P = win ? path.win32 : path.posix;
82
+ const tmp = probe.tmp ?? P.join(home, '.cache', 'lean-agents');
83
+ const node = probe.execPath ?? 'node';
84
+ const nvmDir = P.join(home, '.nvm');
85
+ const floor = toolFloor();
86
+ const fetch = (url, file) => [win ? 'curl.exe' : 'curl', '-fsSL', '--create-dirs', '-o', file, url];
87
+ const steps = [];
88
+ const add = (s) => steps.push({ needsConsent: true, undo: null, skipIf: null, ...s, resumeKey: `prereq:${s.id}` });
89
+
90
+ if (mac) {
91
+ add({
92
+ id: 'xcode-clt', label: 'Xcode Command Line Tools', why: 'Provides git and the compilers Homebrew needs on a fresh Mac.',
93
+ commands: [['xcode-select', '--install']], // opens a system dialog; headless route via softwareupdate VERIFY
94
+ skipIf: has.clt ? 'Command Line Tools are installed' : null,
95
+ });
96
+ add({
97
+ id: 'homebrew', label: 'Homebrew', why: 'Package manager lean-agents uses for rtk, uv and bun on macOS.',
98
+ commands: [fetch(BREW.url, P.join(tmp, 'brew-install.sh')), [node, VERIFY_SHA, P.join(tmp, 'brew-install.sh'), BREW.sha256], ['env', 'NONINTERACTIVE=1', '/bin/bash', P.join(tmp, 'brew-install.sh')]],
99
+ skipIf: has.brew ? 'brew is on PATH' : null, // undo: Homebrew's uninstaller is interactive, so none
100
+ });
101
+ }
102
+
103
+ if (win && needsGit) {
104
+ add({
105
+ id: 'git', label: 'Git', why: 'A selected tool needs git (the release itself does not).',
106
+ commands: has.winget ? [WINGET('Git.Git')] : [], manual: has.winget ? undefined : 'https://git-scm.com/downloads',
107
+ undo: has.winget ? [['winget', 'uninstall', '--id', 'Git.Git', '-e']] : null,
108
+ skipIf: has.git ? 'git is on PATH' : null,
109
+ });
110
+ }
111
+
112
+ if (platform === 'linux') {
113
+ // -E: apt needs the proxy variables, which sudo drops by default. A user with no sudo gets the manual link.
114
+ const sudo = probe.root ? [] : ['sudo', '-E'];
115
+ const aptOk = has.apt && (probe.root || has.sudo);
116
+ const apt = (pkg) => aptOk ? {
117
+ commands: [[...sudo, 'apt-get', 'update', '-qq'], [...sudo, 'apt-get', 'install', '-y', '-qq', '--no-install-recommends', pkg]],
118
+ undo: [[...sudo, 'apt-get', 'remove', '-y', '-qq', pkg]],
119
+ } : { commands: [] };
120
+
121
+ if (needsGit) {
122
+ add({
123
+ id: 'git', label: 'Git', why: "The agents' plugin and skill installs clone with git.",
124
+ ...apt('git'), manual: aptOk ? undefined : 'https://git-scm.com/downloads',
125
+ skipIf: has.git ? 'git is on PATH' : null,
126
+ });
127
+ }
128
+ if (!has.bun) {
129
+ add({
130
+ id: 'unzip', label: 'unzip', why: 'Unpacks the pinned Bun zip.',
131
+ ...apt('unzip'), manual: aptOk ? undefined : 'https://infozip.sourceforge.net/UnZip.html',
132
+ skipIf: has.unzip ? 'unzip is on PATH' : null,
133
+ });
134
+ }
135
+ }
136
+
137
+ // The brew-based steps below run after the Homebrew step, so a planned brew counts.
138
+ const pm = mac && (has.brew || steps.some((s) => s.id === 'homebrew')) ? 'brew' : win && has.winget ? 'winget' : null;
139
+
140
+ if (win) {
141
+ const setup = P.join(tmp, 'nvm-setup.exe');
142
+ add({
143
+ id: 'nvm', label: 'nvm-windows', why: 'Node manager: lets the tools get Node 24 without touching your Node.',
144
+ commands: [fetch(NVM_WIN.url, setup), [node, VERIFY_SHA, setup, NVM_WIN.sha256], [setup, '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART']], // admin-free path VERIFY
145
+ skipIf: has.nvm ? 'nvm is installed' : null,
146
+ });
147
+ } else {
148
+ const script = P.join(tmp, 'nvm-install.sh');
149
+ add({
150
+ id: 'nvm', label: 'nvm', why: 'Node manager: lets the tools get Node 24 without touching your Node.',
151
+ // PROFILE=/dev/null keeps the installer away from the shell profile; the engine finds $NVM_DIR itself. Script hash VERIFY.
152
+ commands: [fetch(NVM_INSTALL_URL, script), ['env', `NVM_DIR=${nvmDir}`, 'PROFILE=/dev/null', 'bash', script]],
153
+ undo: nvmDirExisted ? [] : nvmUndo(nvmDir, home, minVersion(floor)[0]),
154
+ skipIf: has.nvm ? 'nvm is installed' : null,
155
+ });
156
+ }
157
+
158
+ const haveFloor = (nodeActive && satisfies(nodeActive, floor)) || nvmNodes.some((v) => satisfies(v, floor));
159
+ add({
160
+ id: 'node-24', label: 'Node 24 (under nvm)', why: `Context Mode and GSD need Node ${floorText(floor)}+; your own Node stays the default.`,
161
+ commands: [win ? NVM_WIN_INSTALL_24 : ['env', `NVM_DIR=${nvmDir}`, ...nvmInstallArgv(24)]], // nvm-windows `install 24` accepts a major: VERIFY
162
+ skipIf: haveFloor ? `Node ${floorText(floor)}+ is already available` : null,
163
+ });
164
+
165
+ const route = (brew, wingetId, manual) => (pm === 'brew' && brew ? [brew] : pm === 'winget' && wingetId ? [WINGET(wingetId)] : null) ?? { manual };
166
+ const tool = (id, label, why, has_, r, extra = {}) => add({
167
+ id, label, why, skipIf: has_ ? `${id} is on PATH` : null, ...extra,
168
+ ...(Array.isArray(r) ? { commands: r } : { commands: [], manual: r.manual }),
169
+ });
170
+
171
+ const uvScript = P.join(tmp, 'uv-install.sh');
172
+ tool('uv', 'uv', 'Runs Serena (uvx).', has.uv,
173
+ !win && !pm ? [fetch(UV_INSTALL_URL, uvScript), ['sh', uvScript]] : route(['brew', 'install', 'uv'], 'astral-sh.uv', 'https://docs.astral.sh/uv/getting-started/installation/'), // direct script unpinned: VERIFY
174
+ pm === 'brew' ? { undo: [['brew', 'uninstall', 'uv']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'astral-sh.uv', '-e']] } : {});
175
+ const rtk = !win && !pm ? (probe.rtkInstall ?? rtkInstall)(home, tmp, platform, arch) : null;
176
+ tool('rtk', 'RTK', 'Compresses command output for the agents.', has.rtk,
177
+ rtk ? rtk.run : route(['brew', 'install', 'rtk'], 'rtk-ai.rtk', 'https://github.com/rtk-ai/rtk#installation'),
178
+ rtk ? { undo: rtk.undo } : pm === 'brew' ? { undo: [['brew', 'uninstall', 'rtk']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'rtk-ai.rtk', '-e']] } : {});
179
+
180
+ if (terminals.includes('warp') && agents.includes('claude')) {
181
+ tool('jq', 'jq', 'The Warp plugin for Claude Code reads hook JSON with jq.', has.jq,
182
+ route(['brew', 'install', 'jq'], 'jqlang.jq', 'https://jqlang.org/download/'),
183
+ pm === 'brew' ? { undo: [['brew', 'uninstall', 'jq']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'jqlang.jq', '-e']] } : {});
184
+ }
185
+
186
+ const bun = (probe.bunInstall ?? bunInstall)(home, tmp, platform, pm, arch); // probe.bunInstall: tests only
187
+ add({
188
+ id: 'bun', label: 'Bun', why: 'Lets Context Mode run JS and TS.', skipIf: has.bun ? 'bun is installed' : null,
189
+ // the zip lands in tmp
190
+ commands: bun ? [...(mac ? [] : [[node, '-e', 'require("fs").mkdirSync(process.argv[1], { recursive: true })', tmp]]), ...bun.run] : [],
191
+ undo: bun?.undo ?? null,
192
+ ...(bun ? {} : { manual: 'https://bun.sh/docs/installation' }),
193
+ });
194
+
195
+ return steps.map((s) => {
196
+ const out = { ...s, skipIf: s.skipIf ?? (done.includes(s.resumeKey) ? 'finished in an earlier run' : null) };
197
+ if (proxyEnv.length && out.commands.length) out.proxyEnv = proxyEnv;
198
+ return out;
199
+ });
200
+ }
201
+
202
+ // What is left to run: steps with no skipIf.
203
+ export const pendingPrereqs = (steps) => steps.filter((s) => !s.skipIf);
@@ -0,0 +1,22 @@
1
+ // Shell rc files and the marked PATH block a POSIX install writes into them, so a new terminal finds what it installed (#335).
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ // An existing .zshrc, .bashrc or .bash_profile, else .zshrc for a zsh user, else .profile.
6
+ export const rcFiles = (home, shell, fsx = fs) => {
7
+ const have = ['.zshrc', '.bashrc', '.bash_profile'].filter((f) => fsx.existsSync(path.join(home, f)));
8
+ return (have.length ? have : [/zsh$/.test(shell ?? '') ? '.zshrc' : '.profile']).map((f) => path.join(home, f));
9
+ };
10
+
11
+ // dirs: folders under home (e.g. '.local/bin'); brew: the Homebrew prefix this run installs; privateNode: install.sh's own Node.
12
+ // The private Node goes last, so a Node the user already has stays the default.
13
+ export function posixPathBlock({ home, platform, envPath = '', dirs = [], brew = null, privateNode = false, shell, fsx = fs }) {
14
+ if (platform === 'win32') return [];
15
+ const have = new Set(envPath.split(':').map((d) => d.replace(/\/+$/, '')));
16
+ const lines = [];
17
+ if (brew && !have.has(`${brew}/bin`)) lines.push(`[ -x ${brew}/bin/brew ] && eval "$(${brew}/bin/brew shellenv)"`); // a failed Homebrew install must not break every shell
18
+ const add = dirs.filter((d) => !have.has(path.join(home, d)));
19
+ if (add.length) lines.push(`export PATH="${add.map((d) => `$HOME/${d}`).join(':')}:$PATH"`);
20
+ if (privateNode) lines.push('export PATH="$PATH:$HOME/.config/lean-agents/node/bin"');
21
+ return lines.length ? rcFiles(home, shell, fsx).map((p) => ({ kind: 'block', id: 'path', path: p, body: lines.join('\n') })) : [];
22
+ }
@@ -0,0 +1,30 @@
1
+ // Data model of the finish-step summary page (#181). Pure: the page (PR3) only renders this object.
2
+ import { redactText } from './redact.mjs';
3
+
4
+ const BAD = new Set(['error', 'missing']);
5
+
6
+ // state: state.json (or null); rows: doctor rows `{ item, status, detail }`; applied: the `printApplied` shape
7
+ // `{ ok, files, commands, errors, version }`; logins: loginRows(); updated: names the update step changed (default none).
8
+ export function buildSummary({ state = null, rows = [], applied = {}, logins = [], updated = [], home, env, lang = 'en' } = {}) {
9
+ const t = (v) => redactText(v, { home, env });
10
+ const list = (a) => (a ?? []).map(t);
11
+ const problems = rows.filter((r) => BAD.has(r.status));
12
+ return {
13
+ lang,
14
+ version: t(applied.version ?? state?.version ?? ''),
15
+ ok: (applied.ok ?? true) && !problems.length,
16
+ action: { logins: logins.map((l) => ({ tool: l.tool, command: t(l.login), state: l.state })) },
17
+ summary: {
18
+ installed: list([...(applied.files ?? []), ...(applied.commands ?? []).filter((c) => c.ok).map((c) => c.desc)]),
19
+ kept: list(rows.filter((r) => r.status === 'changed').map((r) => r.item)),
20
+ updated: list(updated),
21
+ skipped: list(rows.filter((r) => r.status === 'skipped').map((r) => r.item)),
22
+ errors: list(applied.errors),
23
+ doctor: {
24
+ ok: !problems.length,
25
+ counts: rows.reduce((n, r) => ({ ...n, [r.status]: (n[r.status] ?? 0) + 1 }), {}),
26
+ problems: problems.map((r) => ({ item: t(r.item), status: r.status, detail: t(r.detail ?? '') })),
27
+ },
28
+ },
29
+ };
30
+ }