Skip to content

Commit 1ad131a

Browse files
authored
fix(update): stage, verify, and swap npm self-updates with rollback (#2079)
* fix(update): stage, verify, and swap npm self-updates with rollback The npm self-update installed straight into the live global tree, so any failure after npm removed the old files left a file-less package skeleton with no recovery (#1849) and nothing verified the new tree before it went live (#1942). The launcher now stages the target version into a sibling directory (npm --prefix, same volume), verifies a manifest inside the stage (package.json version, launcher integrity, sentinel deps), moves live aside to a sibling backup, swaps the staged tree in, re-verifies, and rolls back by reverse rename on failure — writing a recovery marker with a one-line restore on double fault. A boot probe restores the newest backup over a broken live tree (power loss mid-swap) and reaps stale backups once live verifies. Staging and backup are SIBLINGS of the package dir, never children — a child would travel with the live rename and the live tree cannot move into its own subtree (design defect caught by the plan audit and fixed here). Closes #1942 Closes #1849 * fix(update): harden transactional swap per adversarial review - verify the bundled Bun binary by size (>=10MB), not just its package.json, so the boot probe can never call a Bun-less tree healthy and reap the only backup - bounded EPERM/EBUSY/EACCES rename retry for the Windows AV/indexer class - staging/backup mkdir failures return phase errors with live untouched; an unexpected throw now reports and stops instead of falling back to the destructive in-place install - the Windows service wrapper (outside the package tree) restores the newest .ocx-backup-* sibling before declaring the install incomplete — the exact power-loss window the in-launcher probe cannot reach
1 parent 11e03eb commit 1ad131a

6 files changed

Lines changed: 534 additions & 9 deletions

File tree

‎bin/ocx.mjs‎

Lines changed: 59 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
runNpmCachePreflight,
2323
} from "../src/update/npm-cache-preflight.mjs";
2424
import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs";
25+
import { bootRestoreProbe, transactionalNpmUpdate } from "../src/update/transactional-install.mjs";
2526

2627
const PKG = "@bitkyc08/opencodex";
2728
const require = createRequire(import.meta.url);
@@ -267,13 +268,50 @@ function runNpmSelfUpdate() {
267268
}
268269
}
269270

270-
console.log(`Updating${latest ? ` to v${latest}` : ""}...\n$ npm install -g ${PKG}@${tag}`);
271-
const res = spawnSync(installInvocation.file, installInvocation.args, {
272-
stdio: "inherit",
273-
timeout: 180000,
274-
windowsHide: true,
275-
...installInvocation.options,
276-
});
271+
// #1942/#1849: stage -> verify -> swap -> rollback instead of installing straight
272+
// into the live tree. A failure at any point leaves either the old or the new tree
273+
// complete — never a file-less skeleton. Falls back to the legacy in-place install
274+
// only when the transactional module cannot run at all.
275+
const packageDir = resolve(here, "..");
276+
console.log(`Updating${latest ? ` to v${latest}` : ""} (transactional)...`);
277+
let res;
278+
try {
279+
const tx = transactionalNpmUpdate({
280+
packageDir,
281+
pkgName: PKG,
282+
targetVersion: latest || undefined,
283+
tag,
284+
runNpm: (args) => {
285+
const invocation = npmInvocation(args);
286+
if (!invocation) return { status: 1 };
287+
return spawnSync(invocation.file, invocation.args, {
288+
stdio: "inherit",
289+
timeout: 180000,
290+
windowsHide: true,
291+
...invocation.options,
292+
});
293+
},
294+
log: (line) => console.log(line),
295+
});
296+
if (tx.ok) {
297+
res = { status: 0 };
298+
} else if (tx.phase === "stage" || tx.phase === "verify") {
299+
// Live tree untouched: report and stop. Nothing to roll back.
300+
console.error(`opencodex: update aborted before touching the live install (${tx.phase}): ${tx.error}`);
301+
res = { status: 1 };
302+
} else {
303+
console.error(`opencodex: update failed (${tx.phase}): ${tx.error}${tx.rolledBack ? " — previous version restored." : ""}`);
304+
res = { status: 1 };
305+
}
306+
} catch (error) {
307+
// An unexpected throw means we cannot prove the live tree is untouched, so the
308+
// legacy in-place install (which deletes live first) is exactly the wrong rescue —
309+
// it recreates the #1849 destruction path. Report and stop; the boot probe and the
310+
// recovery marker cover the swap-window states.
311+
console.error(`opencodex: transactional update failed unexpectedly (${error?.message ?? error}). ` +
312+
"The live install was not knowingly modified; run 'ocx update' again or reinstall with npm install -g.");
313+
res = { status: 1 };
314+
}
277315
if (res.status === 0) {
278316
console.log(`\nUpdated${latest ? ` to v${latest}` : ""}.`);
279317
repairCodexShimIfNeeded();
@@ -449,6 +487,20 @@ if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstal
449487
runNpmSelfUpdate();
450488
}
451489

490+
// #1849 boot probe: a prior update that lost power (or double-faulted) mid-swap leaves a
491+
// backup sibling and a broken live tree. Restore before anything tries to run from the
492+
// broken tree; reap stale backups once the live tree verifies healthy.
493+
if (isNodeModulesInstall() && !isBunGlobalInstall()) {
494+
try {
495+
const probe = bootRestoreProbe(resolve(here, ".."));
496+
if (probe.action === "restored") {
497+
console.warn(`opencodex: previous update left a broken install — restored the backup from ${probe.from}.`);
498+
} else if (probe.action === "failed") {
499+
console.warn(`opencodex: a backup from a failed update exists but could not be restored automatically: ${probe.error}`);
500+
}
501+
} catch { /* the probe must never block launch */ }
502+
}
503+
452504
const bunRuntime = resolveBun();
453505
const bun = bunRuntime.path;
454506

‎src/service.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,6 +1535,9 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15351535
windowsBatchSet("OCX_SERVICE_LOG", serviceLogPath(), "path"),
15361536
windowsBatchSet("OCX_BUN", bun, "path"),
15371537
windowsBatchSet("OCX_CLI", cli, "path"),
1538+
// Package root for the transactional-update restore path (#1942): cli is
1539+
// <pkg>\src\cli\index.ts, so the package dir is three levels up.
1540+
'for %%I in ("%OCX_CLI%\\..\\..\\..") do set "OCX_PKG_DIR=%%~fI"',
15381541
'if exist "%OCX_API_TOKEN_FILE%" (',
15391542
' set /p OPENCODEX_API_AUTH_TOKEN=<"%OCX_API_TOKEN_FILE%"',
15401543
")",
@@ -1547,10 +1550,16 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15471550
'>>"%OCX_SERVICE_LOG%" echo codex_home="%CODEX_HOME%"',
15481551
'>>"%OCX_SERVICE_LOG%" echo token_file="%OCX_API_TOKEN_FILE%"',
15491552
'if not exist "%OCX_BUN%" (',
1553+
" call :restore_backup",
1554+
")",
1555+
'if not exist "%OCX_BUN%" (',
15501556
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] installation is incomplete: bundled Bun is missing; reinstall opencodex, then run ocx service repair',
15511557
" exit /b 3",
15521558
")",
15531559
'if not exist "%OCX_CLI%" (',
1560+
" call :restore_backup",
1561+
")",
1562+
'if not exist "%OCX_CLI%" (',
15541563
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] installation is incomplete: CLI entry is missing; reinstall opencodex, then run ocx service repair',
15551564
" exit /b 3",
15561565
")",
@@ -1563,6 +1572,26 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15631572
" goto loop",
15641573
")",
15651574
"endlocal",
1575+
"goto :eof",
1576+
"",
1577+
// #1942/#1849: a power loss mid-swap leaves the live package dir missing/broken and
1578+
// a sibling .ocx-backup-* holding the previous version. This wrapper lives OUTSIDE
1579+
// the package tree, so it can restore when the launcher itself is gone — the exact
1580+
// window the in-launcher boot probe cannot reach.
1581+
":restore_backup",
1582+
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] install incomplete - looking for a transactional-update backup to restore',
1583+
'for /f "delims=" %%B in (\'dir /b /ad /o-n "%OCX_PKG_DIR%\\..\\.ocx-backup-*" 2^>nul\') do (',
1584+
' if exist "%OCX_PKG_DIR%\\..\\%%B\\opencodex\\package.json" (',
1585+
' if exist "%OCX_PKG_DIR%" rmdir /s /q "%OCX_PKG_DIR%" 2>nul',
1586+
' move "%OCX_PKG_DIR%\\..\\%%B\\opencodex" "%OCX_PKG_DIR%" >nul 2>&1',
1587+
' if exist "%OCX_PKG_DIR%\\package.json" (',
1588+
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] restored previous install from %%B',
1589+
" goto :eof",
1590+
" )",
1591+
" )",
1592+
")",
1593+
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] no restorable backup found',
1594+
"goto :eof",
15661595
].filter((line): line is string => Boolean(line));
15671596
return `${lines.join("\r\n")}\r\n`;
15681597
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
export type InstallTreeVerification = { ok: boolean; failures: string[] };
2+
export function verifyInstallTree(packageDir: string, expectedVersion?: string): InstallTreeVerification;
3+
export function bootRestoreProbe(
4+
packageDir: string,
5+
deps?: { rename?: (from: string, to: string) => void },
6+
): { action: "none" | "reaped" | "restored" | "failed"; count?: number; from?: string; error?: string };
7+
export function transactionalNpmUpdate(args: {
8+
packageDir: string;
9+
pkgName: string;
10+
targetVersion?: string;
11+
tag: string;
12+
runNpm: (args: string[]) => { status: number | null };
13+
log?: (line: string) => void;
14+
deps?: { rename?: (from: string, to: string) => void };
15+
}): {
16+
ok: boolean;
17+
phase: "stage" | "verify" | "swap-backup" | "swap-live" | "post-verify" | "double-fault" | "done";
18+
error?: string;
19+
rolledBack?: boolean;
20+
backup?: string;
21+
};
22+

0 commit comments

Comments
 (0)