The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): write page ledgers as versioned files instead of renaming over them
Zhuowei Wangdee2c98bb418
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjsindex bba8f97..4bb2ced 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-delayed-popup.mjs@@ -2,8 +2,7 @@ export function pageDelayedPopupScheduleCase() {return `const task = await taskSpace(taskName);const source = await newPageAt(task, baseUrl + "/?delayed-popup=schedule");- const ledgerPath = await pageLedgerPath(task.spaceId);- const beforeLedger = JSON.parse(await readFile(ledgerPath, "utf8"));+ const beforeLedger = await readPageLedger(task.spaceId);await writeFile(join(tempDir, "delayed-popup-state.json"),JSON.stringify({@@ -40,12 +39,7 @@ export function pageDelayedPopupResumeCase() {const source = task.page(saved.sourceLabel);await source.waitForTimeout(1_000);const beforeTargets = new Set(saved.beforeTargets);- const ledger = JSON.parse(- await readFile(- await pageLedgerPath(task.spaceId),- "utf8"- )- );+ const ledger = await readPageLedger(task.spaceId);const delayedPopup = Object.entries(ledger.pages).find(([, entry]) => !beforeTargets.has(entry.targetId));diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjsindex bb2f2cc..aca0c3e 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs@@ -351,8 +351,7 @@ export function pageLoadStatesCase() {});document.body.append(button);}, baseUrl + "/secondary?page-load-states=delayed-popup");- const ledgerPath = await pageLedgerPath(task.spaceId);- const beforeLedger = JSON.parse(await readFile(ledgerPath, "utf8"));+ const beforeLedger = await readPageLedger(task.spaceId);const beforeTargets = new Set(Object.values(beforeLedger.pages).map((entry) => entry.targetId));@@ -363,7 +362,7 @@ export function pageLoadStatesCase() {"the popup is created after the action receipt window");await page.waitForTimeout(1_000);- const afterLedger = JSON.parse(await readFile(ledgerPath, "utf8"));+ const afterLedger = await readPageLedger(task.spaceId);const delayedPopup = Object.entries(afterLedger.pages).find(([, entry]) => !beforeTargets.has(entry.targetId));diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjsindex df320a1..bb6f751 100644--- a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs@@ -32,16 +32,43 @@ export function egoSource(body, context) {process.env.EGO_BROWSER_STATE_DIR = join(tempDir, "runtime-state");process.env.EGO_BROWSER_PAGE_BUDGET = "3";- // Ledger files are scoped by browser instance; this isolated state- // directory belongs to the one Ego Lite instance under test.- async function pageLedgerPath(spaceId) {+ // Ledger files are scoped by browser instance (this isolated state+ // directory belongs to the one Ego Lite instance under test) and+ // versioned: every SDK write creates space-<id>@<instance>.<n>.json and+ // removes the versions before it. The current ledger is the highest+ // version that parses, and a path listed a moment ago may already be+ // gone, so read through readPageLedger instead of holding on to a path.+ async function pageLedgerVersions(spaceId) {const stateDir = process.env.EGO_BROWSER_STATE_DIR;const prefix = "space-" + spaceId + "@";- const names = (await readdir(stateDir)).filter(- (name) => name.startsWith(prefix) && name.endsWith(".json")- );- assertEqual(names.length, 1, "one page ledger exists for space " + spaceId);- return join(stateDir, names[0]);+ const names = await readdir(stateDir).catch(() => []);+ return names+ .filter((name) => name.startsWith(prefix) && name.endsWith(".json"))+ .map((name) => ({+ name,+ seq: Number(/\\.(\\d+)\\.json$/.exec(name)?.[1] ?? 0),+ }))+ .sort((a, b) => b.seq - a.seq)+ .map((entry) => join(stateDir, entry.name));+ }++ async function pageLedgerPath(spaceId) {+ const [latest] = await pageLedgerVersions(spaceId);+ assert(Boolean(latest), "a page ledger exists for space " + spaceId);+ return latest;+ }++ async function readPageLedger(spaceId) {+ for (let attempt = 0; attempt < 5; attempt++) {+ for (const path of await pageLedgerVersions(spaceId)) {+ try {+ return JSON.parse(await readFile(path, "utf8"));+ } catch {+ // Superseded between listing and reading, or still being written.+ }+ }+ }+ throw new Error("no readable page ledger for space " + spaceId);}let __assertionCount = 0;@@ -283,16 +310,10 @@ export function egoSource(body, context) {};async function ledgerTargetIds(spaceId) {- const stateDir = process.env.EGO_BROWSER_STATE_DIR;- const prefix = "space-" + spaceId + "@";- const names = await readdir(stateDir).catch(() => []);- const targetIds = new Set();- for (const name of names) {- if (!name.startsWith(prefix) || !name.endsWith(".json")) continue;- const ledger = JSON.parse(await readFile(join(stateDir, name), "utf8"));- for (const page of Object.values(ledger.pages || {})) targetIds.add(page.targetId);- }- return targetIds;+ const ledger = await readPageLedger(spaceId).catch(() => ({}));+ return new Set(+ Object.values(ledger.pages || {}).map((page) => page.targetId)+ );}async function closePagesOpenedByCase() {diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjsindex 22799d6..d218b79 100644--- a/package/ego-browser/src/page-ledger.test.mjs+++ b/package/ego-browser/src/page-ledger.test.mjs@@ -11,11 +11,7 @@ import {import { tmpdir } from "node:os";import { join } from "node:path";-import {- PageLedgerStore,- renameWithRetry,- runtimeInstanceId,-} from "../dist/src/page-ledger.js";+import { PageLedgerStore, runtimeInstanceId } from "../dist/src/page-ledger.js";test("runtimeInstanceId is a pure browser-host identifier", () => {const first = runtimeInstanceId(42);@@ -34,6 +30,25 @@ async function withTempLedger(fn) {}}+/** Parse the highest-numbered version of one ledger, e.g. base "space-5@browser-a". */+async function readLatest(rootDir, base) {+ const versions = (await readdir(rootDir))+ .map((name) => ({+ name,+ seq: Number(new RegExp(`^${base}\\.(\\d+)\\.json$`).exec(name)?.[1]),+ }))+ .filter((file) => Number.isInteger(file.seq))+ .sort((a, b) => b.seq - a.seq);+ assert.ok(versions.length > 0, `no ledger version for ${base}`);+ return JSON.parse(await readFile(join(rootDir, versions[0].name), "utf8"));+}++function sharingViolation(code, syscall) {+ const error = new Error(`${code}: operation not permitted, ${syscall}`);+ error.code = code;+ return error;+}+test("page labels survive a new process and are never reused", async () => {await withTempLedger(async (rootDir) => {const firstRound = new PageLedgerStore({ rootDir });@@ -156,9 +171,7 @@ test("a reused space id starts conservatively in a new browser instance", asyncassert.deepEqual(baseline.pages, {});assert.equal(baseline.unmanagedTargets["target-existing"], "unknown");- const persisted = JSON.parse(- await readFile(join(rootDir, "[email protected]"), "utf8"),- );+ const persisted = await readLatest(rootDir, "space-7@browser-b");assert.equal(persisted.browserInstanceId, "browser-b");});});@@ -187,7 +200,7 @@ test("concurrent browser instances keep separate ledgers for the same space id",await browserB.discard(1);assert.deepEqual(await browserA.getPage(1, "p1"), pageA);assert.deepEqual((await readdir(rootDir)).sort(), [- "[email protected]",+ "[email protected]",]);});});@@ -228,9 +241,7 @@ test("a shared-name ledger from this browser instance moves to its own file", ascode: "ENOENT",});assert.equal(- JSON.parse(- await readFile(join(rootDir, "[email protected]"), "utf8"),- ).pages.p1.targetId,+ (await readLatest(rootDir, "space-7@browser-host-101")).pages.p1.targetId,"target-live",);});@@ -265,9 +276,7 @@ test("a ledger from before instance ids is preserved and backfilled", async () =openedBy: "agent",});assert.equal(- JSON.parse(- await readFile(join(rootDir, "[email protected]"), "utf8"),- ).browserInstanceId,+ (await readLatest(rootDir, "space-7@browser-current")).browserInstanceId,"browser-current",);await assert.rejects(() => readFile(path, "utf8"), { code: "ENOENT" });@@ -292,6 +301,12 @@ test("expired ledgers from other browser instances are removed", async () => {}),);await utimes(stalePath, new Date(0), new Date(0));+ const staleVersionPath = join(rootDir, "[email protected]");+ await writeFile(+ staleVersionPath,+ JSON.stringify({ browserInstanceId: "browser-a", spaceId: 98 }),+ );+ await utimes(staleVersionPath, new Date(0), new Date(0));const secondBrowser = new PageLedgerStore({rootDir,@@ -304,6 +319,9 @@ test("expired ledgers from other browser instances are removed", async () => {await assert.rejects(() => readFile(stalePath, "utf8"), {code: "ENOENT",});+ await assert.rejects(() => readFile(staleVersionPath, "utf8"), {+ code: "ENOENT",+ });});});@@ -321,14 +339,12 @@ test("custom labels share the permanent used-label namespace", async () => {});});-test("writes use a complete atomic ledger document", async () => {+test("writes use a complete ledger document", async () => {await withTempLedger(async (rootDir) => {const store = new PageLedgerStore({ rootDir });await store.addPage(5, "target-a");- const parsed = JSON.parse(- await readFile(join(rootDir, "space-5.json"), "utf8"),- );+ const parsed = await readLatest(rootDir, "space-5");assert.deepEqual(parsed, {spaceId: 5,nextLabel: 2,@@ -347,130 +363,110 @@ test("writes use a complete atomic ledger document", async () => {});});-function sharingViolation(code = "EPERM") {- const error = new Error(`${code}: operation not permitted, rename`);- error.code = code;- return error;-}--test("renameWithRetry retries transient Windows sharing violations with backoff", async () => {- const calls = [];- const delays = [];- let failures = 3;- await renameWithRetry("from", "to", {- rename: async (from, to) => {- calls.push([from, to]);- if (failures-- > 0)- throw sharingViolation(["EPERM", "EACCES", "EBUSY"][failures]);- },- sleep: async (ms) => {- delays.push(ms);- },- });-- assert.equal(calls.length, 4);- assert.deepEqual(calls[0], ["from", "to"]);- assert.deepEqual(delays, [20, 40, 80]);-});--test("renameWithRetry does not retry non-transient errors", async () => {- let calls = 0;- await assert.rejects(- renameWithRetry("from", "to", {- rename: async () => {- calls += 1;- throw sharingViolation("ENOENT");- },- sleep: async () => {- assert.fail("must not sleep");- },- }),- { code: "ENOENT" },- );- assert.equal(calls, 1);-});--test("renameWithRetry gives up after the attempt budget", async () => {- let calls = 0;- const delays = [];- await assert.rejects(- renameWithRetry("from", "to", {- rename: async () => {- calls += 1;- throw sharingViolation();- },- sleep: async (ms) => {- delays.push(ms);- },- attempts: 4,- }),- { code: "EPERM" },- );- assert.equal(calls, 5);- assert.deepEqual(delays, [20, 40, 80, 160]);-});+test("each write creates a new version and removes the superseded ones", async () => {+ await withTempLedger(async (rootDir) => {+ const store = new PageLedgerStore({ rootDir });+ await store.addPage(5, "target-a");+ assert.deepEqual(await readdir(rootDir), ["space-5.1.json"]);-test("renameWithRetry caps the delay between attempts", async () => {- let failures = 6;- const delays = [];- await renameWithRetry("from", "to", {- rename: async () => {- if (failures-- > 0) throw sharingViolation();- },- sleep: async (ms) => {- delays.push(ms);- },+ await store.addPage(5, "target-b");+ assert.deepEqual(await readdir(rootDir), ["space-5.2.json"]);+ assert.deepEqual(+ Object.keys((await readLatest(rootDir, "space-5")).pages),+ ["p1", "p2"],+ );});- assert.deepEqual(delays, [20, 40, 80, 160, 250, 250]);});-test("a ledger write survives a transient EPERM on the final rename", async () => {+test("a superseded version held open by another process is left behind and ignored", async () => {await withTempLedger(async (rootDir) => {- const { rename } = await import("node:fs/promises");- let failures = 2;- let renames = 0;+ // Windows refuses to delete (or rename over) a file that another process+ // holds without delete sharing. Only the removal is affected: the next+ // version is still created, and readers pick it up.+ let held;const store = new PageLedgerStore({rootDir,- rename: {- rename: async (from, to) => {- renames += 1;- if (failures-- > 0) throw sharingViolation();- await rename(from, to);- },- sleep: async () => {},+ remove: async (path) => {+ if (path === held) throw sharingViolation("EBUSY", "unlink");+ await rm(path, { force: true });},});await store.addPage(5, "target-a");+ held = join(rootDir, "space-5.1.json");+const page = await store.addPage(5, "target-b");assert.equal(page.label, "p2");- // Two writes: the first needed three attempts, the second one.- assert.equal(renames, 4);- const parsed = JSON.parse(- await readFile(join(rootDir, "space-5.json"), "utf8"),+ assert.deepEqual((await readdir(rootDir)).sort(), [+ "space-5.1.json",+ "space-5.2.json",+ ]);+ const nextRound = new PageLedgerStore({ rootDir });+ assert.deepEqual(Object.keys((await nextRound.read(5)).pages), [+ "p1",+ "p2",+ ]);++ held = undefined;+ await store.addPage(5, "target-c");+ assert.deepEqual(await readdir(rootDir), ["space-5.3.json"]);+ });+});++test("a version that is unreadable or still being written falls back to the previous one", async () => {+ await withTempLedger(async (rootDir) => {+ const store = new PageLedgerStore({ rootDir });+ await store.addPage(5, "target-a");+ await writeFile(+ join(rootDir, "space-5.2.json"),+ '{"spaceId": 5, "nextLabel": 3, "usedLabels": ["p1", "p2"], "pages": {',);- assert.deepEqual(Object.keys(parsed.pages), ["p1", "p2"]);++ assert.deepEqual(Object.keys((await store.read(5)).pages), ["p1"]);++ const page = await store.addPage(5, "target-b");+ assert.equal(page.label, "p2");+ assert.deepEqual(await readdir(rootDir), ["space-5.3.json"]);+ });+});++test("concurrent writers never lose each other's update", async () => {+ await withTempLedger(async (rootDir) => {+ const roundA = new PageLedgerStore({ rootDir });+ const roundB = new PageLedgerStore({ rootDir });+ await roundA.addPage(5, "target-seed");++ const [pageA, pageB] = await Promise.all([+ roundA.addPage(5, "target-a"),+ roundB.addPage(5, "target-b"),+ ]);++ assert.notEqual(pageA.label, pageB.label);+ const ledger = await roundA.read(5);assert.deepEqual(- (await readdir(rootDir)).filter((name) => name.endsWith(".tmp")),- [],+ Object.values(ledger.pages)+ .map((page) => page.targetId)+ .sort(),+ ["target-a", "target-b", "target-seed"],);+ assert.deepEqual(ledger.usedLabels, ["p1", "p2", "p3"]);+ assert.deepEqual(await readdir(rootDir), ["space-5.3.json"]);});});-test("a persistent EPERM on the final rename still surfaces and leaves no temporary file", async () => {+test("discard tolerates a version that cannot be removed yet", async () => {await withTempLedger(async (rootDir) => {const store = new PageLedgerStore({rootDir,- rename: {- rename: async () => {- throw sharingViolation();- },- sleep: async () => {},- attempts: 2,+ remove: async () => {+ throw sharingViolation("EPERM", "unlink");},});- await assert.rejects(store.addPage(5, "target-a"), { code: "EPERM" });- assert.deepEqual(await readdir(rootDir), []);+ await store.addPage(5, "target-a");++ await store.discard(5);++ assert.deepEqual(await readdir(rootDir), ["space-5.1.json"]);});});@@ -508,7 +504,8 @@ test("old ledger metadata is accepted and removed on the next write", async () =});await store.addPage(12, "target-new");- const persisted = JSON.parse(await readFile(path, "utf8"));+ await assert.rejects(() => readFile(path, "utf8"), { code: "ENOENT" });+ const persisted = await readLatest(rootDir, "space-12");assert.equal(Object.hasOwn(persisted, "version"), false);assert.equal(Object.hasOwn(persisted, "writerRound"), false);assert.equal(Object.hasOwn(persisted, "touchedAt"), false);@@ -543,7 +540,7 @@ test("old handoff baselines migrate to a pending user-control boundary", async (await store.reconcile(13, ["target-agent", "target-user"], {autoAdoptNew: true,});- const persisted = JSON.parse(await readFile(path, "utf8"));+ const persisted = await readLatest(rootDir, "space-13");assert.equal(persisted.userControlPending, false);assert.equal(Object.hasOwn(persisted, "handoffBaseline"), false);assert.equal(persisted.unmanagedTargets["target-user"], "unknown");diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.tsindex 3a5ab36..7db1e65 100644--- a/package/ego-browser/src/page-ledger.ts+++ b/package/ego-browser/src/page-ledger.ts@@ -1,15 +1,12 @@-import { randomUUID } from "node:crypto";import {mkdir,readFile,readdir,- rename,rm,stat,writeFile,} from "node:fs/promises";import { join } from "node:path";-import { setTimeout as sleep } from "node:timers/promises";import { runtimeStateDir } from "./env.js";import {validatePageRefState,@@ -45,56 +42,25 @@ type PageLedgerStoreOptions = {browserInstanceId?: string | (() => string | Promise<string>);staleAfterMs?: number;now?: () => number;- /** Test seam for the final rename of an atomic ledger write. */- rename?: RenameWithRetryOptions;+ /** Test seam for removing superseded ledger versions. */+ remove?: (path: string) => Promise<void>;};const DEFAULT_STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;+const MAX_WRITE_CONFLICTS = 8;+const LEDGER_FILE_PATTERN = /^space-\d+(@[A-Za-z0-9_-]+)?(\.\d+)?\.json$/;/**- * Windows reports a sharing violation as EPERM/EACCES/EBUSY when a rename- * replaces a file that another handle (an antivirus scan, the search indexer,- * a concurrent reader) still holds open. The condition clears within- * milliseconds, so the replacement is retried briefly instead of aborting- * the caller's script.+ * Codes under which a ledger version cannot be opened right now. Windows+ * reports a file that another process holds without delete sharing, or that+ * is pending deletion, as EPERM/EACCES/EBUSY rather than ENOENT.*/-const RETRYABLE_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);-const RENAME_RETRY_ATTEMPTS = 10;-const RENAME_RETRY_BASE_MS = 20;-const RENAME_RETRY_MAX_MS = 250;--type RenameWithRetryOptions = {- rename?: (from: string, to: string) => Promise<void>;- sleep?: (ms: number) => Promise<unknown>;- attempts?: number;-};+const UNREADABLE_CODES = new Set(["ENOENT", "EPERM", "EACCES", "EBUSY"]);-/** Rename over an existing file, retrying transient sharing violations. */-export async function renameWithRetry(- from: string,- to: string,- options: RenameWithRetryOptions = {},-): Promise<void> {- const doRename = options.rename || rename;- const wait = options.sleep || sleep;- const attempts = options.attempts ?? RENAME_RETRY_ATTEMPTS;- for (let attempt = 0; ; attempt++) {- try {- await doRename(from, to);- return;- } catch (error) {- if (- !RETRYABLE_RENAME_CODES.has((error as { code?: string })?.code ?? "") ||- attempt >= attempts- ) {- throw error;- }- await wait(- Math.min(RENAME_RETRY_BASE_MS * 2 ** attempt, RENAME_RETRY_MAX_MS),- );- }- }-}+/** A version with the next sequence number appeared between load and write. */+class LedgerWriteConflict extends Error {}++type LedgerFile = { seq: number; path: string };/** Stable across Agent rounds and Node-service restarts in one Ego Lite run. */export function runtimeInstanceId(parentPid = process.ppid): string {@@ -114,18 +80,24 @@ type ReconcileOptions = {/*** Stores durable page labels in one JSON document per task space and browser* instance. Space ids restart at 1 in every Ego Lite instance, so concurrent- * instances sharing the state directory must not share a file. Each update- * replaces the complete document with an atomic rename so readers never see a- * partially written ledger.+ * instances sharing the state directory must not share a file.+ *+ * Every write creates a new numbered version (`space-<id>@<instance>.<n>.json`)+ * and the highest version that parses is the current ledger. No file is ever+ * renamed over or truncated in place: on Windows, replacing a file that+ * another process (an antivirus scan, the search indexer, a concurrent+ * reader) holds open fails with EPERM for as long as that handle stays open,+ * which used to abort the caller's script. Superseded versions are removed+ * best-effort after each write, so one that is still held open is simply+ * left for a later write. Readers skip a version they cannot open or parse+ * yet, so a write in progress is invisible until it is complete.*/export class PageLedgerStore {readonly rootDir: string;- readonly #writeToken = randomUUID();readonly #browserInstanceId?: string | (() => string | Promise<string>);readonly #staleAfterMs: number;readonly #now: () => number;- readonly #renameOptions: RenameWithRetryOptions;- #temporarySequence = 0;+ readonly #remove: (path: string) => Promise<void>;#resolvedBrowserInstanceId?: Promise<string | undefined>;#cleanup?: Promise<void>;@@ -137,7 +109,7 @@ export class PageLedgerStore {? DEFAULT_STALE_AFTER_MS: options.staleAfterMs;this.#now = options.now || Date.now;- this.#renameOptions = options.rename || {};+ this.#remove = options.remove || ((path) => rm(path, { force: true }));if (!Number.isFinite(this.#staleAfterMs) || this.#staleAfterMs < 0) {throw new TypeError("staleAfterMs must be a non-negative number");}@@ -164,15 +136,19 @@ export class PageLedgerStore {ledger.initialized = true;ledger.usedLabels.push(label);ledger.pages[label] = entry;- await this.#writeAtomic(spaceId, ledger);+ await this.#writeLatest(spaceId, ledger);return { label, ...entry };}- /** Remove all Page-model state after its task space is finished or closed. */+ /**+ * Remove all Page-model state after its task space is finished or closed.+ * A version that another process still holds open stays behind; it is+ * expired like any other stale ledger.+ */async discard(spaceId: number): Promise<void> {assertSpaceId(spaceId);const browserInstanceId = await this.#currentBrowserInstanceId();- await rm(this.#path(spaceId, browserInstanceId), { force: true });+ await this.#removeAll(await this.#listVersions(spaceId, browserInstanceId));}async getPage(spaceId: number, label: string): Promise<ManagedPage> {@@ -405,39 +381,153 @@ export class PageLedgerStore {mutate: (ledger: PageLedger) => void,): Promise<PageLedger> {assertSpaceId(spaceId);- const next = await this.#readCurrent(spaceId);- mutate(next);- await this.#writeAtomic(spaceId, next);- return cloneLedger(next);+ for (let conflicts = 0; ; conflicts++) {+ const { ledger, files } = await this.#load(spaceId);+ mutate(ledger);+ try {+ await this.#write(spaceId, ledger, files);+ return cloneLedger(ledger);+ } catch (error) {+ if (+ !(error instanceof LedgerWriteConflict) ||+ conflicts >= MAX_WRITE_CONFLICTS+ ) {+ throw error;+ }+ }+ }}async #readCurrent(spaceId: number): Promise<PageLedger> {+ return (await this.#load(spaceId)).ledger;+ }++ /** The current ledger plus every version file it was chosen from. */+ async #load(+ spaceId: number,+ ): Promise<{ ledger: PageLedger; files: LedgerFile[] }> {const browserInstanceId = await this.#currentBrowserInstanceId();await this.#cleanupExpiredLedgers(browserInstanceId);- const path = this.#path(spaceId, browserInstanceId);- const stored = await readLedgerJson(path);- if (stored !== undefined) {- return (- ownedLedger(stored, spaceId, path, browserInstanceId) ||- emptyLedger(spaceId, browserInstanceId)- );+ const files = await this.#listVersions(spaceId, browserInstanceId);+ for (const file of files) {+ const stored = await readLedgerJson(file.path);+ if (stored === undefined) continue;+ return {+ ledger:+ ownedLedger(stored, spaceId, file.path, browserInstanceId) ||+ emptyLedger(spaceId, browserInstanceId),+ files,+ };+ }+ if (browserInstanceId === undefined || files.length > 0) {+ return { ledger: emptyLedger(spaceId, browserInstanceId), files };}- if (browserInstanceId === undefined) return emptyLedger(spaceId);// Earlier SDKs wrote every instance's ledger to the shared space file.// Move this instance's ledger (or one from before instance ids existed)// so an SDK upgrade does not discard live Page labels.- const legacyPath = this.#path(spaceId);+ const legacyPath = this.#legacyPath(spaceId);const legacy = await readLedgerJson(legacyPath);const ledger =legacy === undefined? undefined: ownedLedger(legacy, spaceId, legacyPath, browserInstanceId);- if (!ledger) return emptyLedger(spaceId, browserInstanceId);+ if (!ledger) {+ return { ledger: emptyLedger(spaceId, browserInstanceId), files };+ }ledger.browserInstanceId = browserInstanceId;- await this.#writeAtomic(spaceId, ledger);- await rm(legacyPath, { force: true });- return ledger;+ const written = await this.#writeLatest(spaceId, ledger);+ await this.#remove(legacyPath).catch(() => {});+ return { ledger, files: written };+ }++ /** Write `ledger` as the next version, whatever versions exist right now. */+ async #writeLatest(+ spaceId: number,+ ledger: PageLedger,+ ): Promise<LedgerFile[]> {+ const browserInstanceId = await this.#currentBrowserInstanceId();+ for (let conflicts = 0; ; conflicts++) {+ const files = await this.#listVersions(spaceId, browserInstanceId);+ try {+ return await this.#write(spaceId, ledger, files);+ } catch (error) {+ if (+ !(error instanceof LedgerWriteConflict) ||+ conflicts >= MAX_WRITE_CONFLICTS+ ) {+ throw error;+ }+ }+ }+ }++ /**+ * Create the version after `files` (the listing the ledger was loaded+ * from), then remove those superseded versions. Another writer that got+ * there first raises LedgerWriteConflict so the caller reloads instead of+ * overwriting its update.+ */+ async #write(+ spaceId: number,+ ledger: PageLedger,+ files: LedgerFile[],+ ): Promise<LedgerFile[]> {+ await mkdir(this.rootDir, { recursive: true, mode: 0o700 });+ const seq = (files[0]?.seq ?? 0) + 1;+ const path = `${this.#base(spaceId, await this.#currentBrowserInstanceId())}.${seq}.json`;+ try {+ await writeFile(path, `${JSON.stringify(ledger, null, 2)}\n`, {+ encoding: "utf8",+ flag: "wx",+ mode: 0o600,+ });+ } catch (error) {+ if ((error as { code?: string })?.code === "EEXIST") {+ throw new LedgerWriteConflict(+ `page ledger ${path} was written concurrently`,+ );+ }+ throw error;+ }+ await this.#removeAll(files);+ return [{ seq, path }];+ }++ /** Best-effort removal: a version held open elsewhere is left behind. */+ async #removeAll(files: LedgerFile[]): Promise<void> {+ await Promise.all(+ files.map((file) => this.#remove(file.path).catch(() => {})),+ );+ }++ /** Every version of one space's ledger, newest first; the unnumbered legacy file is version 0. */+ async #listVersions(+ spaceId: number,+ browserInstanceId: string | undefined,+ ): Promise<LedgerFile[]> {+ let names: string[];+ try {+ names = await readdir(this.rootDir);+ } catch (error) {+ if (error?.code === "ENOENT") return [];+ throw error;+ }+ // The base holds only digits and a sanitized [A-Za-z0-9_-] scope.+ const base = `space-${spaceId}${scopeSuffix(browserInstanceId)}`;+ const pattern = new RegExp(`^${base}(?:\\.(\\d+))?\\.json$`);+ return names+ .flatMap((name) => {+ const match = pattern.exec(name);+ if (!match) return [];+ return [+ {+ seq: match[1] ? Number(match[1]) : 0,+ path: join(this.rootDir, name),+ },+ ];+ })+ .sort((a, b) => b.seq - a.seq);}async #currentBrowserInstanceId(): Promise<string | undefined> {@@ -473,7 +563,7 @@ export class PageLedgerStore {}await Promise.all(names- .filter((name) => /^space-\d+(@[A-Za-z0-9_-]+)?\.json$/.test(name))+ .filter((name) => LEDGER_FILE_PATTERN.test(name)).map(async (name) => {const path = join(this.rootDir, name);const metadata = await stat(path).catch(() => undefined);@@ -498,42 +588,43 @@ export class PageLedgerStore {);}- async #writeAtomic(spaceId: number, ledger: PageLedger): Promise<void> {- await mkdir(this.rootDir, { recursive: true, mode: 0o700 });- const path = this.#path(spaceId, await this.#currentBrowserInstanceId());- const temporary = `${path}.${process.pid}.${this.#writeToken}.${++this.#temporarySequence}.tmp`;- try {- await writeFile(temporary, `${JSON.stringify(ledger, null, 2)}\n`, {- encoding: "utf8",- mode: 0o600,- });- await renameWithRetry(temporary, path, this.#renameOptions);- } finally {- await rm(temporary, { force: true }).catch(() => {});- }+ #base(spaceId: number, browserInstanceId?: string): string {+ return join(+ this.rootDir,+ `space-${spaceId}${scopeSuffix(browserInstanceId)}`,+ );}- #path(spaceId: number, browserInstanceId?: string): string {- const scope =- browserInstanceId === undefined- ? ""- : `@${browserInstanceId.replace(/[^A-Za-z0-9_-]/g, "-")}`;- return join(this.rootDir, `space-${spaceId}${scope}.json`);+ /** The shared, unnumbered file that SDKs before instance ids wrote. */+ #legacyPath(spaceId: number): string {+ return `${this.#base(spaceId)}.json`;}}+function scopeSuffix(browserInstanceId: string | undefined): string {+ return browserInstanceId === undefined+ ? ""+ : `@${browserInstanceId.replace(/[^A-Za-z0-9_-]/g, "-")}`;+}++/**+ * Read one ledger document. Returns undefined when the file is missing, cannot+ * be opened right now, or does not parse: a version another process is still+ * writing, or one left truncated by a crash, must not shadow the version+ * before it.+ */async function readLedgerJson(path: string): Promise<unknown> {let raw: string;try {raw = await readFile(path, "utf8");} catch (error) {- if (error?.code === "ENOENT") return undefined;+ if (UNREADABLE_CODES.has(error?.code)) return undefined;throw error;}try {return JSON.parse(raw);- } catch (error) {- throw new Error(`invalid page ledger ${path}: ${error.message}`);+ } catch {+ return undefined;}}