From a32761880f9f155e35d3d2b350f6e23dcf1d12cd Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Tue, 18 Aug 2026 05:45:45 +0300 Subject: [PATCH] fix(sqlite): survive a read-only database parent instead of reporting no sessions `openDatabase` opens provider databases with `readOnly: true`, which is not enough for a WAL-mode database: SQLite has to create `-shm` and an empty `-wal` in the database's own directory unless they already exist. Two things follow, and both are real. The open writes. On a writable directory it succeeds and leaves two files behind in the user's provider directory, which is not what "CodeBurn only reads your session logs" implies. On a non-writable parent it fails outright with "attempt to write a readonly database". It is conditional on -shm being absent, which is exactly the state after the tool exits cleanly, so the symptom is intermittent: a provider's spend disappears whenever that tool is not running. Both discovery sites swallowed it with a bare `catch { continue }`, so the provider reported zero sessions with nothing on stderr - indistinguishable from the tool not being installed. It covers cursor, cursor-agent, opencode, goose, warp, kilo-code, zerostack and the copilot agent-traces DB. The direct open stays the fast path and is unchanged when it succeeds: no stat, no permission probe. Only when SQLite reports SQLITE_READONLY does the fallback run, copying the database and its -wal/-shm siblings into the CodeBurn cache directory and opening the copy there. The copy is fingerprinted the same way session-cache fingerprints a SQLite source, so an unchanged database is not copied twice, and there is one bounded entry per source path. The discovery sites now tell SQLITE_READONLY apart from ENOENT and emit one notice per source path rather than per session, matching what the parse-time paths already do. This is not specific to any one sandbox: it applies to a database on read-only media, a restrictive-permissions setup, and both the Flatpak and snap confinements. The snap was narrowed to a read-only personal-files plug in #978 and is likely affected; I have no snap install to confirm that on. --- CHANGELOG.md | 1 + src/providers/cursor.ts | 14 +- src/providers/sqlite-session-parser.ts | 14 +- src/sqlite.ts | 239 ++++++++++++++++++++++++- tests/sqlite-readonly-parent.test.ts | 207 +++++++++++++++++++++ 5 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 tests/sqlite-readonly-parent.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9242c070..1c6cdd65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Changed +- **SQLite providers now survive read-only database parents.** CodeBurn keeps the existing read-only open as the fast path, then fingerprints and caches the database plus `-wal`/`-shm` siblings only when SQLite reports that the source directory cannot create its sidecars. The cache has one bounded entry per source path and reuses it while the main-plus-WAL fingerprint is unchanged; the original provider database is never opened writable or modified. Read-only discovery failures are identified separately from missing databases and produce one rate-limited stderr notice. - **Codex rollouts parse across worker threads too, and the workload gate now takes bytes or files.** Codex is the bigger half of a real cold parse — a 4 GB rollout corpus against 1.8 GB of Claude sessions — and it was still decoding one file at a time. A whole-file rollout decode now runs on the same pool, against an empty dedup set, and comes back with the calls, the dedup keys it claimed, and the codex-cache entry it would have written; the parent installs all three in the serial loop's order, so `codex-results.json` and every payload come out byte-identical to a serial run. Cross-file state stays where it was: a forked rollout replaying its parent's token_count history collides on the parent's keys and is re-parsed in-process, and no worker ever touches the cache module's per-directory state. Files the Codex cache can serve exactly or resume into from a byte offset never reach a worker — they read a few KB and the resume state belongs to the parent. The workload gate is now pending BYTES alone (200 MB), not file count: 250 pending files holding under a megabyte between them spawned threads that made the run ~5% slower, while a few hundred huge rollouts were being turned away. The count takes `max(pendingFiles / 50, pendingBytes / 200 MB)`, and the per-thread memory budget is derived per parse as `clamp(256 MB, 2 × average pending file + 128 MB, 1 GB)` rather than a flat 256 MB — a 260 MB rollout peaks near 430 MB in its worker and scales linearly with the pool, so the flat figure over-subscribed exactly the workload this adds. The decision is per provider, and at most one pool is alive at a time. - **A large cold Claude parse now runs across worker threads.** Reading, decoding and line-parsing a session JSONL is per-file work that never touches anything shared, so it moves onto `worker_threads`; each worker ships its parsed turns back as a JSON string and the parent installs them in the exact order the serial loop would. Everything with cross-file state — the streaming-message dedup, canonical project paths, spawn links, PR correlation, progress saves — stays on the main thread, and a file whose message ids were already claimed by an earlier file (or whose worker failed) is simply re-parsed in-process, so the session cache and every payload are identical either way. On a 6 GB corpus a cold `status` drops from 27.5s to 14.8s with peak RSS up 2.27 GB → 2.52 GB. Threads only engage for a genuinely large cold parse: never with under 200 MB behind the pending whole-file re-parses, 2 or fewer cores, or under 4 GB of available memory — so warm and incremental runs are untouched and spawn nothing. Otherwise the count is `min(cores - 1, min(0.25 × available, 2 GB) / 256 MB, pendingFiles / 50)`, where available is `process.availableMemory()` (cgroup-aware in containers) rather than free memory, which on macOS reports free pages and would switch the feature on and off between runs. `CODEBURN_PARSE_WORKERS=0` forces the serial parse and `CODEBURN_PARSE_WORKERS=N` forces N (capped at the core count), both bypassing every gate; `CODEBURN_VERBOSE=1` prints the resolved count and why. - **A warm launch rewrites only the month that changed, and a ranged query reads only the months it can report on.** Per-provider shards still meant one appended session republished that provider's entire history — 95 MB for Claude on a 6 GB corpus. Each provider's shard is now split again by the UTC month of the cached session's FIRST turn, a bucket that never moves as a session grows, so an append rewrites one month. Every shard records the newest month it holds, which lets `--period today/week` skip the shards that cannot contribute a turn to the range; the skipped months stay on disk untouched across the save, and providers whose cache is the only surviving record (durable) or whose parse fingerprint moved are always read in full. Remaining shards are read concurrently. Existing v8 and v7 caches are re-laid-out losslessly on first load and the old layout removed once the new one is published: nothing re-parses. diff --git a/src/providers/cursor.ts b/src/providers/cursor.ts index 290f615a..b38aee54 100644 --- a/src/providers/cursor.ts +++ b/src/providers/cursor.ts @@ -5,7 +5,16 @@ import { homedir } from 'os' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' import { readCachedResults, writeCachedResults } from '../cursor-cache.js' -import { isSqliteAvailable, isSqliteBusyError, getSqliteLoadError, openDatabase, blobToText, type SqliteDatabase } from '../sqlite.js' +import { + isSqliteAvailable, + isSqliteBusyError, + getSqliteLoadError, + openDatabase, + blobToText, + isSqliteReadonlyError, + warnSqliteReadonlyOnce, + type SqliteDatabase, +} from '../sqlite.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { DateRange } from '../types.js' import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' @@ -188,7 +197,8 @@ function loadWorkspaceMap(workspaceStorageDir: string): WorkspaceMapping { let db: SqliteDatabase try { db = openDatabase(wsDbPath) - } catch { + } catch (err) { + if (isSqliteReadonlyError(err)) warnSqliteReadonlyOnce(wsDbPath) continue } try { diff --git a/src/providers/sqlite-session-parser.ts b/src/providers/sqlite-session-parser.ts index b1e962f0..925a942b 100644 --- a/src/providers/sqlite-session-parser.ts +++ b/src/providers/sqlite-session-parser.ts @@ -2,7 +2,16 @@ import { readdir } from 'fs/promises' import { join } from 'path' import { calculateCost } from '../models.js' -import { isSqliteAvailable, getSqliteLoadError, openDatabase, blobToText, isSqliteBusyError, type SqliteDatabase } from '../sqlite.js' +import { + isSqliteAvailable, + getSqliteLoadError, + openDatabase, + blobToText, + isSqliteBusyError, + isSqliteReadonlyError, + warnSqliteReadonlyOnce, + type SqliteDatabase, +} from '../sqlite.js' import { buildAssistantCall, parseTimestamp, sanitize, type MessageData, type PartData } from './session-message.js' import type { SessionSource, @@ -310,7 +319,8 @@ export async function discoverSqliteSessions( let db: SqliteDatabase try { db = openDatabase(dbPath) - } catch { + } catch (err) { + if (isSqliteReadonlyError(err)) warnSqliteReadonlyOnce(dbPath) continue } diff --git a/src/sqlite.ts b/src/sqlite.ts index 3fb3c6a8..9576bc78 100644 --- a/src/sqlite.ts +++ b/src/sqlite.ts @@ -1,4 +1,9 @@ import { createRequire } from 'node:module' +import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs' +import { createHash, randomBytes } from 'node:crypto' +import { join } from 'node:path' + +import { getCodeburnCacheDir } from './cache-dir.js' /// Thin SQLite read-only wrapper over Node's built-in `node:sqlite` module (stable in /// Node 24, experimental in Node 22 / 23). Replaces the earlier `better-sqlite3` binding @@ -14,12 +19,14 @@ export type SqliteDatabase = { close(): void } -type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean }) => { +type DatabaseSyncInstance = { prepare(sql: string): { all(...params: unknown[]): Row[] } exec?(sql: string): void close(): void } +type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean }) => DatabaseSyncInstance + let DatabaseSync: DatabaseSyncCtor | null = null let loadAttempted = false let loadError: string | null = null @@ -116,12 +123,219 @@ export function isSqliteBusyError(err: unknown): boolean { ) } +/// SQLite reports SQLITE_READONLY_DIRECTORY as ERR_SQLITE_ERROR with an extended +/// result code on the Node 22 builds CodeBurn supports. Keep the base-code check +/// so this also covers SQLITE_READONLY and its other extended variants, while +/// leaving ENOENT/SQLITE_CANTOPEN distinguishable to callers. +export function isSqliteReadonlyError(err: unknown): boolean { + const e = err as { code?: unknown; errcode?: unknown; errstr?: unknown; message?: unknown } | null + const code = typeof e?.code === 'string' ? e.code : '' + const errcode = typeof e?.errcode === 'number' ? e.errcode : null + const message = [ + typeof e?.message === 'string' ? e.message : '', + typeof e?.errstr === 'string' ? e.errstr : '', + ].join(' ') + + return ( + (errcode !== null && (errcode & 0xff) === 8) || + /SQLITE_READONLY|attempt to write a readonly database|readonly database|read-only database/i.test(`${code} ${message}`) + ) +} + +type DatabaseFingerprint = { + dev: number + ino: number + mtimeMs: number + sizeBytes: number +} + +type CachedDatabaseMetadata = { + version: number + sourcePath: string + fingerprint: DatabaseFingerprint +} + +const SQLITE_CACHE_VERSION = 1 +const warnedReadonlyDatabases = new Set() + +/// A read-only SQLite connection can still need sidecar files. This notice is +/// intentionally once per source path: a provider may discover many sessions +/// from the same database, and the fallback is already doing the useful work. +export function warnSqliteReadonlyOnce(path: string): void { + if (warnedReadonlyDatabases.has(path)) return + warnedReadonlyDatabases.add(path) + process.stderr.write( + `codeburn: SQLite database ${path} is in a read-only directory and needs sidecar files; using a cache copy when necessary. ` + + 'The original database is not modified.\n', + ) +} + +function errorCode(err: unknown): string | undefined { + if (typeof err !== 'object' || err === null || !('code' in err)) return undefined + const code = err.code + return typeof code === 'string' ? code : undefined +} + +/// This deliberately mirrors fingerprintSqliteFile/fingerprintFile in +/// session-cache.ts. openDatabase is synchronous, so the fallback uses the +/// synchronous fs APIs only after the direct open has already failed; the +/// ordinary successful open remains probe-free. +function fingerprintDatabase(path: string): DatabaseFingerprint { + const main = statSync(path) + let wal: ReturnType | null = null + try { + wal = statSync(path + '-wal') + } catch (err) { + if (errorCode(err) !== 'ENOENT') throw err + } + return { + dev: main.dev, + ino: main.ino, + mtimeMs: wal ? Math.max(main.mtimeMs, wal.mtimeMs) : main.mtimeMs, + sizeBytes: main.size + (wal?.size ?? 0), + } +} + +function sameFingerprint(a: DatabaseFingerprint, b: DatabaseFingerprint): boolean { + return ( + a.dev === b.dev && + a.ino === b.ino && + a.mtimeMs === b.mtimeMs && + a.sizeBytes === b.sizeBytes + ) +} + +function isDatabaseFingerprint(value: unknown): value is DatabaseFingerprint { + if (typeof value !== 'object' || value === null) return false + const candidate = value as Partial + return ( + typeof candidate.dev === 'number' && + typeof candidate.ino === 'number' && + typeof candidate.mtimeMs === 'number' && + typeof candidate.sizeBytes === 'number' + ) +} + +function readCachedMetadata(path: string): CachedDatabaseMetadata | null { + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (typeof parsed !== 'object' || parsed === null) return null + const candidate = parsed as { version?: unknown; sourcePath?: unknown; fingerprint?: unknown } + if ( + candidate.version !== SQLITE_CACHE_VERSION || + typeof candidate.sourcePath !== 'string' || + !isDatabaseFingerprint(candidate.fingerprint) + ) return null + return { version: SQLITE_CACHE_VERSION, sourcePath: candidate.sourcePath, fingerprint: candidate.fingerprint } + } catch { + return null + } +} + +function unlinkIfPresent(path: string): void { + try { + unlinkSync(path) + } catch (err) { + if (errorCode(err) !== 'ENOENT') throw err + } +} + +function copyOptionalFile(sourcePath: string, destinationPath: string): boolean { + try { + copyFileSync(sourcePath, destinationPath) + return true + } catch (err) { + if (errorCode(err) === 'ENOENT') return false + throw err + } +} + +function readOnlyCachePath(sourcePath: string, fingerprint: DatabaseFingerprint): string { + const cacheDir = join(getCodeburnCacheDir(), 'sqlite-ro') + mkdirSync(cacheDir, { recursive: true, mode: 0o700 }) + + const sourceKey = createHash('sha256').update(sourcePath, 'utf8').digest('hex') + const cachePath = join(cacheDir, `${sourceKey}.db`) + const metadataPath = `${cachePath}.json` + const cached = readCachedMetadata(metadataPath) + if ( + existsSync(cachePath) && + cached?.sourcePath === sourcePath && + sameFingerprint(cached.fingerprint, fingerprint) + ) { + return cachePath + } + + const tempBase = `${cachePath}.tmp-${process.pid}-${randomBytes(8).toString('hex')}` + const tempWal = tempBase + '-wal' + const tempShm = tempBase + '-shm' + const tempMetadata = `${metadataPath}.tmp-${process.pid}-${randomBytes(8).toString('hex')}` + + try { + copyFileSync(sourcePath, tempBase) + const copiedWal = copyOptionalFile(sourcePath + '-wal', tempWal) + const copiedShm = copyOptionalFile(sourcePath + '-shm', tempShm) + + // Do not publish a cache made from a moving database. A live WAL writer will + // normally make the direct open succeed once its sidecars exist; this check + // covers the narrow race where the source changes during the copy fallback. + if (!sameFingerprint(fingerprintDatabase(sourcePath), fingerprint)) { + throw new Error('SQLite database changed while preparing its read-only cache copy') + } + + unlinkIfPresent(cachePath) + unlinkIfPresent(cachePath + '-wal') + unlinkIfPresent(cachePath + '-shm') + renameSync(tempBase, cachePath) + if (copiedWal) renameSync(tempWal, cachePath + '-wal') + if (copiedShm) renameSync(tempShm, cachePath + '-shm') + + const metadata: { version: number; sourcePath: string; fingerprint: DatabaseFingerprint } = { + version: SQLITE_CACHE_VERSION, + sourcePath, + fingerprint, + } + writeFileSync(tempMetadata, JSON.stringify(metadata), { encoding: 'utf8', mode: 0o600 }) + renameSync(tempMetadata, metadataPath) + return cachePath + } finally { + unlinkIfPresent(tempBase) + unlinkIfPresent(tempWal) + unlinkIfPresent(tempShm) + unlinkIfPresent(tempMetadata) + } +} + +function openReadonlyCache(path: string, originalError: unknown): DatabaseSyncInstance { + let fingerprint: DatabaseFingerprint + try { + fingerprint = fingerprintDatabase(path) + } catch { + // Preserve the original SQLite error when the source disappeared or became + // inaccessible between the failed query and the fallback probe. + throw originalError + } + const cachedPath = readOnlyCachePath(path, fingerprint) + const Driver = DatabaseSync + if (Driver === null) throw new Error(getSqliteLoadError()) + return new Driver(cachedPath, { readOnly: true }) +} + export function openDatabase(path: string): SqliteDatabase { if (!loadDriver() || DatabaseSync === null) { throw new Error(getSqliteLoadError()) } - const db = new DatabaseSync(path, { readOnly: true }) + let db: DatabaseSyncInstance + let fallbackUsed = false + try { + db = new DatabaseSync(path, { readOnly: true }) + } catch (err) { + if (!isSqliteReadonlyError(err)) throw err + fallbackUsed = true + warnSqliteReadonlyOnce(path) + db = openReadonlyCache(path, err) + } try { db.exec?.('PRAGMA busy_timeout = 1000') } catch { @@ -130,7 +344,26 @@ export function openDatabase(path: string): SqliteDatabase { return { query(sql: string, params: unknown[] = []): T[] { - return db.prepare(sql).all(...params) as T[] + try { + return db.prepare(sql).all(...params) as T[] + } catch (err) { + if (!isSqliteReadonlyError(err)) throw err + if (fallbackUsed) throw err + fallbackUsed = true + warnSqliteReadonlyOnce(path) + try { + db.close() + } catch { + // The failed connection may already have been closed by node:sqlite. + } + db = openReadonlyCache(path, err) + try { + db.exec?.('PRAGMA busy_timeout = 1000') + } catch { + // Best effort, matching the direct-open path above. + } + return db.prepare(sql).all(...params) as T[] + } }, close() { db.close() diff --git a/tests/sqlite-readonly-parent.test.ts b/tests/sqlite-readonly-parent.test.ts new file mode 100644 index 00000000..13a71af3 --- /dev/null +++ b/tests/sqlite-readonly-parent.test.ts @@ -0,0 +1,207 @@ +import { chmodSync, existsSync, readdirSync, statSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { tmpdir } from 'node:os' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + isSqliteReadonlyError, + openDatabase, +} from '../src/sqlite.js' +import { + discoverSqliteSessions, + type SqliteProviderConfig, +} from '../src/providers/sqlite-session-parser.js' + +const requireForTest = createRequire(import.meta.url) + +type NativeDatabase = { + exec(sql: string): void + prepare(sql: string): { run(...params: unknown[]): void; all(...params: unknown[]): unknown[] } + close(): void +} + +type NativeDatabaseCtor = new (path: string) => NativeDatabase + +const { DatabaseSync: NativeDatabase } = requireForTest('node:sqlite') as { + DatabaseSync: NativeDatabaseCtor +} + +let sourceRoot: string +let cacheRoot: string +let previousCacheDir: string | undefined +const openWriters: NativeDatabase[] = [] + +beforeEach(async () => { + sourceRoot = await mkdtemp(join(tmpdir(), 'codeburn-sqlite-source-')) + cacheRoot = await mkdtemp(join(tmpdir(), 'codeburn-sqlite-cache-')) + previousCacheDir = process.env['CODEBURN_CACHE_DIR'] + process.env['CODEBURN_CACHE_DIR'] = cacheRoot +}) + +afterEach(async () => { + chmodSync(sourceRoot, 0o755) + for (const writer of openWriters.splice(0)) writer.close() + await rm(sourceRoot, { recursive: true, force: true }) + await rm(cacheRoot, { recursive: true, force: true }) + if (previousCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR'] + else process.env['CODEBURN_CACHE_DIR'] = previousCacheDir +}) + +function createClosedWalDatabase(dbPath: string): void { + const db = new NativeDatabase(dbPath) + db.exec('PRAGMA journal_mode=WAL') + db.exec('CREATE TABLE values_table (c INTEGER)') + db.prepare('INSERT INTO values_table (c) VALUES (?)').run(1) + db.close() +} + +function createOpenWalDatabase(dbPath: string): NativeDatabase { + const db = new NativeDatabase(dbPath) + db.exec('PRAGMA journal_mode=WAL') + db.exec('CREATE TABLE values_table (c INTEGER)') + db.prepare('INSERT INTO values_table (c) VALUES (?)').run(1) + expect(existsSync(dbPath + '-wal')).toBe(true) + expect(existsSync(dbPath + '-shm')).toBe(true) + openWriters.push(db) + return db +} + +function createDiscoveryDatabase(dbPath: string): void { + const db = new NativeDatabase(dbPath) + db.exec('PRAGMA journal_mode=WAL') + db.exec(` + CREATE TABLE session ( + id TEXT PRIMARY KEY, + directory TEXT, + title TEXT, + time_created INTEGER, + parent_id TEXT, + time_archived INTEGER + ) + `) + db.exec('CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data BLOB)') + db.exec('CREATE TABLE part (id INTEGER PRIMARY KEY, message_id TEXT, session_id TEXT, data BLOB)') + db.prepare( + 'INSERT INTO session (id, directory, title, time_created, parent_id, time_archived) VALUES (?, ?, ?, ?, ?, ?)', + ).run('session-1', '/tmp/project', 'Read-only fixture', Date.now(), null, null) + db.close() +} + +function makeSourceParentReadOnly(skip: (reason?: string) => void): boolean { + chmodSync(sourceRoot, 0o555) + const mode = statSync(sourceRoot).mode & 0o777 + if ((mode & 0o222) !== 0) { + skip(`SKIP: chmod 0555 did not make the fixture parent non-writable (mode ${mode.toString(8)})`) + return false + } + return true +} + +function cachedDatabaseFiles(): string[] { + try { + return readdirSync(join(cacheRoot, 'sqlite-ro')).filter(name => name.endsWith('.db')) + } catch { + return [] + } +} + +function readValue(dbPath: string): number { + const db = openDatabase(dbPath) + try { + const rows = db.query<{ c: number }>('SELECT c FROM values_table') + return rows[0]?.c ?? -1 + } finally { + db.close() + } +} + +describe('SQLite read-only parent fallback', () => { + it('keeps the existing writable-parent open behaviour', () => { + const dbPath = join(sourceRoot, 'state.vscdb') + createClosedWalDatabase(dbPath) + expect(existsSync(dbPath + '-wal')).toBe(false) + expect(existsSync(dbPath + '-shm')).toBe(false) + + expect(readValue(dbPath)).toBe(1) + + expect(existsSync(dbPath + '-wal')).toBe(true) + expect(existsSync(dbPath + '-shm')).toBe(true) + expect(cachedDatabaseFiles()).toEqual([]) + }) + + it('reads a WAL database when the parent is read-only and sidecars are absent', ({ skip }) => { + const dbPath = join(sourceRoot, 'state.vscdb') + createClosedWalDatabase(dbPath) + expect(existsSync(dbPath + '-wal')).toBe(false) + expect(existsSync(dbPath + '-shm')).toBe(false) + if (!makeSourceParentReadOnly(skip)) return + + expect(readValue(dbPath)).toBe(1) + + expect(existsSync(dbPath + '-wal')).toBe(false) + expect(existsSync(dbPath + '-shm')).toBe(false) + expect(cachedDatabaseFiles()).toHaveLength(1) + }) + + it('opens directly when a read-only parent already has WAL sidecars', ({ skip }) => { + const dbPath = join(sourceRoot, 'state.vscdb') + createOpenWalDatabase(dbPath) + if (!makeSourceParentReadOnly(skip)) return + + expect(readValue(dbPath)).toBe(1) + expect(cachedDatabaseFiles()).toEqual([]) + }) + + it('reuses an unchanged fallback copy instead of copying the database again', ({ skip }) => { + const dbPath = join(sourceRoot, 'state.vscdb') + createClosedWalDatabase(dbPath) + if (!makeSourceParentReadOnly(skip)) return + + expect(readValue(dbPath)).toBe(1) + const cachedPath = join(cacheRoot, 'sqlite-ro', cachedDatabaseFiles()[0]!) + const firstMtime = statSync(cachedPath).mtimeMs + expect(readValue(dbPath)).toBe(1) + expect(statSync(cachedPath).mtimeMs).toBe(firstMtime) + }) + + it('keeps a genuinely missing database distinguishable from SQLITE_READONLY', () => { + let thrown: unknown + try { + openDatabase(join(sourceRoot, 'missing.vscdb')) + } catch (err) { + thrown = err + } + + expect(thrown).toBeDefined() + expect(isSqliteReadonlyError(thrown)).toBe(false) + expect(thrown).toMatchObject({ errcode: 14, message: 'unable to open database file' }) + }) + + it('surfaces one read-only notice in SQLite discovery and still finds the session', async ({ skip }) => { + const dbPath = join(sourceRoot, 'state.db') + createDiscoveryDatabase(dbPath) + if (!makeSourceParentReadOnly(skip)) return + + const config: SqliteProviderConfig = { + providerName: 'opencode', + displayName: 'OpenCode', + dbDir: sourceRoot, + dbFilePrefix: 'state', + } + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + const sessions = await discoverSqliteSessions(config) + expect(sessions).toHaveLength(1) + expect(sessions[0]?.path).toBe(`${dbPath}:session-1`) + expect(stderr.mock.calls.filter(([chunk]) => String(chunk).includes('read-only directory'))).toHaveLength(1) + + await discoverSqliteSessions(config) + expect(stderr.mock.calls.filter(([chunk]) => String(chunk).includes('read-only directory'))).toHaveLength(1) + } finally { + stderr.mockRestore() + } + }) +})