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
@@ -3,12 +3,26 @@
3
3
  // file - a whole file lean-agents owns (rules, agent definitions, loaders)
4
4
  // json - edits to a JSON/JSONC file the user owns; comments and formatting survive
5
5
  // block - a marked block inside a text file the user owns (CLAUDE.md, AGENTS.md);
6
- // toml: true uses # markers and puts the block first, so its keys stay top-level
6
+ // toml: true uses # markers and puts the block first, so its keys stay top-level;
7
+ // id: '<name>' uses # markers named by id (shell rc files: several blocks per file, and HTML markers break the shell)
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
9
10
  import crypto from 'node:crypto';
10
11
  import { parse, modify, applyEdits, findNodeAtLocation, parseTree } from 'jsonc-parser';
11
12
 
13
+ // Rename that waits out a file another process holds for a moment (Windows antivirus or indexer: EBUSY, EPERM, EACCES on a file
14
+ // just written). Retries `tries` times, `ms` apart; if it still fails, the error says so and keeps its code.
15
+ const waitMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
16
+ export function renameRetry(from, to, { rename = fs.renameSync, sleep = waitMs, tries = 8, ms = 250 } = {}) {
17
+ for (let i = 1; ; i++) {
18
+ try { return rename(from, to); } catch (e) {
19
+ if (!['EBUSY', 'EPERM', 'EACCES'].includes(e.code)) throw e;
20
+ if (i >= tries) throw Object.assign(new Error(`${e.message} (still locked after ${tries} tries over ${Math.round(((tries - 1) * ms) / 1000)} s: another program holds it; close it and try again)`), { code: e.code });
21
+ sleep(ms);
22
+ }
23
+ }
24
+ }
25
+
12
26
  export const OWNED_MARK = 'managed by lean-agents';
13
27
  const BLOCK_START = '<!-- lean-agents:start -->';
14
28
  const BLOCK_END = '<!-- lean-agents:end -->';
@@ -153,8 +167,10 @@ export function revertJsonEdits(text, applied) {
153
167
  return text;
154
168
  }
155
169
 
156
- export function setBlock(original, body, toml = false) {
157
- const [open, close] = toml ? [TOML_START, TOML_END] : [BLOCK_START, BLOCK_END];
170
+ const idMarks = (id) => [`# lean-agents:${id}:start`, `# lean-agents:${id}:end`];
171
+
172
+ export function setBlock(original, body, toml = false, id = undefined) {
173
+ const [open, close] = id ? idMarks(id) : toml ? [TOML_START, TOML_END] : [BLOCK_START, BLOCK_END];
158
174
  const block = `${open}\n${body.trim()}\n${close}`;
159
175
  const text = original ?? '';
160
176
  const start = text.indexOf(open);
@@ -167,13 +183,16 @@ export function setBlock(original, body, toml = false) {
167
183
  return `${text}${sep}${block}\n`;
168
184
  }
169
185
 
170
- export function removeBlock(text) {
171
- for (const [open, close] of [[BLOCK_START, BLOCK_END], [TOML_START, TOML_END]]) {
186
+ export function removeBlock(text, id = undefined) {
187
+ for (const [open, close] of id ? [idMarks(id)] : [[BLOCK_START, BLOCK_END], [TOML_START, TOML_END]]) {
172
188
  const start = text.indexOf(open);
173
189
  const end = text.indexOf(close);
174
190
  if (start < 0 || end < start) continue;
175
- const rest = text.slice(0, start) + text.slice(end + close.length);
176
- return (start === 0 ? rest.replace(/^\n+/, '') : rest).replace(/\n{3,}$/, '\n\n').replace(/^\n+$/, '');
191
+ const head = text.slice(0, start);
192
+ const tail = text.slice(end + close.length).replace(/^\n+/, '');
193
+ // A block between two others leaves one blank line, not the separators of both.
194
+ const rest = tail ? head.replace(/\n*$/, head ? '\n\n' : '') + tail : head;
195
+ return rest.replace(/\n{3,}$/, '\n\n').replace(/^\n+$/, '');
177
196
  }
178
197
  return text;
179
198
  }
@@ -215,7 +234,7 @@ export function plan(actions, roots = [], prior = []) {
215
234
  keptKeys = r.kept.map((k) => k.path.join('.'));
216
235
  if (r.kept.length) note = `kept your values for: ${r.kept.map((k) => k.path.join('.')).join(', ')}`;
217
236
  } else if (a.kind === 'block') {
218
- after = setBlock(before, a.body, a.toml);
237
+ after = setBlock(before, a.body, a.toml, a.id);
219
238
  }
220
239
  const status = before === null ? 'create' : before === after ? 'unchanged' : 'modify';
221
240
  // A file lean-agents created and nobody edited since holds nothing of the user's: a rerun needs no backup of it.
@@ -232,9 +251,8 @@ export function describe(planned, home) {
232
251
  .join('\n');
233
252
  }
234
253
 
235
- // Write planned changes. Returns state entries for uninstall.
236
- export function apply(planned, backupDir, home, roots = [home]) {
237
- const entries = [];
254
+ // Write planned changes. Returns state entries for uninstall; a caller that passes `entries` keeps what was written if a later write throws.
255
+ export function apply(planned, backupDir, home, roots = [home], entries = []) {
238
256
  for (const p of planned) {
239
257
  if (p.status === 'skip' || p.status === 'unchanged') continue;
240
258
  const blocked = unsafe(p.path, roots);
@@ -246,13 +264,21 @@ export function apply(planned, backupDir, home, roots = [home]) {
246
264
  privateDir(path.dirname(backup), path.dirname(backupDir));
247
265
  writePrivate(backup, p.before);
248
266
  }
267
+ // The folders this write creates, deepest first: undo removes them again once they are empty (#223).
268
+ const dirs = [];
269
+ for (let d = path.dirname(p.path); !fs.existsSync(d); d = path.dirname(d)) dirs.push(d);
249
270
  fs.mkdirSync(path.dirname(p.path), { recursive: true });
271
+ entries.push({ path: p.path, kind: p.kind, created: p.before === null, backup, hash: sha(p.after), applied: p.applied, noRestore: p.applied?.some((e) => e.upgraded), keepEmpty: p.keepEmpty, ...(p.id && { id: p.id }), ...(dirs.length && { dirs }) });
250
272
  fs.writeFileSync(p.path, p.after);
251
- entries.push({ path: p.path, kind: p.kind, created: p.before === null, backup, hash: sha(p.after), applied: p.applied, noRestore: p.applied?.some((e) => e.upgraded), keepEmpty: p.keepEmpty });
252
273
  }
253
274
  return entries;
254
275
  }
255
276
 
277
+ // Only empty folders: a file the user added since keeps its folder.
278
+ function removeEmptyDirs(dirs = []) {
279
+ for (const d of dirs) try { fs.rmdirSync(d); } catch { return; }
280
+ }
281
+
256
282
  // Undo state entries. If the user edited a file after install, remove only our parts.
257
283
  export function undo(entries, roots = []) {
258
284
  const report = [];
@@ -260,11 +286,12 @@ export function undo(entries, roots = []) {
260
286
  const blocked = unsafe(e.path, roots);
261
287
  if (blocked) { report.push(['left (symlink)', e.path]); continue; }
262
288
  const now = read(e.path);
263
- if (now === null) continue;
289
+ if (now === null) { removeEmptyDirs(e.dirs); continue; }
264
290
  const untouched = sha(now) === e.hash;
265
291
  if (untouched && e.created) {
266
292
  fs.rmSync(e.path);
267
293
  report.push(['removed', e.path]);
294
+ removeEmptyDirs(e.dirs);
268
295
  } else if (untouched && e.backup && !e.noRestore && fs.existsSync(e.backup)) {
269
296
  fs.writeFileSync(e.path, fs.readFileSync(e.backup, 'utf8'));
270
297
  report.push(['restored', e.path]);
@@ -274,6 +301,7 @@ export function undo(entries, roots = []) {
274
301
  if (e.created && left && typeof left === 'object' && !Object.keys(left).length) {
275
302
  fs.rmSync(e.path);
276
303
  report.push(['removed', e.path]);
304
+ removeEmptyDirs(e.dirs);
277
305
  continue;
278
306
  }
279
307
  // A tool that rejects a file without its container key (Copilot: "mcpServers: Required") keeps it empty.
@@ -281,7 +309,7 @@ export function undo(entries, roots = []) {
281
309
  fs.writeFileSync(e.path, text);
282
310
  report.push(['reverted our keys', e.path]);
283
311
  } else if (e.kind === 'block') {
284
- fs.writeFileSync(e.path, removeBlock(now));
312
+ fs.writeFileSync(e.path, removeBlock(now, e.id));
285
313
  report.push(['removed our block', e.path]);
286
314
  } else {
287
315
  report.push(['left (you edited it)', e.path]);
@@ -146,8 +146,9 @@ export function treeSha(dir, fsx) {
146
146
  return h.digest('hex');
147
147
  }
148
148
 
149
- // Skills (a folder with SKILL.md) found in two or more of `dirs`. Two paths that are one folder (a link) are not a duplicate.
150
- export function duplicateSkills(dirs, fsx = fs) {
149
+ // Skills (a folder with SKILL.md) found in two or more of `dirs`. Two paths that are one folder (a link) are not a duplicate,
150
+ // unless `links` is set: --adopt counts them, because a client scanning both paths still meets the skill twice (#176).
151
+ export function duplicateSkills(dirs, fsx = fs, { links = false } = {}) {
151
152
  const found = new Map();
152
153
  for (const d of dirs) {
153
154
  let names;
@@ -156,7 +157,7 @@ export function duplicateSkills(dirs, fsx = fs) {
156
157
  let real;
157
158
  try { real = fsx.realpathSync(j(d, name)); } catch { real = j(d, name); }
158
159
  const list = found.get(name) ?? [];
159
- if (!list.some((x) => x.real === real)) list.push({ dir: d, real });
160
+ if (links || !list.some((x) => x.real === real)) list.push({ dir: d, real });
160
161
  found.set(name, list);
161
162
  }
162
163
  }
@@ -164,7 +165,7 @@ export function duplicateSkills(dirs, fsx = fs) {
164
165
  const shas = l.map((x) => treeSha(j(x.dir, name), fsx));
165
166
  const unreadable = shas.includes(UNREADABLE);
166
167
  // The load order is not documented and OpenCode 1.19's log shows the "existing" copy changing per skill (#78), so no winner is claimed.
167
- return { name, dirs: l.map((x) => x.dir), shas, unreadable, differs: unreadable || new Set(shas).size > 1, winner: 'unknown (load order)' };
168
+ return { name, dirs: l.map((x) => x.dir), shas, unreadable, linked: new Set(l.map((x) => x.real)).size < l.length, differs: unreadable || new Set(shas).size > 1, winner: 'unknown (load order)' };
168
169
  });
169
170
  }
170
171
 
@@ -0,0 +1,28 @@
1
+ // Login checklist (#181): one row per tool with the command the user runs. Read-only, never reads or stores credentials.
2
+ import { quiet, which } from './system.mjs';
3
+
4
+ // `status` is an upstream read-only command whose exit code says logged in (0) or not; null means no such command is verified (docs/compatibility.md).
5
+ const TOOLS = [
6
+ { tool: 'gh', login: 'gh auth login', status: ['gh', 'auth', 'status'], bin: 'gh' },
7
+ { tool: 'claude', agent: 'claude', login: 'claude auth login', status: ['claude', 'auth', 'status'], bin: 'claude' },
8
+ { tool: 'opencode', agent: /^opencode-v[12]$/, login: 'opencode, then /connect', status: null },
9
+ { tool: 'copilot', agent: 'copilot-cli', login: 'copilot, then /login', status: null },
10
+ { tool: 'antigravity', agent: 'antigravity', login: 'agy', status: null },
11
+ { tool: 'vscode-copilot', agent: 'vscode-copilot', login: 'sign in to GitHub Copilot from the VS Code Accounts menu', status: null },
12
+ ];
13
+
14
+ // Rows `{ tool, login, state }`, state: ok | needed | unknown (not checked: no verified command, `exec` off, outbound off, tool missing, or the probe timed out).
15
+ // Only the exit code is used; the probe's output is dropped on purpose (it can hold an account name or email).
16
+ export function loginRows({ agents = [], gh = false, exec = false, outbound = 'on', run = quiet, have = which } = {}) {
17
+ const wanted = TOOLS.filter((t) => (t.tool === 'gh' ? gh : t.agent instanceof RegExp ? agents.some((a) => t.agent.test(a)) : agents.includes(t.agent)));
18
+ return wanted.map(({ tool, login, status, bin }) => {
19
+ let state = 'unknown';
20
+ // `gh auth status` may refresh a token over the network, so strict runs only show the command.
21
+ if (exec && status && outbound !== 'off' && have(bin)) {
22
+ const r = run(status, 15000);
23
+ // A timeout or signal (offline, slow proxy) is not a "not logged in" answer.
24
+ state = r.ok ? 'ok' : r.failed ? 'unknown' : 'needed';
25
+ }
26
+ return { tool, login, state };
27
+ });
28
+ }
@@ -1,5 +1,4 @@
1
1
  // Network choices (telemetry, auto-update, other outbound calls) and proxy handling for child commands.
2
- import os from 'node:os';
3
2
  export const CATEGORIES = ['telemetry', 'autoUpdate', 'outbound'];
4
3
  export const preset = (value) => Object.fromEntries(CATEGORIES.map((c) => [c, value]));
5
4
 
@@ -15,6 +14,10 @@ export function fromPrivacy(privacy) {
15
14
  return preset(privacy === 'strict' ? 'off' : 'on');
16
15
  }
17
16
 
17
+ // Mode for the agent self-updater switch (#182, #284): forced when the category is off, absent when the user chose updates
18
+ // on (`--auto-update on`, per-category menu, or the saved choice), else written only when the user has no value.
19
+ export const updaterMode = (opts) => (opts.network.autoUpdate === 'off' ? 'set' : opts.keepUpdater ? null : 'setIfAbsent');
20
+
18
21
  export const privacyOf = (network) => (CATEGORIES.every((c) => network[c] === 'off') ? 'strict' : 'standard');
19
22
 
20
23
  // Env for the commands lean-agents runs, so installers do not phone home when telemetry is off.
@@ -30,26 +33,58 @@ export const redactUrl = (v) => v.replace(/(^|\/\/|=)[^/\s=]*@/g, '$1***@');
30
33
  // Names whose values are secrets: redactText scrubs their values, allowedEnv never passes them on.
31
34
  export const SECRET_NAME = /TOKEN|SECRET|PASSW|API_?KEY|(^|_)AUTH($|_)|CREDENTIAL|PRIVATE/i;
32
35
 
33
- // Light scrub for proxy and CA values the user needs to read: no userinfo, no query string, home as ~.
34
- export function scrubValue(v, home = os.homedir()) {
35
- const out = redactUrl(v).replace(/\?\S*/g, '?<redacted>');
36
- return home ? out.split(home).join('~') : out;
37
- }
38
-
39
36
  // What a child process may inherit. Sources are in docs/compatibility.md; the rest (GH_TOKEN, API keys, ...) stays here.
40
37
  const ENV_EXACT = new Set(['PATH', 'HOME', 'USER', 'LOGNAME', 'USERNAME', 'SHELL', 'TERM', 'COLORTERM', 'LANG', 'TZ', 'TMPDIR', 'TMP', 'TEMP', 'CI', 'NODE_OPTIONS', 'NODE_USE_ENV_PROXY', 'OPENSSL_CONF', 'DO_NOT_TRACK', 'COPILOT_HOME', 'CLAUDE_CONFIG_DIR', 'BUN_INSTALL']);
41
38
  const ENV_WINDOWS = ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'CommonProgramFiles', 'HOMEDRIVE', 'HOMEPATH', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'PSModulePath', 'ALLUSERSPROFILE', 'PUBLIC', 'COMPUTERNAME'];
42
39
  const ENV_PREFIX = ['LC_', 'XDG_', 'NPM_CONFIG_', 'NODE_', 'NVM_', 'FNM_', 'VOLTA_', 'HOMEBREW_', 'UV_', 'GIT_', 'BUN_', 'OPENCODE_'];
43
40
 
44
- export function allowedEnv(env = process.env, platform = process.platform) {
41
+ // Names that run code or carry a credential inside a prefix we otherwise pass (#163). `:` and `//` are npm per-registry keys (`//host/:_authToken`).
42
+ const ENV_DROP = /^(NODE_PATH|GIT_CONFIG.*|GIT_ASKPASS|GIT_SSH|GIT_SSH_COMMAND|GIT_PROXY_COMMAND|GIT_EXEC_PATH|GIT_EDITOR|GIT_PAGER|GIT_EXTERNAL_DIFF|NPM_CONFIG_SCRIPT_SHELL)$|:|\/\//i;
43
+ // Values that hold a credential whatever the name: `://user:pass@` or `://token@`, GitHub and npm tokens.
44
+ const SECRET_VALUE = /:\/\/[^/\s@]+@|\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}|\bnpm_[A-Za-z0-9]{20,}/;
45
+
46
+ // NODE_OPTIONS passes only when every token is a CA, proxy, memory or DNS setting a corporate proxy setup needs; --require, --import and the like can run code.
47
+ const SAFE_NODE_FLAG = /^--(use-(system|openssl|bundled)-ca|use-env-proxy|max-old-space-size=\d+|dns-result-order=\w+)$/;
48
+ const SPACE_VALUE = { '--max-old-space-size': /^\d+$/, '--dns-result-order': /^\w+$/ };
49
+ function safeNodeOptions(v) {
50
+ const t = v.trim().split(/\s+/);
51
+ for (let i = 0; i < t.length; i++) {
52
+ if (SAFE_NODE_FLAG.test(t[i])) continue;
53
+ const value = SPACE_VALUE[t[i]];
54
+ if (!value || !value.test(t[i + 1] ?? '')) return false;
55
+ i++;
56
+ }
57
+ return true;
58
+ }
59
+
60
+ // One stderr line per new name, names only: a dropped NODE_OPTIONS or GIT_CONFIG_* would otherwise vanish without a trace (#235).
61
+ // resetDropWarnings lets a test start from a clean slate, so stderr does not depend on test order.
62
+ const warnedDrop = new Set();
63
+ export const resetDropWarnings = () => warnedDrop.clear();
64
+ function warnDropped(names) {
65
+ const fresh = names.filter((n) => !warnedDrop.has(n));
66
+ if (!fresh.length) return;
67
+ fresh.forEach((n) => warnedDrop.add(n));
68
+ console.error(`lean-agents: not passed to child processes (unsafe or carries a credential): ${fresh.join(', ')}`);
69
+ }
70
+
71
+ // onDrop gets the names of variables that would have passed but were dropped; never their values.
72
+ export function allowedEnv(env = process.env, platform = process.platform, onDrop = warnDropped) {
45
73
  const exact = new Set([...ENV_EXACT, ...PROXY_VARS, ...CA_VARS, ...(platform === 'win32' ? ENV_WINDOWS : [])].map((n) => n.toUpperCase()));
46
74
  const out = {};
75
+ const dropped = [];
47
76
  const seen = new Set(); // Windows keeps one key per name in any case; a plain object could hold both
48
77
  for (const [name, value] of Object.entries(env)) {
49
78
  const up = name.toUpperCase();
50
- if (value == null || SECRET_NAME.test(name) || seen.has(up)) continue;
51
- if (exact.has(up) || ENV_PREFIX.some((p) => up.startsWith(p))) { out[name] = value; seen.add(up); }
79
+ if (value == null || seen.has(up)) continue;
80
+ const wanted = exact.has(up) || ENV_PREFIX.some((p) => up.startsWith(p));
81
+ // A corporate proxy URL may carry user:pass on purpose; the child needs it.
82
+ const unsafe = (up === 'NODE_OPTIONS' && value && !safeNodeOptions(value)) || SECRET_NAME.test(name) || ENV_DROP.test(name)
83
+ || (!exact.has(up) && SECRET_VALUE.test(PROXY_VARS.includes(up) ? value.replace(/:\/\/[^/\s@]*@/, '://') : value));
84
+ if (unsafe) { if (wanted && !seen.has(up)) dropped.push(name); continue; }
85
+ if (wanted) { out[name] = value; seen.add(up); }
52
86
  }
87
+ if (dropped.length) onDrop(dropped);
53
88
  return out;
54
89
  }
55
90
 
@@ -68,12 +103,17 @@ export function shareProxy(env = process.env) {
68
103
  // True when a proxy is configured (NO_PROXY alone is not one).
69
104
  export const hasProxy = (env = process.env) => PROXY_VARS.slice(0, 3).some((n) => env[n] || env[n.toLowerCase()]);
70
105
 
71
- export function proxyReport(env = process.env, home = os.homedir()) {
106
+ // Values never leave this report (proxy hosts and CA paths are internal): only set / not set, plus loopback in NO_PROXY.
107
+ export function proxyReport(env = process.env) {
72
108
  const lines = [];
73
109
  for (const name of PROXY_VARS) {
74
110
  const value = env[name] || env[name.toLowerCase()];
75
- if (value) lines.push(`${name}=${scrubValue(value, home)}`);
111
+ if (!value) continue;
112
+ if (name !== 'NO_PROXY') { lines.push(`${name}=set`); continue; }
113
+ const have = value.split(',').map((x) => x.trim());
114
+ const missing = ['localhost', '127.0.0.1', '::1'].filter((h) => !have.includes(h));
115
+ lines.push(`NO_PROXY=set (loopback ${missing.length ? `missing: ${missing.join(', ')}` : 'present'})`);
76
116
  }
77
- for (const name of CA_VARS) if (env[name]) lines.push(`${name}=${scrubValue(env[name], home)}`);
117
+ for (const name of CA_VARS) if (env[name]) lines.push(`${name}=set`);
78
118
  return lines;
79
119
  }
@@ -0,0 +1,204 @@
1
+ // Permanent backup and frozen copy of the OpenCode 1.x data (#80 part 2, P3): `--upgrade-agent opencode --backup`.
2
+ // Order: preflight (read-only) -> raw backup, every file sha256-checked against its source, session count on a temp copy
3
+ // -> frozen copy made from the backup and checked again. The live data is only read: never opened for writing, never
4
+ // checkpointed or VACUUMed. Both copies are built in `<name>.partial` and renamed when verified; a finished copy is never deleted.
5
+ // `home`, `list`, `statfs` and `count` are passed in so tests never read the real machine.
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { countInChild } from './adopt.mjs';
12
+ import { configHome, envDir } from './system.mjs';
13
+ import { privateDir, renameRetry } from './fsops.mjs';
14
+
15
+ const j = path.join;
16
+ const GIB = 1024 ** 3;
17
+ export const DB_FILES = ['opencode.db', 'opencode.db-wal', 'opencode.db-shm'];
18
+ export const DATA_DIRS = ['storage', 'snapshot'];
19
+ export const STAMP_FILE = 'STAMP.json';
20
+
21
+ export const stamp = (d = new Date()) => d.toISOString().replace(/\.\d+Z$/, 'Z').replace(/[-:]/g, '');
22
+ // Backup + frozen copy are two full copies; keep 1 GiB spare (plan 80b, decision 2).
23
+ // The temp count copy of the db (os.tmpdir(), often the same volume) adds one more db.
24
+ export const neededBytes = (bytes, dbBytes = 0) => 2 * bytes + dbBytes + GIB;
25
+ export const opencodeRunning = (names) => names.some((n) => /^opencode(\.exe)?$/i.test(n.trim().split(/[\\/]/).pop()));
26
+
27
+ // Image names of every running process. shortcut: found by image name only (the 2.x service, and 1.19's platform binary, which npm's node wrapper spawns: VERIFY), not by command line.
28
+ export function listProcesses(platform = process.platform) {
29
+ const win = platform === 'win32';
30
+ const out = execFileSync(win ? 'tasklist' : 'ps', win ? ['/FO', 'CSV', '/NH'] : ['-A', '-o', 'comm='], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
31
+ return out.split(/\r?\n/).map((l) => (win ? /^"([^"]*)"/.exec(l)?.[1] ?? '' : l)).filter(Boolean);
32
+ }
33
+
34
+ // Written last, atomically, once every check passed: backup-stamp.mjs reads it to open the apply gate.
35
+ function writeStamp(dir, info) {
36
+ const tmp = j(dir, `${STAMP_FILE}.tmp`);
37
+ fs.writeFileSync(tmp, `${JSON.stringify({ version: 1, verified: true, ...info }, null, 2)}\n`, { mode: 0o600 });
38
+ renameRetry(tmp, j(dir, STAMP_FILE));
39
+ }
40
+
41
+ export function backupLayout(home, ts) {
42
+ const dataRoot = envDir(home, 'XDG_DATA_HOME', j(home, '.local', 'share'));
43
+ const lean = j(dataRoot, 'lean-agents');
44
+ // `frozen` is what `opencode1` will use as XDG_DATA_HOME: 1.x reads `<frozen>/opencode`.
45
+ return { live: j(dataRoot, 'opencode'), config: j(configHome(home), 'opencode'), lean, backup: j(lean, 'backups', `opencode1-sessions-${ts}`), frozen: j(lean, 'opencode1', 'data') };
46
+ }
47
+
48
+ // Regular files under `root` (relative, '/'-separated); anything else (a symlink) stops the backup instead of being followed.
49
+ function walk(root, skip, rel = '', out = []) {
50
+ for (const e of fs.readdirSync(j(root, rel), { withFileTypes: true })) {
51
+ const r = rel ? `${rel}/${e.name}` : e.name;
52
+ if (skip && e.name === skip) continue;
53
+ if (e.isDirectory()) walk(root, skip, r, out);
54
+ else if (e.isFile()) out.push({ rel: r, size: fs.statSync(j(root, r)).size });
55
+ else throw new Error(`${j(root, r)} is not a regular file (a link?); not copied`);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ export function listSource({ live, config }) {
61
+ const data = DB_FILES.filter((f) => fs.existsSync(j(live, f))).map((f) => ({ rel: f, size: fs.statSync(j(live, f)).size }));
62
+ for (const d of DATA_DIRS) if (fs.existsSync(j(live, d))) data.push(...walk(live, null, d));
63
+ // node_modules is rebuilt by OpenCode; the rest of the config dir (plugins, commands, AGENTS.md) is the snapshot.
64
+ return { data, config: fs.existsSync(config) ? walk(config, 'node_modules') : [] };
65
+ }
66
+
67
+ export function sha256File(file) {
68
+ const h = crypto.createHash('sha256');
69
+ const buf = Buffer.allocUnsafe(1 << 20);
70
+ const fd = fs.openSync(file, 'r');
71
+ try { for (let n; (n = fs.readSync(fd, buf, 0, buf.length, null)) > 0;) h.update(buf.subarray(0, n)); } finally { fs.closeSync(fd); }
72
+ return h.digest('hex');
73
+ }
74
+
75
+ // Copy `entries` from `src` to `dst` (0700 dirs), then compare sha256 of every source and copied file. Returns [{rel, sha}].
76
+ export function copyVerified(src, dst, entries) {
77
+ for (const { rel } of entries) {
78
+ fs.mkdirSync(path.dirname(j(dst, rel)), { recursive: true, mode: 0o700 });
79
+ fs.copyFileSync(j(src, rel), j(dst, rel));
80
+ }
81
+ return entries.map(({ rel }) => {
82
+ const sha = sha256File(j(src, rel));
83
+ if (sha256File(j(dst, rel)) !== sha) throw new Error(`sha256 differs after copying ${rel}`);
84
+ return { rel, sha };
85
+ });
86
+ }
87
+
88
+ // Session count on a temp copy of the db (+wal/shm), never on `dir` itself: opening a db can write its wal. null = not counted.
89
+ // shortcut: the copy goes to os.tmpdir(); a small tmpfs /tmp cannot hold a multi-GB db. Upgrade when someone hits it.
90
+ export function countCopy(dir, count = countInChild) {
91
+ const tmp = fs.mkdtempSync(j(os.tmpdir(), 'lean-count-'));
92
+ try {
93
+ for (const f of DB_FILES) if (fs.existsSync(j(dir, f))) fs.copyFileSync(j(dir, f), j(tmp, f));
94
+ return count(j(tmp, 'opencode.db'), null).sessions ?? null;
95
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
96
+ }
97
+
98
+ const nearest = (p) => { while (!fs.existsSync(p) && path.dirname(p) !== p) p = path.dirname(p); return p; };
99
+ const gb = (n) => `${(n / GIB).toFixed(2)} GB`;
100
+
101
+ function restoreText(L, ts, sessions) {
102
+ return `# Restore the OpenCode 1.x data (backup ${ts}, ${sessions} sessions)
103
+
104
+ Made by lean-agents (\`--upgrade-agent opencode --backup\`). lean-agents never deletes this folder.
105
+ Close every OpenCode first. \`data/\` is a raw copy of \`${L.live}\` (db, -wal, -shm, storage, snapshot); \`config/\` is \`${L.config}\` without node_modules.
106
+
107
+ Check the files (macOS, Linux; from this folder): \`sha256sum -c MANIFEST.sha256\` (macOS: \`shasum -a 256 -c MANIFEST.sha256\`)
108
+
109
+ macOS, Linux (set the current data aside, then copy the backup back):
110
+
111
+ mv "${L.live}" "${L.live}.aside"
112
+ cp -a "${j(L.backup, 'data')}" "${L.live}"
113
+
114
+ Windows (PowerShell):
115
+
116
+ Move-Item "${L.live}" "${L.live}.aside"
117
+ Copy-Item -Recurse "${j(L.backup, 'data')}" "${L.live}"
118
+
119
+ The config: copy the files in \`config/\` over \`${L.config}\` the same way.
120
+ `;
121
+ }
122
+
123
+ // Returns { ok, sessions, backup, frozen }. dryRun: preflight and the plan only, nothing is written.
124
+ export function backupOpencode({ home, dryRun = false, log = console.log, now = new Date(), list = listProcesses, statfs = fs.statfsSync, count = countInChild }) {
125
+ const ts = stamp(now);
126
+ const L = backupLayout(home, ts);
127
+ const refuse = (problems) => { log(`refused, nothing changed:\n${problems.map((p) => ` - ${p}`).join('\n')}`); return { ok: false }; };
128
+ if (!fs.existsSync(j(L.live, 'opencode.db'))) return refuse([`no opencode.db in ${L.live}: nothing to back up`]);
129
+
130
+ const problems = [];
131
+ try {
132
+ if (opencodeRunning(list())) problems.push('an opencode process is running (the 1.x app or the 2.x background service): close it first');
133
+ } catch (e) { problems.push(`cannot list the running processes (${String(e.message).split('\n')[0]}): not safe to copy`); }
134
+ let src;
135
+ try { src = listSource(L); } catch (e) { return refuse([e.message]); }
136
+ const bytes = [...src.data, ...src.config].reduce((n, f) => n + f.size, 0);
137
+ const st = statfs(nearest(L.lean));
138
+ const dbBytes = src.data.filter((f) => f.rel.startsWith('opencode.db')).reduce((n, f) => n + f.size, 0);
139
+ const free = Number(st.bavail) * Number(st.bsize);
140
+ if (free < neededBytes(bytes, dbBytes)) problems.push(`not enough free space: ${gb(free)} free, ${gb(neededBytes(bytes, dbBytes))} needed (2 x ${gb(bytes)} + the db once more for the count copy + 1 GB)`);
141
+ if (fs.existsSync(L.frozen)) problems.push(`a frozen copy already exists at ${L.frozen}: lean-agents does not overwrite it`);
142
+ if (fs.existsSync(L.backup)) problems.push(`${L.backup} already exists: try again in a second`);
143
+ let sessions = null;
144
+ let countCopied = true;
145
+ log(`counting the sessions on a temp copy of the db (${gb(dbBytes)}; minutes on a large db)`);
146
+ try { sessions = countCopy(L.live, count); } catch (e) { countCopied = false; problems.push(`could not copy the db to count sessions (${String(e.message).split('\n')[0]})`); }
147
+ if (sessions === null && countCopied && (dryRun || !problems.length)) problems.push('could not count the sessions (no Node with node:sqlite answered: missing, too old or timed out): the backup could not be checked');
148
+ if (dryRun) {
149
+ log(`dry run: would copy ${src.data.length} data files + ${src.config.length} config files (${gb(bytes)}, ${sessions === null ? 'unknown' : sessions} sessions)`);
150
+ log(` free space: ${gb(free)} free, ${gb(neededBytes(bytes, dbBytes))} needed (2 x data + db + 1 GB)`);
151
+ log(` permanent backup: ${L.backup}`);
152
+ log(` frozen copy: ${L.frozen}`);
153
+ if (problems.length) log(`blocker for apply: ${problems.join('; ')}`);
154
+ log('dry run: nothing was written');
155
+ return { ok: true, sessions, backup: L.backup, frozen: L.frozen };
156
+ }
157
+
158
+ if (problems.length) return refuse(problems);
159
+
160
+ log(`copying ${src.data.length} data files + ${src.config.length} config files (${gb(bytes)}, ${sessions} sessions)`);
161
+ log(` permanent backup: ${L.backup}`);
162
+ log(` frozen copy: ${L.frozen}`);
163
+
164
+ const part = `${L.backup}.partial`;
165
+ const fpart = `${L.frozen}.partial`;
166
+ let manifestCount = 0;
167
+ try {
168
+ fs.rmSync(part, { recursive: true, force: true });
169
+ fs.rmSync(fpart, { recursive: true, force: true });
170
+ privateDir(part, L.lean);
171
+ const manifest = [
172
+ ...copyVerified(L.live, j(part, 'data'), src.data).map((m) => ({ ...m, rel: `data/${m.rel}` })),
173
+ ...copyVerified(L.config, j(part, 'config'), src.config).map((m) => ({ ...m, rel: `config/${m.rel}` })),
174
+ ];
175
+ manifestCount = manifest.length;
176
+ fs.writeFileSync(j(part, 'MANIFEST.sha256'), manifest.map((m) => `${m.sha} ${m.rel}`).join('\n') + '\n', { mode: 0o600 });
177
+ fs.writeFileSync(j(part, 'RESTORE.md'), restoreText(L, ts, sessions), { mode: 0o600 });
178
+ // OpenCode may have started during the copy, which then can miss its last writes (#253).
179
+ if (opencodeRunning(list())) throw new Error('an opencode process started during the copy: close it and run this again');
180
+ renameRetry(part, L.backup);
181
+ log('backup: every file sha256 equals its source');
182
+ } catch (e) {
183
+ fs.rmSync(part, { recursive: true, force: true });
184
+ log(`backup failed: ${e.message}\nnothing else was changed (the live data was only read)`);
185
+ return { ok: false };
186
+ }
187
+ try {
188
+ const after = countCopy(j(L.backup, 'data'), count);
189
+ if (after !== sessions) throw new Error(`session count differs: ${sessions} live, ${after} in the backup`);
190
+ log(`backup: ${after} sessions on a temp copy, equal to the live count`);
191
+ privateDir(j(fpart, 'opencode'), L.lean);
192
+ copyVerified(j(L.backup, 'data'), j(fpart, 'opencode'), src.data);
193
+ const frozen = countCopy(j(fpart, 'opencode'), count);
194
+ if (frozen !== sessions) throw new Error(`session count differs: ${sessions} live, ${frozen} in the frozen copy`);
195
+ renameRetry(fpart, L.frozen);
196
+ log(`frozen copy: every file sha256 equals the backup, ${frozen} sessions`);
197
+ writeStamp(L.backup, { ts, sessions, files: manifestCount });
198
+ } catch (e) {
199
+ fs.rmSync(fpart, { recursive: true, force: true });
200
+ log(`failed: ${e.message}\nthe permanent backup is kept at ${L.backup}; the live data was only read`);
201
+ return { ok: false, backup: L.backup };
202
+ }
203
+ return { ok: true, sessions, backup: L.backup, frozen: L.frozen };
204
+ }