interface CheckpointIndex { schemaVersion: 1; active: string; files: string[]; } export interface StoredCheckpoint { bytes: Uint8Array; } async function readFile(directory: FileSystemDirectoryHandle, name: string): Promise { try { const handle = await directory.getFileHandle(name); return new Uint8Array(await (await handle.getFile()).arrayBuffer()); } catch { return null; } } async function writeFile(directory: FileSystemDirectoryHandle, name: string, bytes: Uint8Array): Promise { const handle = await directory.getFileHandle(name, { create: true }); const writable = await handle.createWritable({ keepExistingData: false }); await writable.write(bytes as unknown as FileSystemWriteChunkType); await writable.close(); } /** OPFS-backed current-schema checkpoint store with an atomic index commit. */ export class CheckpointStore { private readonly rootPromise: Promise; private constructor() { this.rootPromise = navigator.storage.getDirectory(); } static async open(): Promise { if (typeof navigator.storage?.getDirectory !== 'function') throw new Error('OPFS is unavailable'); return new CheckpointStore(); } private async directory(): Promise { const root = await this.rootPromise; return root.getDirectoryHandle('botpsy-checkpoints', { create: true }); } async load(modelHash: string): Promise { const directory = await this.directory(); const rawIndex = await readFile(directory, `${modelHash}.index.json`); if (!rawIndex) return null; try { const index = JSON.parse(new TextDecoder().decode(rawIndex)) as CheckpointIndex; if (index.schemaVersion !== 1 || typeof index.active !== 'string') return null; const bytes = await readFile(directory, index.active); if (!bytes) return null; return { bytes }; } catch { return null; } } async save(modelHash: string, bytes: Uint8Array): Promise { const directory = await this.directory(); const name = `${modelHash}-${Date.now()}.ckpt`; await writeFile(directory, name, bytes); const previous = await readFile(directory, `${modelHash}.index.json`); const index: CheckpointIndex = { schemaVersion: 1, active: name, files: [name], }; if (previous) { try { const old = JSON.parse(new TextDecoder().decode(previous)) as CheckpointIndex; for (const file of old.files) { if (file !== name) { await directory.removeEntry(file).catch(() => undefined); } } } catch { // A corrupt previous index is superseded by this commit. } } await writeFile(directory, `${modelHash}.index.json`, new TextEncoder().encode(JSON.stringify(index))); } async clear(modelHash: string): Promise { const directory = await this.directory(); const rawIndex = await readFile(directory, `${modelHash}.index.json`); if (rawIndex) { try { const index = JSON.parse(new TextDecoder().decode(rawIndex)) as CheckpointIndex; for (const file of index.files) await directory.removeEntry(file).catch(() => undefined); } catch { // Ignore malformed indexes while deleting. } } await directory.removeEntry(`${modelHash}.index.json`).catch(() => undefined); } }