diff --git a/hub/src/cursor/cursorLegacyMigrator.test.ts b/hub/src/cursor/cursorLegacyMigrator.test.ts index 78da0abb..57f8f5a8 100644 --- a/hub/src/cursor/cursorLegacyMigrator.test.ts +++ b/hub/src/cursor/cursorLegacyMigrator.test.ts @@ -24,7 +24,7 @@ * - skipVerify path (load + prompt both skipped, no probe spawned) */ -import { describe, it, expect, beforeEach, afterEach } from 'bun:test' +import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test' import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, statSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' @@ -205,7 +205,7 @@ function cleanupHarness(h: Harness): void { try { rmSync(h.tmp, { recursive: true, force: true }) } catch {} } -function makeMigrator(h: Harness, probe: ReturnType | null, opts: { archiveSession?: (id: string) => Promise; updateOverride?: (sessionId: string, namespace: string, lastUsedModel: string | null) => { ok: true } | { ok: false; reason: 'version_mismatch_or_missing' } | { ok: false; reason: 'session_active' }; isAgentAcpTransportActive?: () => { active: boolean; holderPid: number | null }; getCurrentSession?: (sessionId: string, namespace: string) => { active: boolean; lifecycleState?: string; cursorSessionProtocol?: string } | null; acquireAcpActiveLock?: () => { release(): void } | null; checkpointLegacyStore?: (storeDbPath: string) => void; getHapiMessageCount?: (sessionId: string, namespace: string) => number } = {}): CursorLegacyMigrator { +function makeMigrator(h: Harness, probe: ReturnType | null, opts: { archiveSession?: (id: string) => Promise; updateOverride?: (sessionId: string, namespace: string, lastUsedModel: string | null) => { ok: true } | { ok: false; reason: 'version_mismatch_or_missing' } | { ok: false; reason: 'session_active' }; isAgentAcpTransportActive?: () => { active: boolean; holderPid: number | null }; getCurrentSession?: (sessionId: string, namespace: string) => { active: boolean; lifecycleState?: string; cursorSessionProtocol?: string } | null; acquireAcpActiveLock?: () => { release(): void } | null; checkpointLegacyStore?: (storeDbPath: string) => void; removeSourceFile?: (storeDbPath: string) => void; getHapiMessageCount?: (sessionId: string, namespace: string) => number } = {}): CursorLegacyMigrator { return new CursorLegacyMigrator({}, { homeDir: () => h.home, hostName: () => 'h', // matches the test sessions' metadata.host @@ -229,6 +229,7 @@ function makeMigrator(h: Harness, probe: ReturnType | null // implementations to simulate post-checkpoint WAL growth. // Codex review #34 P2 v8. checkpointLegacyStore: opts.checkpointLegacyStore ?? (() => {}), + removeSourceFile: opts.removeSourceFile, getCurrentSession: opts.getCurrentSession, logger: { debug() {}, info() {}, warn() {}, error() {} }, archiveSession: opts.archiveSession ?? (async (id) => { h.archiveCalls.push(id) }), @@ -240,6 +241,12 @@ function makeMigrator(h: Harness, probe: ReturnType | null }) } +function stubPlatform(value: NodeJS.Platform): () => void { + const original = process.platform + Object.defineProperty(process, 'platform', { value, configurable: true }) + return () => Object.defineProperty(process, 'platform', { value: original, configurable: true }) +} + /* ---------- tests ---------- */ describe('findLegacyChatStore', () => { @@ -786,6 +793,78 @@ describe('CursorLegacyMigrator.migrateOne — happy path', () => { expect(out.lastUsedModelPreserved).toBeNull() expect(h.updateCalls[0].lastUsedModel).toBeNull() }) + + it('runs Windows-style source cleanup GC and retries sharing failures without rolling back ACP', async () => { + const cursorSessionId = 'windows-cleanup-retry-uuid' + const sourceStore = h.placeLegacyStore(cursorSessionId) + let removeCalls = 0 + const gcSpy = spyOn(Bun, 'gc') + const restorePlatform = stubPlatform('win32') + const session = h.makeSession({ + metadata: { path: '/workspace/x', host: 'h', flavor: 'cursor', cursorSessionId } + }) + try { + const migrator = makeMigrator(h, makeMockProbe(), { + removeSourceFile: (storeDbPath) => { + removeCalls += 1 + if (removeCalls < 2) { + const error = new Error('resource busy or locked') as NodeJS.ErrnoException + error.code = 'EBUSY' + throw error + } + rmSync(storeDbPath, { force: true }) + } + }) + + const out = await migrator.migrateOne(session, {}) + + expect(out.ok).toBe(true) + if (!out.ok) return + expect(out.sourceRemoved).toBe(true) + expect(removeCalls).toBe(2) + expect(gcSpy.mock.calls.length).toBe(2) + expect(existsSync(sourceStore)).toBe(false) + expect(existsSync(join(h.acpSessionsDir, cursorSessionId, 'store.db'))).toBe(true) + } finally { + gcSpy.mockRestore() + restorePlatform() + } + }) + + it('keeps the ACP target when source cleanup ultimately fails', async () => { + const cursorSessionId = 'cleanup-failure-target-intact-uuid' + const sourceStore = h.placeLegacyStore(cursorSessionId) + let removeCalls = 0 + const gcSpy = spyOn(Bun, 'gc') + const restorePlatform = stubPlatform('win32') + const session = h.makeSession({ + metadata: { path: '/workspace/x', host: 'h', flavor: 'cursor', cursorSessionId } + }) + try { + const migrator = makeMigrator(h, makeMockProbe(), { + removeSourceFile: () => { + removeCalls += 1 + const error = new Error('resource busy or locked') as NodeJS.ErrnoException + error.code = 'EBUSY' + throw error + } + }) + + const out = await migrator.migrateOne(session, {}) + + expect(out.ok).toBe(true) + if (!out.ok) return + expect(out.sourceRemoved).toBe(false) + expect(removeCalls).toBe(3) + expect(gcSpy.mock.calls.length).toBe(3) + expect(existsSync(sourceStore)).toBe(true) + expect(existsSync(join(h.acpSessionsDir, cursorSessionId, 'store.db'))).toBe(true) + expect(h.updateCalls).toHaveLength(1) + } finally { + gcSpy.mockRestore() + restorePlatform() + } + }) }) describe('CursorLegacyMigrator.migrateOne — ambiguous source store (tiann/hapi#872)', () => { diff --git a/hub/src/cursor/cursorLegacyMigrator.ts b/hub/src/cursor/cursorLegacyMigrator.ts index d5af5e35..6ce40a3c 100644 --- a/hub/src/cursor/cursorLegacyMigrator.ts +++ b/hub/src/cursor/cursorLegacyMigrator.ts @@ -114,6 +114,8 @@ export interface CursorLegacyMigratorDeps { * Codex review #34 P2 v8. */ checkpointLegacyStore?: (storeDbPath: string) => void + /** Remove the legacy store.db. Override in tests to exercise cleanup failure paths. */ + removeSourceFile?: (storeDbPath: string) => void /** Where to allocate the verify staging temp dir. Default: os.tmpdir(). */ tmpDir?: () => string /** Time source for telemetry. Default: Date.now. */ @@ -474,7 +476,7 @@ export function preflightSession(session: Session | undefined, now: () => number export class CursorLegacyMigrator { private readonly opts: Required> - private readonly deps: Required> + private readonly deps: Required> & Pick constructor(opts: CursorLegacyMigratorOptions, deps: CursorLegacyMigratorDeps) { @@ -508,6 +510,7 @@ export class CursorLegacyMigrator { // behavior can inject `() => tryAcquireAcpActiveLock(home)`. acquireAcpActiveLock: deps.acquireAcpActiveLock ?? (() => ({ release() {} })), checkpointLegacyStore: deps.checkpointLegacyStore ?? defaultCheckpointLegacyStore, + removeSourceFile: deps.removeSourceFile ?? ((storeDbPath) => rmSync(storeDbPath, { force: true })), tmpDir: deps.tmpDir ?? (() => tmpdir()), now: deps.now ?? (() => Date.now()), awaitLockRelease: deps.awaitLockRelease ?? defaultAwaitLockRelease, @@ -986,27 +989,12 @@ export class CursorLegacyMigrator { return refusal(session.id, 'metadata_write_failed', `hapi.db write failed: ${updateResult.reason}`, start, this.deps.now) } - // Remove source unless --keep-source. The rm is the LAST step; if it - // fails, the migration is still considered successful because the ACP - // target is intact and metadata is flipped. - let sourceRemoved = false - if (!opts.keepSource) { - try { - rmSync(legacy.storeDbPath, { force: true }) - // Also drop SQLite sidecars if present (WAL + SHM). - tryRm(`${legacy.storeDbPath}-wal`) - tryRm(`${legacy.storeDbPath}-shm`) - // ONLY rmdir the parent if empty. We never recursively delete - // unknown files - a future cursor-agent version that drops - // additional artifacts in the chat dir would otherwise see - // them silently destroyed. - try { rmdirSync(dirname(legacy.storeDbPath)) } catch {} - sourceRemoved = true - log.info('[migrator] removed legacy source', { sessionId: session.id, path: legacy.storeDbPath }) - } catch (err) { - log.warn('[migrator] legacy source rm failed (target intact, treating as success)', { sessionId: session.id, error: err instanceof Error ? err.message : String(err) }) - } - } + // Remove source unless --keep-source. The cleanup is the LAST step; + // if it ultimately fails, the migration is still considered + // successful because the ACP target is intact and metadata is flipped. + const sourceRemoved = opts.keepSource + ? false + : await removeLegacySource(legacy.storeDbPath, session.id, log, this.deps.removeSourceFile) // tiann/hapi#872: diagnostic log on every successful transplant. // Uses pre-rm snapshots captured at discovery time so the count @@ -1217,6 +1205,63 @@ function tryRm(path: string): void { } } +const WINDOWS_SOURCE_CLEANUP_RETRY_DELAYS_MS = [0, 50, 250] as const + +function isRetryableWindowsSourceCleanupError(error: unknown): boolean { + if (process.platform !== 'win32') return false + const code = (error as NodeJS.ErrnoException | null)?.code + return code === 'EBUSY' || code === 'EPERM' +} + +function collectWindowsSqliteGarbage(): void { + if (process.platform !== 'win32') return + // Bun's sqlite3_close_v2 can leave unreachable prepared statements holding + // Windows file handles until the next GC cycle. This mirrors Store.close() + // and must happen before the legacy source removal attempt. + try { Bun.gc(true) } catch {} +} + +async function removeLegacySource( + storeDbPath: string, + sessionId: string, + log: NonNullable, + removeSourceFile: (storeDbPath: string) => void +): Promise { + const delays = process.platform === 'win32' + ? WINDOWS_SOURCE_CLEANUP_RETRY_DELAYS_MS + : [0] as const + let lastError: unknown = null + + for (let attempt = 0; attempt < delays.length; attempt += 1) { + const delayMs = delays[attempt] + if (delayMs > 0) await sleep(delayMs) + collectWindowsSqliteGarbage() + + try { + removeSourceFile(storeDbPath) + // Also drop SQLite sidecars if present (WAL + SHM). + tryRm(`${storeDbPath}-wal`) + tryRm(`${storeDbPath}-shm`) + // ONLY rmdir the parent if empty. We never recursively delete + // unknown files - a future cursor-agent version that drops + // additional artifacts in the chat dir would otherwise see + // them silently destroyed. + try { rmdirSync(dirname(storeDbPath)) } catch {} + log.info('[migrator] removed legacy source', { sessionId, path: storeDbPath, attempts: attempt + 1 }) + return true + } catch (error) { + lastError = error + if (!isRetryableWindowsSourceCleanupError(error) || attempt === delays.length - 1) break + } + } + + log.warn('[migrator] legacy source rm failed (target intact, treating as success)', { + sessionId, + error: lastError instanceof Error ? lastError.message : String(lastError) + }) + return false +} + /** * Open the legacy store and flush the WAL into the main file with * `PRAGMA wal_checkpoint(TRUNCATE)`. Idempotent: on non-WAL stores the