lean-agents 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +407 -0
- package/LICENSE +21 -0
- package/README.es.md +560 -0
- package/README.md +559 -2
- package/core/AGENTS.es.md +60 -0
- package/core/AGENTS.md +60 -0
- package/core/README.md +8 -0
- package/core/agents/debug.md +14 -0
- package/core/agents/explore.md +13 -0
- package/core/agents/planner.md +14 -0
- package/core/agents/research.md +13 -0
- package/core/agents/review.md +13 -0
- package/core/copilot-usage-tui.js +189 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +39 -0
- package/core/tiers.json +4 -0
- package/node_modules/@clack/core/LICENSE +9 -0
- package/node_modules/@clack/core/README.md +22 -0
- package/node_modules/@clack/core/dist/index.d.mts +503 -0
- package/node_modules/@clack/core/dist/index.mjs +1003 -0
- package/node_modules/@clack/core/package.json +63 -0
- package/node_modules/@clack/prompts/LICENSE +9 -0
- package/node_modules/@clack/prompts/README.md +396 -0
- package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
- package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
- package/node_modules/@clack/prompts/package.json +67 -0
- package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
- package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
- package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
- package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
- package/node_modules/fast-string-truncated-width/license +21 -0
- package/node_modules/fast-string-truncated-width/package.json +35 -0
- package/node_modules/fast-string-truncated-width/readme.md +59 -0
- package/node_modules/fast-string-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-width/dist/index.js +14 -0
- package/node_modules/fast-string-width/license +21 -0
- package/node_modules/fast-string-width/package.json +34 -0
- package/node_modules/fast-string-width/readme.md +42 -0
- package/node_modules/fast-wrap-ansi/LICENSE +23 -0
- package/node_modules/fast-wrap-ansi/README.md +26 -0
- package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
- package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
- package/node_modules/fast-wrap-ansi/package.json +51 -0
- package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
- package/node_modules/jsonc-parser/LICENSE.md +21 -0
- package/node_modules/jsonc-parser/README.md +364 -0
- package/node_modules/jsonc-parser/SECURITY.md +41 -0
- package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
- package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
- package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
- package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
- package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
- package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
- package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
- package/node_modules/jsonc-parser/package.json +37 -0
- package/node_modules/sisteransi/license +21 -0
- package/node_modules/sisteransi/package.json +34 -0
- package/node_modules/sisteransi/readme.md +113 -0
- package/node_modules/sisteransi/src/index.js +58 -0
- package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
- package/package.json +30 -4
- package/profiles/README.md +10 -0
- package/profiles/anthropic-api/gsd-defaults.json +26 -0
- package/profiles/anthropic-api.json +18 -0
- package/profiles/antigravity.json +12 -0
- package/profiles/claude-subscription/gsd-defaults.json +26 -0
- package/profiles/claude-subscription.json +17 -0
- package/profiles/github-copilot/gsd-defaults.json +26 -0
- package/profiles/github-copilot.json +17 -0
- package/profiles/openai-api/gsd-defaults.json +26 -0
- package/profiles/openai-api.json +17 -0
- package/profiles/opencode-go/gsd-defaults.json +26 -0
- package/profiles/opencode-go.json +17 -0
- package/profiles/vertex-gemini/gsd-defaults.json +26 -0
- package/profiles/vertex-gemini.json +18 -0
- package/scripts/adhd-skill.mjs +12 -0
- package/scripts/behavior-diff.sh +47 -0
- package/scripts/bump-pins.mjs +115 -0
- package/scripts/check-private.sh +52 -0
- package/scripts/check-readme.mjs +131 -0
- package/scripts/ci-download.sh +20 -0
- package/scripts/ci-install-opencode-v2.sh +6 -0
- package/scripts/ci-latest-report.mjs +38 -0
- package/scripts/ci-timing.mjs +61 -0
- package/scripts/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +56 -0
- package/scripts/lean.mjs +1319 -0
- package/scripts/lib/adapters/antigravity.mjs +83 -0
- package/scripts/lib/adapters/claude.mjs +127 -0
- package/scripts/lib/adapters/copilot-cli.mjs +82 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +79 -0
- package/scripts/lib/adapters/opencode-v2.mjs +216 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +619 -0
- package/scripts/lib/agent-lifecycle.mjs +280 -0
- package/scripts/lib/backup-stamp.mjs +25 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +279 -0
- package/scripts/lib/feedback.mjs +48 -0
- package/scripts/lib/fsops.mjs +319 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +196 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/logins.mjs +28 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +119 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/opencode-backup.mjs +204 -0
- package/scripts/lib/opencode-upgrade.mjs +441 -0
- package/scripts/lib/opencode1.mjs +203 -0
- package/scripts/lib/parallel.mjs +270 -0
- package/scripts/lib/pins-diff.mjs +33 -0
- package/scripts/lib/pins.mjs +52 -0
- package/scripts/lib/plugin-health.mjs +191 -0
- package/scripts/lib/prereqs.mjs +203 -0
- package/scripts/lib/project.mjs +38 -0
- package/scripts/lib/redact.mjs +30 -0
- package/scripts/lib/render.mjs +101 -0
- package/scripts/lib/shell-path.mjs +22 -0
- package/scripts/lib/summary-data.mjs +30 -0
- package/scripts/lib/summary-html.mjs +159 -0
- package/scripts/lib/system.mjs +269 -0
- package/scripts/lib/terminals.mjs +316 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/update-plan.mjs +60 -0
- package/scripts/lib/upgrade.mjs +231 -0
- package/scripts/lib/verify-commit.mjs +16 -0
- package/scripts/lib/verify-prompt.mjs +46 -0
- package/scripts/lib/verify-sha256.mjs +20 -0
- package/scripts/lint-workflows.mjs +25 -0
- package/scripts/models-refresh.mjs +58 -0
- package/scripts/parallel.mjs +59 -0
- package/scripts/pins-latest.mjs +66 -0
- package/scripts/release.mjs +71 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +124 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|