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
@@ -0,0 +1,441 @@
1
+ // `--upgrade-agent opencode --yes` (apply) and `--undo` (#80 part 2, P6): one journal, five steps, rollback in reverse.
2
+ // Steps: backup (re-verify the stamp), opencode1 (P4), install2x, config (P5 translation + managed items), dcp (P5).
3
+ // The journal lives in state.json under `upgrade` and is saved before and after every step, so a killed run still shows what to undo.
4
+ // Apply never opens or starts OpenCode 2 itself: the live 1.x data is only read, and it must equal the backup when the run starts.
5
+ // A failed step undoes the finished steps in reverse; if the live data changed meanwhile it is restored like `--undo` does.
6
+ // Nothing here deletes the permanent backup or the frozen copy; a 2.x-migrated db is moved aside, never removed.
7
+ // Every effect outside the data (installer, state file, adapter) comes in through `d`, so tests use fakes.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { backupLayout, listSource, copyVerified, countCopy, sha256File, stamp as stampTs, DB_FILES, DATA_DIRS } from './opencode-backup.mjs';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { layout as layout1, removeOpencode1 } from './opencode1.mjs';
14
+ import { upgradeApply } from './upgrade.mjs';
15
+ import { undo as undoEntries, privateDir, renameRetry } from './fsops.mjs';
16
+ import { configHome } from './system.mjs';
17
+
18
+ const j = path.join;
19
+ const GIB = 1024 ** 3;
20
+ const first = (e) => String(e?.message ?? e).split('\n')[0];
21
+ const iso = () => new Date().toISOString();
22
+
23
+ export const STEPS = ['backup', 'opencode1', 'install2x', 'config', 'dcp'];
24
+ // A journal in one of these states means an upgrade is live (or half undone): apply refuses, `--undo` works, `--uninstall` refuses.
25
+ export const ACTIVE = ['applying', 'rolling-back', 'applied', 'undoing', 'rollback-failed', 'undo-failed'];
26
+ export const isActive = (u) => Boolean(u) && ACTIVE.includes(u.status);
27
+
28
+ // Fault injection for CI: fail right after the named step finished, so its undo is exercised too.
29
+ // Test-only on purpose: no flag, and it refuses to run unless LEAN_AGENTS_TEST=1 is set as well.
30
+ export function failAt(env = process.env) {
31
+ const v = env.LEAN_TEST_FAIL_AT;
32
+ if (!v) return null;
33
+ if (env.LEAN_AGENTS_TEST !== '1') throw new Error('LEAN_TEST_FAIL_AT is a test-only setting (it needs LEAN_AGENTS_TEST=1): unset it');
34
+ if (!STEPS.includes(v)) throw new Error(`LEAN_TEST_FAIL_AT=${v}: unknown step (${STEPS.join(', ')})`);
35
+ return v;
36
+ }
37
+
38
+ // --- the backup, read-only ---
39
+
40
+ export function manifestOf(dir) {
41
+ return fs.readFileSync(j(dir, 'MANIFEST.sha256'), 'utf8').split('\n').filter(Boolean).map((l) => {
42
+ const m = /^([0-9a-f]{64}) {2}(.+)$/.exec(l);
43
+ if (!m || path.isAbsolute(m[2]) || m[2].split('/').includes('..')) throw new Error(`bad line in ${j(dir, 'MANIFEST.sha256')}: ${l.slice(0, 80)}`);
44
+ return { sha: m[1], rel: m[2] };
45
+ });
46
+ }
47
+
48
+ // Problems found re-hashing the backup against its manifest ([] = every file equals its recorded sha256).
49
+ export function verifyBackup(dir) {
50
+ const bad = [];
51
+ try {
52
+ for (const { sha, rel } of manifestOf(dir)) {
53
+ const f = j(dir, ...rel.split('/'));
54
+ if (!fs.existsSync(f)) bad.push(`${rel} is missing from the backup`);
55
+ else if (sha256File(f) !== sha) bad.push(`${rel} differs from its recorded sha256`);
56
+ }
57
+ } catch (e) { bad.push(first(e)); }
58
+ return bad;
59
+ }
60
+
61
+ // null when the live data equals the backup, else the first difference. Read-only.
62
+ export function liveDiffers(L, dir) {
63
+ try {
64
+ const want = new Map(manifestOf(dir).filter((m) => m.rel.startsWith('data/')).map((m) => [m.rel.slice(5), m.sha]));
65
+ const have = listSource({ live: L.live, config: j(L.live, '.none') }).data;
66
+ if (have.length !== want.size) return `${have.length} files now, ${want.size} in the backup`;
67
+ for (const f of have) if (want.get(f.rel) !== sha256File(j(L.live, ...f.rel.split('/')))) return `${f.rel} changed since the backup`;
68
+ return null;
69
+ } catch (e) { return first(e); }
70
+ }
71
+
72
+ // null when the live data equals the frozen copy (what `--undo` leaves behind: the 1.x state plus the sessions opencode1 made).
73
+ export function frozenDiffers(L) {
74
+ try {
75
+ const frozen = j(L.frozen, 'opencode');
76
+ const none = j(frozen, '.none');
77
+ const a = listSource({ live: L.live, config: none }).data;
78
+ const b = listSource({ live: frozen, config: none }).data;
79
+ if (a.length !== b.length) return `${a.length} files now, ${b.length} in the frozen copy`;
80
+ const want = new Map(b.map((f) => [f.rel, f.size]));
81
+ for (const f of a) {
82
+ if (want.get(f.rel) !== f.size || sha256File(j(L.live, ...f.rel.split('/'))) !== sha256File(j(frozen, ...f.rel.split('/')))) return `${f.rel} differs from the frozen copy`;
83
+ }
84
+ return null;
85
+ } catch (e) { return first(e); }
86
+ }
87
+
88
+ // What the live data equals right now: the backup, the frozen copy (after an earlier --undo) or neither.
89
+ export const liveBaseline = (L, dir) => (liveDiffers(L, dir) === null ? 'backup' : frozenDiffers(L) === null ? 'frozen' : null);
90
+
91
+ // Problem with the frozen copy, or null. It equals the backup until 1.x writes to it (opencode1 run/serve change only the frozen db),
92
+ // so a copy that differs is trusted only if it still counts at least the backup's sessions; fewer, or not countable, is not.
93
+ export function frozenProblem(home, dir, { count, sessions = null } = {}) {
94
+ const L = backupLayout(home, 'x');
95
+ const frozen = j(L.frozen, 'opencode');
96
+ if (!fs.existsSync(j(frozen, 'opencode.db'))) return `the frozen copy has no opencode.db (${frozen})`;
97
+ try {
98
+ const have = new Map(listSource({ live: frozen, config: j(frozen, '.none') }).data.map((f) => [f.rel, sha256File(j(frozen, ...f.rel.split('/')))]));
99
+ const want = manifestOf(dir).filter((m) => m.rel.startsWith('data/'));
100
+ if (have.size === want.length && want.every((m) => have.get(m.rel.slice(5)) === m.sha)) return null;
101
+ const need = sessions ?? countCopy(j(dir, 'data'), count);
102
+ const got = countCopy(frozen, count);
103
+ if (got === null || need === null) return 'the frozen copy differs from the backup and its sessions could not be counted';
104
+ return got >= need ? null : `the frozen copy has ${got} sessions, the backup ${need}`;
105
+ } catch (e) { return first(e); }
106
+ }
107
+
108
+ // Live config files that differ from the 1.x snapshot in the backup (reported after an undo; never overwritten here).
109
+ export function configDrift(L, dir) {
110
+ const out = [];
111
+ try {
112
+ for (const { sha, rel } of manifestOf(dir).filter((m) => m.rel.startsWith('config/'))) {
113
+ const f = j(L.config, ...rel.slice(7).split('/'));
114
+ if (!fs.existsSync(f) || sha256File(f) !== sha) out.push(rel.slice(7));
115
+ }
116
+ } catch (e) { out.push(first(e)); }
117
+ return out;
118
+ }
119
+
120
+ // What stops an apply before anything is written: { problems, baseline } (no problems = go; baseline = what the live data equals).
121
+ export function applyPreflight({ home, stamp, upgrade, exec = true, list, opencodeRunning, count }) {
122
+ const problems = [];
123
+ let baseline = null;
124
+ if (!exec) problems.push('--no-exec: apply installs OpenCode 2 and runs `--version` probes, so it needs commands enabled');
125
+ if (isActive(upgrade)) problems.push(`an upgrade is already ${upgrade.status}: run --upgrade-agent opencode --undo first`);
126
+ if (!stamp) { problems.push('no verified session backup: run --upgrade-agent opencode --backup --yes first (no stamp, no apply)'); return { problems, baseline }; }
127
+ try { if (opencodeRunning(list())) problems.push('an opencode process is running (the 1.x app or the 2.x background service): close it first'); } catch (e) { problems.push(`cannot list the running processes (${first(e)}): not safe to continue`); }
128
+ const bad = verifyBackup(stamp.dir);
129
+ if (bad.length) problems.push(`the backup no longer matches its manifest (${bad[0]}${bad.length > 1 ? ` and ${bad.length - 1} more` : ''}): not used`);
130
+ else {
131
+ const L = backupLayout(home, 'x');
132
+ const bad2 = frozenProblem(home, stamp.dir, { count, sessions: stamp.sessions });
133
+ if (bad2) problems.push(`${bad2}: the frozen copy is not trusted. Move ${stamp.frozen} aside by hand (lean-agents never deletes it), then run --backup --yes again; the permanent backup in ${stamp.dir} is untouched`);
134
+ baseline = liveBaseline(L, stamp.dir);
135
+ if (!baseline) problems.push(`the live data changed since the backup (${liveDiffers(L, stamp.dir)}) and differs from the frozen copy: those sessions would not be in a copy. Move ${stamp.dir} and ${stamp.frozen} aside by hand (lean-agents never deletes them) and run --backup --yes again`);
136
+ }
137
+ return { problems, baseline };
138
+ }
139
+
140
+ // --- the data: move the 2.x db aside, copy the frozen copy back ---
141
+
142
+ // Replaces the live db, storage and snapshot with the frozen copy (or the permanent backup when the frozen copy holds fewer
143
+ // sessions). Order: choose the source and check its count, copy it next to the live folder and check it, move the live items to
144
+ // `backups/opencode2-db-<ts>/`, rename the copy into place. Anything else in the live folder (auth, logs) is left alone.
145
+ export function restoreData({ home, backupDir, now = new Date(), count, statfs = fs.statfsSync, rename = renameRetry, log = console.log }) {
146
+ const ts = stampTs(now);
147
+ const L = backupLayout(home, ts);
148
+ const frozenData = j(L.frozen, 'opencode');
149
+ const backupData = j(backupDir, 'data');
150
+ const want = countCopy(backupData, count);
151
+ let src = frozenData;
152
+ let n = fs.existsSync(j(frozenData, 'opencode.db')) ? countCopy(frozenData, count) : null;
153
+ if (want === null && n !== null) log('the backup could not be counted: using the frozen copy without the comparison');
154
+ else if (n === null || want === null || n < want) {
155
+ log(`the frozen copy has ${n ?? 'no countable'} sessions, the backup ${want ?? '?'}: restoring from the permanent backup`);
156
+ src = backupData;
157
+ n = want;
158
+ }
159
+ if (n === null) throw new Error('could not count the sessions (no Node with node:sqlite answered: missing, too old or timed out): the data is not restored');
160
+ const items = listSource({ live: src, config: j(src, '.none') }).data;
161
+ const bytes = items.reduce((t, f) => t + f.size, 0);
162
+ const dbBytes = items.filter((f) => f.rel.startsWith('opencode.db')).reduce((t, f) => t + f.size, 0);
163
+ let probe = L.lean;
164
+ while (!fs.existsSync(probe) && path.dirname(probe) !== probe) probe = path.dirname(probe);
165
+ const st = statfs(probe);
166
+ if (Number(st.bavail) * Number(st.bsize) < bytes + dbBytes + GIB) throw new Error(`not enough free space to copy ${src} back (${bytes + dbBytes + GIB} bytes needed): nothing was moved`);
167
+
168
+ const stage = `${L.live}.restore-partial`;
169
+ const aside = j(L.lean, 'backups', `opencode2-db-${ts}`);
170
+ // A rename onto an existing name would replace an earlier aside copy: never reuse a folder.
171
+ if (fs.existsSync(aside)) throw new Error(`${aside} already exists: try again in a second; nothing was moved`);
172
+ if (fs.existsSync(stage)) log(`replacing an earlier staged copy at ${stage} (a copy of the frozen copy or the backup)`);
173
+ fs.rmSync(stage, { recursive: true, force: true }); // our own leftover from an interrupted run
174
+ copyVerified(src, stage, items);
175
+ const staged = countCopy(stage, count);
176
+ if (staged !== n) throw new Error(`the staged copy has ${staged} sessions, expected ${n}: nothing was moved`);
177
+
178
+ const names = [...DB_FILES, ...DATA_DIRS];
179
+ const moved = [];
180
+ const placed = [];
181
+ try {
182
+ privateDir(aside, L.lean);
183
+ for (const name of names) if (fs.existsSync(j(L.live, name))) { rename(j(L.live, name), j(aside, name)); moved.push(name); }
184
+ fs.mkdirSync(L.live, { recursive: true });
185
+ for (const name of names) if (fs.existsSync(j(stage, name))) { rename(j(stage, name), j(L.live, name)); placed.push(name); }
186
+ } catch (e) {
187
+ // Put it back the way it was; if that fails too, the aside folder and the stage still hold every byte.
188
+ try {
189
+ for (const name of placed) rename(j(L.live, name), j(stage, name));
190
+ for (const name of moved) rename(j(aside, name), j(L.live, name));
191
+ } catch (e2) { throw new Error(`${first(e)}; putting the old data back failed too (${first(e2)}). Your data is in ${aside}, ${stage} and ${L.frozen}; see ${j(backupDir, 'RESTORE.md')}`); }
192
+ throw new Error(`${first(e)} (the old data was put back)`);
193
+ }
194
+ fs.rmSync(stage, { recursive: true, force: true });
195
+ const now2 = countCopy(L.live, count);
196
+ if (now2 !== n) throw new Error(`the restored data has ${now2} sessions, expected ${n}: see ${j(backupDir, 'RESTORE.md')}; the replaced data is in ${aside}`);
197
+ log(`restored ${n} sessions from ${src === frozenData ? 'the frozen copy' : 'the permanent backup'}; the replaced db is kept in ${aside}`);
198
+ return { sessions: n, aside, source: src };
199
+ }
200
+
201
+ // --- the journal ---
202
+
203
+ // A state.json that cannot be written (a Windows rename refused, a full disk) must not hide the way out: say so and go on.
204
+ const safeSave = (save, log) => () => { try { save(); } catch (e) { log(`could not save the journal (${first(e)}): the steps above are still undone in this run`); } };
205
+
206
+ async function unwind({ steps, journal, keep, ctx, log }) {
207
+ if (!Array.isArray(journal.steps)) throw new Error('the journal has no step list');
208
+ for (const rec of [...journal.steps].reverse()) {
209
+ if (rec.status === 'undone') continue;
210
+ const step = steps.find((s) => s.id === rec.id);
211
+ if (!step) throw new Error(`the journal names an unknown step "${rec.id}"`);
212
+ try {
213
+ await step.undo(rec, ctx);
214
+ } catch (e) { throw new Error(`could not undo step ${rec.id}: ${first(e)}`); }
215
+ rec.status = 'undone';
216
+ keep();
217
+ log(` undone: ${rec.id}`);
218
+ }
219
+ }
220
+
221
+ // Returns true when every step ran. On failure: undo finished steps in reverse; restore the data too if it changed. Never throws.
222
+ export async function runApply({ steps, journal, save, ctx, log = console.log, fail = null, restore }) {
223
+ const keep = safeSave(save, log);
224
+ try {
225
+ Object.assign(journal, { status: 'applying', startedAt: iso(), finishedAt: null, error: null, steps: [] });
226
+ save();
227
+ for (const s of steps) {
228
+ const rec = { id: s.id, status: 'running' };
229
+ journal.steps.push(rec);
230
+ save();
231
+ log(`step ${s.id}: ${s.desc}`);
232
+ await s.run(rec, ctx);
233
+ rec.status = 'done';
234
+ save();
235
+ if (fail === s.id) throw new Error(`injected failure after step ${s.id} (LEAN_TEST_FAIL_AT)`);
236
+ }
237
+ Object.assign(journal, { status: 'applied', finishedAt: iso() });
238
+ save();
239
+ return true;
240
+ } catch (e) {
241
+ Object.assign(journal, { status: 'rolling-back', error: first(e) });
242
+ keep();
243
+ log(`failed: ${first(e)}\nrolling back the finished steps (the backup and the frozen copy are kept)`);
244
+ try {
245
+ await unwind({ steps, journal, keep, ctx, log });
246
+ const drift = ctx.liveDrift();
247
+ if (drift) {
248
+ log(`the live data changed during the upgrade (${drift}): restoring it like --undo does`);
249
+ await restore();
250
+ }
251
+ Object.assign(journal, { status: 'rolled-back', finishedAt: iso() });
252
+ keep();
253
+ log('rolled back: everything this run changed was undone');
254
+ } catch (e2) {
255
+ Object.assign(journal, { status: 'rollback-failed', error: `${journal.error}; rollback: ${first(e2)}` });
256
+ keep();
257
+ log(`ROLLBACK STOPPED: ${first(e2)}\nNothing was deleted. Follow ${ctx.restoreMd} to put the 1.x data back by hand; then run --undo again.`);
258
+ }
259
+ return false;
260
+ }
261
+ }
262
+
263
+ // `--undo`: every step in reverse, then the data. Returns true when the 1.x state is back.
264
+ export async function runUndo({ steps, journal, save, ctx, log = console.log, restore }) {
265
+ const keep = safeSave(save, log);
266
+ try {
267
+ Object.assign(journal, { status: 'undoing', error: null });
268
+ keep();
269
+ await unwind({ steps, journal, keep, ctx, log });
270
+ const r = await restore();
271
+ Object.assign(journal, { status: 'undone', finishedAt: iso(), restored: { sessions: r.sessions, aside: r.aside } });
272
+ keep();
273
+ return true;
274
+ } catch (e) {
275
+ Object.assign(journal, { status: 'undo-failed', error: first(e) });
276
+ keep();
277
+ log(`UNDO STOPPED: ${first(e)}\nNothing was deleted. Follow ${ctx.restoreMd} to put the 1.x data back by hand; then run --undo again.`);
278
+ return false;
279
+ }
280
+ }
281
+
282
+ // What the steps and the rollback share: the journal lookup, the drift check and where the by-hand restore notes are.
283
+ export function makeCtx({ home, stamp, journal }) {
284
+ return {
285
+ restoreMd: j(stamp.dir, 'RESTORE.md'),
286
+ step: (id) => journal.steps.find((s) => s.id === id),
287
+ undoing: () => journal.status === 'undoing',
288
+ // The live data must still equal what it equaled when the apply started (the backup, or the frozen copy after an earlier --undo).
289
+ liveDrift: () => (journal.baseline === 'frozen' ? frozenDiffers(backupLayout(home, 'x')) : liveDiffers(backupLayout(home, 'x'), stamp.dir)),
290
+ };
291
+ }
292
+
293
+ // --- the real steps ---
294
+
295
+ // Runs `bin --version` with throwaway data and state dirs: a 2.x binary migrates a db it finds, so never the real or frozen one.
296
+ // A 2.x binary may print its version on stderr (the CI log of the first run showed no stdout version): read both, and keep what it
297
+ // printed when it fails, so the error names the cause. Returns the first x.y.z found.
298
+ export function probeBoth(bin, env) {
299
+ const r = spawnSync(bin, ['--version'], { env, encoding: 'utf8', timeout: 30000, windowsHide: true });
300
+ const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim();
301
+ const m = /(\d+\.\d+\.\d+)/.exec(out);
302
+ if (m) return m[1];
303
+ throw new Error(r.error ? first(r.error) : `exit ${r.status}, printed: ${out.slice(0, 120) || 'nothing'}`);
304
+ }
305
+
306
+ export function versionIn(bin, { probe = probeBoth, env = process.env } = {}) {
307
+ const scratch = fs.mkdtempSync(j(os.tmpdir(), 'lean-probe-'));
308
+ try { return probe(bin, { ...env, XDG_DATA_HOME: scratch, XDG_STATE_HOME: scratch, XDG_CACHE_HOME: scratch, XDG_CONFIG_HOME: scratch }); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
309
+ }
310
+
311
+ // d: { home, platform, log, state, save, inv, stamp, roots, adapterFor(tools), tools, backupDir(name), which(cmd), probe, manual,
312
+ // plan1(), install1(plan, files, onRecord), installAgent(), uninstallAgent() }
313
+ export function createSteps(d) {
314
+ const win = (d.platform ?? process.platform) === 'win32';
315
+ const ocBin = j(d.home, '.opencode', 'bin', `opencode${win ? '.exe' : ''}`);
316
+ const cfgRoot = configHome(d.home);
317
+ const tried = [];
318
+ const find2x = () => {
319
+ tried.length = 0;
320
+ for (const c of [ocBin, d.which?.('opencode')].filter((x) => x && fs.existsSync(x))) {
321
+ try {
322
+ const v = versionIn(c, { probe: d.probe });
323
+ if (/^2\./.test(v)) return { path: c, version: v };
324
+ tried.push(`${c}: version ${v}, not 2.x`);
325
+ } catch (e) { tried.push(`${c}: ${first(e)}`); }
326
+ }
327
+ return null;
328
+ };
329
+
330
+ // Saved before each write (fsops pushes the entry first), so a kill midway still leaves entries --undo can revert.
331
+ const journaled = (rec) => Object.assign([], { push: (...e) => { Array.prototype.push.apply(rec.entries, e); d.save(); return rec.entries.length; } });
332
+ const config = (id, desc, tools, translate) => ({
333
+ id, desc,
334
+ run(rec) {
335
+ rec.entries = journaled(rec);
336
+ const r = upgradeApply({ home: d.home, inv: translate ? d.inv : { items: [] }, adapter: d.adapterFor(tools), backupDir: d.backupDir(id), stamp: d.stamp, entries: rec.entries });
337
+ d.log(r.text);
338
+ },
339
+ undo(rec) {
340
+ for (const [what, file] of undoEntries(rec.entries ?? [], [cfgRoot])) d.log(` ${what.padEnd(20)} ${file}`);
341
+ },
342
+ });
343
+
344
+ return [
345
+ {
346
+ id: 'backup', desc: 'the verified backup and frozen copy (checked again, not copied)',
347
+ run(rec) { rec.dir = d.stamp.dir; rec.sessions = d.stamp.sessions; },
348
+ undo() { /* permanent: lean-agents never deletes it */ },
349
+ },
350
+ {
351
+ id: 'opencode1', desc: 'OpenCode 1.x side by side (binary copy, shim, PATH), reading only the frozen copy',
352
+ run(rec) {
353
+ // Set up earlier by `--opencode1 --yes`: kept as it is, and not ours to undo.
354
+ if (d.state.opencode1 && fs.existsSync(d.state.opencode1.binary)) { rec.preexisting = true; rec.opencode1 = d.state.opencode1; d.log(` already set up (${d.state.opencode1.binary}): kept`); return; }
355
+ const p = d.plan1();
356
+ if (!p.ok) throw new Error(`opencode1: ${p.problems.join('; ').replace(/\n\s*/g, ' ')}`); // one line: the step log prints only the first
357
+ rec.source = p.source;
358
+ rec.entries = journaled(rec);
359
+ d.install1(p, rec.entries, (record) => { rec.opencode1 = record; d.state.opencode1 = record; d.save(); });
360
+ },
361
+ undo(rec) {
362
+ if (rec.preexisting) return;
363
+ for (const [what, file] of undoEntries(rec.entries ?? [], [...d.roots, layout1(d.home).root])) d.log(` ${what.padEnd(20)} ${file}`);
364
+ if (rec.opencode1) for (const [what, file] of removeOpencode1(rec.opencode1, { home: d.home })) d.log(` ${what.padEnd(20)} ${file}`);
365
+ delete d.state.opencode1;
366
+ },
367
+ },
368
+ {
369
+ id: 'install2x', desc: 'OpenCode 2 (the installer may overwrite the 1.x binary; the copy from the step above is the way back)',
370
+ async run(rec) {
371
+ rec.preSha = fs.existsSync(ocBin) ? sha256File(ocBin) : null;
372
+ const have = find2x();
373
+ if (have) { rec.method = 'existing'; rec.version = have.version; rec.path = have.path; d.log(` OpenCode ${have.version} is already there (${have.path}): kept`); return; }
374
+ // The hand install overwrites ~/.opencode/bin/opencode.exe, and the rollback removes this run's 1.x copy: --opencode1 keeps it (#179 PC run).
375
+ if (d.manual) throw new Error(`${d.manual}. In this order: run --upgrade-agent opencode --opencode1 --yes (keeps the 1.x binary), install OpenCode 2 by hand, then run this again`);
376
+ rec.method = 'installer';
377
+ rec.installAttempted = true;
378
+ d.save();
379
+ await d.installAgent();
380
+ const now = find2x();
381
+ if (!now) throw new Error(`the OpenCode 2 install did not leave a working 2.x binary at ${ocBin}${tried.length ? ` (${tried.join('; ')})` : ''}`);
382
+ rec.version = now.version;
383
+ },
384
+ async undo(rec, ctx) {
385
+ if (rec.installAttempted) await d.uninstallAgent();
386
+ await restore1x(rec, ctx);
387
+ // The uninstall only logs when it fails: check that no 2.x is left before the opencode1 copy is removed.
388
+ if (rec.installAttempted && find2x()) throw new Error('OpenCode 2 is still installed after the uninstall: remove it by hand, then run --undo again (the 1.x copy is kept)');
389
+ },
390
+ },
391
+ config('config', 'the 2.x config: managed items and the translation of your 1.x keys (user-manual keys stay)', d.tools.config, true),
392
+ config('dcp', 'DCP on 2.x (plugin and dcp.jsonc; your own dcp.jsonc values are kept)', d.tools.dcp, false),
393
+ ];
394
+
395
+ // The installer writes the same path 1.x lived in (Windows, script installs): put the copied 1.x binary back, 2.x aside.
396
+ async function restore1x(rec, ctx) {
397
+ {
398
+ const copy = ctx.step('opencode1')?.opencode1?.binary;
399
+ if (rec.method === 'existing') {
400
+ // A rollback leaves the 2.x that was there before the run. --undo means back to 1.x: a 2.x installed by hand (the Windows route)
401
+ // sits where 1.x lived, so the opencode1 copy goes back there and 2.x aside (#179 PC run).
402
+ if (!ctx.undoing?.()) return;
403
+ if (rec.path === ocBin && copy && fs.existsSync(copy)) {
404
+ const want = sha256File(copy);
405
+ // Safe to run again: already back (an earlier --undo), or 2.x already moved aside by a put-back that failed later.
406
+ if (fs.existsSync(ocBin) && sha256File(ocBin) === want) return;
407
+ return putBack(copy, want);
408
+ }
409
+ d.log(` ! OpenCode ${rec.version} at ${rec.path} was there before this run and stays: start opencode1, not opencode, until you remove it (opencode would migrate the 1.x data again)`);
410
+ rec.kept2x = true;
411
+ return;
412
+ }
413
+ if (!rec.preSha) return;
414
+ if (fs.existsSync(ocBin) && sha256File(ocBin) === rec.preSha) return;
415
+ // Overwritten and no verified copy to put back: stop, the opencode1 copy stays.
416
+ if (!copy || !fs.existsSync(copy) || sha256File(copy) !== rec.preSha) throw new Error(`the file at ${ocBin} was replaced and the 1.x copy that matches it is missing or differs: not restored; the opencode1 copy is kept`);
417
+ return putBack(copy, rec.preSha);
418
+ }
419
+ }
420
+
421
+ // Moves the 2.x binary at ocBin aside and copies the 1.x binary there, sha256 checked against `want`.
422
+ function putBack(copy, want) {
423
+ {
424
+ if (fs.existsSync(ocBin)) {
425
+ const lean = backupLayout(d.home, 'x').lean;
426
+ const aside = j(lean, 'backups', `opencode2-bin-${stampTs()}`);
427
+ privateDir(aside, lean);
428
+ if (fs.existsSync(j(aside, path.basename(ocBin)))) throw new Error(`${aside} already holds a 2.x binary: not replaced`);
429
+ renameRetry(ocBin, j(aside, path.basename(ocBin)));
430
+ d.log(` moved the 2.x binary to ${aside}`);
431
+ }
432
+ fs.mkdirSync(path.dirname(ocBin), { recursive: true });
433
+ const part = `${ocBin}.partial`;
434
+ fs.copyFileSync(copy, part);
435
+ if (!win) fs.chmodSync(part, 0o755);
436
+ if (sha256File(part) !== want) { fs.rmSync(part, { force: true }); throw new Error('sha256 differs after copying the 1.x binary back'); }
437
+ renameRetry(part, ocBin);
438
+ d.log(` restored the 1.x binary at ${ocBin} (sha256 checked)`);
439
+ }
440
+ }
441
+ }
@@ -0,0 +1,203 @@
1
+ // `opencode1`: OpenCode 1.x side by side with 2.x (#80 part 2, P4): `--upgrade-agent opencode --opencode1`.
2
+ // Copies the 1.x binary to `<data>/lean-agents/opencode1/<version>/`, writes an owned shim `opencode1` (+ `opencode1.cmd` on Windows)
3
+ // that points XDG_DATA_HOME + XDG_STATE_HOME at the frozen copy (proven by the P1 spike) and XDG_CONFIG_HOME at its own copy of the
4
+ // 1.x config (the upgrade rewrites ~/.config/opencode to 2.x keys, which 1.x may reject), and puts the shim folder on PATH: a marked
5
+ // block in the shell rc file, or the HKCU user PATH on Windows. Files and blocks go through the engine's fsops actions; the copied
6
+ // binary and the HKCU entry are recorded in state.json (`opencode1`) and removed by `--uninstall`. The backup, the frozen copy and
7
+ // `opencode1/state` (what 1.x writes while it runs) and `opencode1/config` (the 1.x config copy) are never removed.
8
+ // `which`, `probe`, `winPath` and `shell` are passed in so tests never read the real machine or the registry.
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { rcFiles } from './shell-path.mjs';
13
+ import { execFileSync } from 'node:child_process';
14
+ import { backupLayout, sha256File } from './opencode-backup.mjs';
15
+ import { which as findOnPath } from './system.mjs';
16
+ import { plan as planActions, renameRetry } from './fsops.mjs';
17
+
18
+ const j = path.join;
19
+ const MIN_BINARY = 1 << 20; // npm ships a ~0.5 KB launcher in bin/ until its postinstall swaps in the native binary
20
+
21
+ export function layout(home) {
22
+ const { lean, frozen } = backupLayout(home, 'x');
23
+ const root = j(lean, 'opencode1');
24
+ return { root, frozen, state: j(root, 'state'), config: j(root, 'config'), bin: j(root, 'bin') };
25
+ }
26
+
27
+ const sq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
28
+ const MARK = 'managed by lean-agents: OpenCode 1.x on its own frozen copy of the data (#80); removed by --uninstall';
29
+
30
+ export function shimText(kind, { data, state, binary, config }) {
31
+ if (kind === 'cmd') {
32
+ const lines = ['@echo off', `rem ${MARK}`, 'setlocal', `set "XDG_DATA_HOME=${data}"`, `set "XDG_STATE_HOME=${state}"`, ...(config ? [`set "XDG_CONFIG_HOME=${config}"`] : []), `"${binary}" %*`, 'exit /b %errorlevel%'];
33
+ return `${lines.join('\r\n')}\r\n`;
34
+ }
35
+ const fwd = (p) => p.replace(/\\/g, '/'); // Git Bash on Windows reads D:/x
36
+ return `#!/bin/sh\n# ${MARK}\nexport XDG_DATA_HOME=${sq(fwd(data))}\nexport XDG_STATE_HOME=${sq(fwd(state))}\n${config ? `export XDG_CONFIG_HOME=${sq(fwd(config))}\n` : ''}exec ${sq(fwd(binary))} "$@"\n`;
37
+ }
38
+
39
+ // Where an `opencode` 1.x binary may be: the 2.x installer's folder (same path on Windows), what is on PATH, and npm's platform packages.
40
+ export function candidates({ home, platform = process.platform, whichPath = null, fsx = fs }) {
41
+ const ext = platform === 'win32' ? '.exe' : '';
42
+ const out = [j(home, '.opencode', 'bin', `opencode${ext}`)];
43
+ if (whichPath) {
44
+ let real = whichPath;
45
+ try { real = fsx.realpathSync(whichPath); } catch { /* keep the path as found */ }
46
+ out.push(real);
47
+ const dir = path.dirname(real);
48
+ for (const pkg of [j(dir, 'node_modules', 'opencode-ai'), path.dirname(dir)]) {
49
+ out.push(j(pkg, 'bin', `opencode${ext}`));
50
+ for (const base of [j(pkg, 'node_modules'), path.dirname(pkg)]) {
51
+ let names = [];
52
+ try { names = fsx.readdirSync(base); } catch { /* no such folder */ }
53
+ for (const n of names) if (/^opencode-/.test(n) && n !== 'opencode-ai') out.push(j(base, n, 'bin', `opencode${ext}`));
54
+ }
55
+ }
56
+ }
57
+ const big = (f) => { try { const s = fsx.statSync(f); return s.isFile() && s.size >= MIN_BINARY; } catch { return false; } };
58
+ return [...new Set(out)].filter((f) => !/\.(cmd|bat|ps1)$/i.test(f) && big(f));
59
+ }
60
+
61
+ export function probeVersion(bin, env) {
62
+ const out = execFileSync(bin, ['--version'], { env, encoding: 'utf8', timeout: 30000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
63
+ return out.trim().split(/\r?\n/).pop().trim();
64
+ }
65
+
66
+ // First candidate that runs and reports a 1.x version: { path, version }, or { tried: [...] }.
67
+ export function findBinary({ home, platform, whichPath, probe, env, fsx = fs }) {
68
+ const tried = [];
69
+ for (const c of candidates({ home, platform, whichPath, fsx })) {
70
+ try {
71
+ const v = probe(c, env);
72
+ if (/^1\.\d+\.\d+$/.test(v)) return { path: c, version: v };
73
+ tried.push(`${c} (version ${v || '?'}, not 1.x)`);
74
+ } catch (e) { tried.push(`${c} (does not run: ${String(e.message).split('\n')[0]})`); }
75
+ }
76
+ return { tried };
77
+ }
78
+
79
+ // User PATH on Windows, read and written unexpanded like install.ps1 does. Prints present | absent | changed.
80
+ const WIN_PATH_PS = `
81
+ $ErrorActionPreference = 'Stop'
82
+ $dir = $env:LEAN_PATH_DIR
83
+ function Open-Env($w) { [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $w) }
84
+ function Get-Norm($p) { [Environment]::ExpandEnvironmentVariables($p).TrimEnd('\\') }
85
+ $k = Open-Env $false
86
+ try { $raw = [string]$k.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } finally { $k.Close() }
87
+ $parts = @($raw -split ';' | Where-Object { $_ })
88
+ $has = @($parts | Where-Object { (Get-Norm $_) -eq (Get-Norm $dir) }).Count -gt 0
89
+ if ($env:LEAN_PATH_OP -eq 'has') { if ($has) { 'present' } else { 'absent' }; exit 0 }
90
+ if ($env:LEAN_PATH_OP -eq 'add' -or $env:LEAN_PATH_OP -eq 'prepend') {
91
+ if ($has) { 'present'; exit 0 }
92
+ if ($env:LEAN_PATH_OP -eq 'prepend') {
93
+ if (-not $raw) { $new = $dir } else { $new = "$dir;" + $raw.TrimStart(';') }
94
+ } else {
95
+ if (-not $raw) { $new = $dir } elseif ($raw.EndsWith(';')) { $new = "$raw$dir" } else { $new = "$raw;$dir" }
96
+ }
97
+ } else {
98
+ if (-not $has) { 'absent'; exit 0 }
99
+ $new = @($parts | Where-Object { (Get-Norm $_) -ne (Get-Norm $dir) }) -join ';'
100
+ }
101
+ $k = Open-Env $true
102
+ try { $k.SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $k.Close() }
103
+ [Environment]::SetEnvironmentVariable('LEAN_AGENTS_PATH_REFRESH', '1', 'User')
104
+ [Environment]::SetEnvironmentVariable('LEAN_AGENTS_PATH_REFRESH', $null, 'User')
105
+ 'changed'
106
+ `;
107
+ export const winPathDefault = (op, dir) => execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', WIN_PATH_PS], {
108
+ encoding: 'utf8', windowsHide: true, env: { ...process.env, LEAN_PATH_DIR: dir, LEAN_PATH_OP: op },
109
+ }).trim().split(/\r?\n/).pop();
110
+
111
+ // Read-only. Returns { ok, problems, version, source, binary, actions, pathDir } for `installOpencode1`.
112
+ // `configSnapshot`: the 1.x config folder saved by --backup (copied for the shim); without one the shim gets an empty config folder.
113
+ export function planOpencode1({ home, configSnapshot = null, exec = true, platform = process.platform, env = process.env, which = findOnPath, probe = probeVersion, shell = process.env.SHELL, fsx = fs }) {
114
+ const L = layout(home);
115
+ const win = platform === 'win32';
116
+ const problems = [];
117
+ if (!fsx.existsSync(j(L.frozen, 'opencode', 'opencode.db'))) problems.push(`no frozen copy at ${L.frozen}: run --upgrade-agent opencode --backup --yes first`);
118
+ // The binary is run once (`--version`) to name its folder and to prove the copy works: not under --no-exec.
119
+ if (!exec) problems.push('--no-exec: the 1.x binary has to run `--version`, so this step needs commands enabled');
120
+ if (problems.length) return { ok: false, problems };
121
+ // Candidates may be 2.x (it migrates a db it finds): probe them on an empty throwaway data dir, never on the frozen copy.
122
+ const scratch = fsx.mkdtempSync(j(os.tmpdir(), 'lean-probe-'));
123
+ let found;
124
+ try { found = findBinary({ home, platform, whichPath: which('opencode'), probe, env: { ...env, XDG_DATA_HOME: scratch, XDG_STATE_HOME: scratch }, fsx }); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
125
+ if (!found.path) problems.push(`no OpenCode 1.x binary found${found.tried.length ? `; tried:\n ${found.tried.join('\n ')}` : ' (none on PATH or in ~/.opencode/bin)'}`);
126
+ if (problems.length) return { ok: false, problems };
127
+
128
+ const binary = j(L.root, found.version, `opencode${win ? '.exe' : ''}`);
129
+ const text = { data: L.frozen, state: L.state, binary, config: L.config };
130
+ const actions = win
131
+ ? [{ kind: 'file', path: j(L.bin, 'opencode1.cmd'), content: shimText('cmd', text) }, { kind: 'file', path: j(L.bin, 'opencode1'), content: shimText('sh', text) }]
132
+ : [{ kind: 'file', path: j(L.bin, 'opencode1'), content: shimText('sh', text) },
133
+ ...rcFiles(home, shell, fsx).map((p) => ({ kind: 'block', id: 'opencode1', path: p, body: `export PATH=${sq(L.bin)}:"$PATH"` }))];
134
+ return { ok: true, problems, version: found.version, source: found.path, binary, actions, pathDir: L.bin, root: L.root, configSnapshot, configDir: j(L.config, 'opencode') };
135
+ }
136
+
137
+ // Writes. `files` collects the fsops entries (the caller saves them in state.json); `onRecord(record)` fires after each step that
138
+ // `--uninstall` must undo, so an error midway still leaves a state to undo. Returns the record (state.json `opencode1`).
139
+ export function installOpencode1(p, { home, roots, backupDir, apply, files = [], platform = process.platform, probe = probeVersion, env = process.env, winPath = winPathDefault, onRecord = () => {} }) {
140
+ const win = platform === 'win32';
141
+ const record = { version: p.version, dir: path.dirname(p.binary), binary: p.binary, binDir: p.pathDir, pathEntry: false };
142
+ const planned = planActions(p.actions, roots);
143
+ const refused = planned.filter((a) => a.status === 'skip');
144
+ if (refused.length) throw new Error(refused.map((a) => `${a.path}: ${a.note}`).join('; '));
145
+
146
+ if (fs.existsSync(p.binary)) {
147
+ if (sha256File(p.binary) !== sha256File(p.source)) throw new Error(`${p.binary} exists and differs from ${p.source}: not overwritten`);
148
+ } else {
149
+ fs.mkdirSync(record.dir, { recursive: true, mode: 0o700 });
150
+ const part = `${p.binary}.partial`;
151
+ fs.copyFileSync(p.source, part);
152
+ if (!win) fs.chmodSync(part, 0o755);
153
+ if (sha256File(part) !== sha256File(p.source)) throw new Error('sha256 differs after copying the binary');
154
+ const scratch = fs.mkdtempSync(j(os.tmpdir(), 'lean-probe-'));
155
+ let v;
156
+ try { v = probe(part, { ...env, XDG_DATA_HOME: scratch, XDG_STATE_HOME: scratch }); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
157
+ if (v !== p.version) throw new Error(`the copied binary reports "${v}", expected ${p.version}`);
158
+ renameRetry(part, p.binary);
159
+ }
160
+ // 1.x gets its own copy of the config it knew; an existing copy (the user may have edited it) is never overwritten.
161
+ const cfg = p.configDir ?? j(layout(home).config, 'opencode');
162
+ if (!fs.existsSync(cfg)) {
163
+ // Copy beside it and rename: a copy that fails midway must not leave a partial folder that later runs would keep.
164
+ const part = `${cfg}.partial`;
165
+ fs.rmSync(part, { recursive: true, force: true });
166
+ fs.mkdirSync(part, { recursive: true, mode: 0o700 });
167
+ if (p.configSnapshot && fs.existsSync(p.configSnapshot)) fs.cpSync(p.configSnapshot, part, { recursive: true, filter: (f) => path.basename(f) !== 'node_modules' });
168
+ renameRetry(part, cfg);
169
+ }
170
+ onRecord(record);
171
+ try { apply(planned, backupDir, home, roots, files); } finally { onRecord(record); }
172
+ if (!win) fs.chmodSync(p.actions[0].path, 0o755);
173
+ if (win) {
174
+ // Recorded before the registry write (a kill in between must not leave an HKCU entry --uninstall does not know about), but
175
+ // only when the entry was absent: removing one the user already had would be ours to answer for.
176
+ record.pathEntry = winPath('has', p.pathDir) === 'absent';
177
+ onRecord(record);
178
+ if (record.pathEntry) {
179
+ record.pathEntry = winPath('add', p.pathDir) === 'changed';
180
+ onRecord(record);
181
+ }
182
+ }
183
+ return record;
184
+ }
185
+
186
+ // Undo what `record` holds (the shim files and rc blocks are undone by fsops from state.files). Returns [what, path] lines.
187
+ export function removeOpencode1(record, { home, winPath = winPathDefault, platform = process.platform } = {}) {
188
+ const report = [];
189
+ const L = layout(home);
190
+ // Only ever inside <data>/lean-agents/opencode1: a hand-edited state.json cannot point this at anything else.
191
+ const inside = (p) => path.dirname(p) === L.root && p !== L.frozen && p !== L.state && p !== L.config && p !== L.bin;
192
+ // Only the copied binary, then the folder if nothing else is in it.
193
+ if (record.dir && inside(record.dir) && record.binary && path.dirname(record.binary) === record.dir && fs.existsSync(record.binary)) {
194
+ fs.rmSync(record.binary);
195
+ report.push(['removed', record.binary]);
196
+ try { fs.rmdirSync(record.dir); report.push(['removed', record.dir]); } catch { /* not empty: left */ }
197
+ }
198
+ try { if (fs.readdirSync(L.bin).length === 0) { fs.rmdirSync(L.bin); report.push(['removed', L.bin]); } } catch { /* absent or not empty */ }
199
+ if (record.pathEntry && platform === 'win32' && record.binDir === L.bin) {
200
+ if (winPath('remove', L.bin) === 'changed') report.push(['removed from user PATH', L.bin]);
201
+ }
202
+ return report;
203
+ }