Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(turnrewind): data-safety P0 fixes from the 2026-09-03 review

yingtianlan2634adccc2a8
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
index dcfdf960..cd6d9500 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
@@ -303,6 +303,11 @@ function assertSafePath(workspaceDir: string, path: string): string {
const target = resolve(root, path)
if (target !== root && !target.startsWith(`${root}${sep}`))
throw new Error(`TURNREWIND_PATH_ESCAPE: ${path}`)
+ // Defense in depth: the workspace root itself is never a restorable path.
+ // A path that normalizes to the root would make a restore delete the whole
+ // workspace instead of one file.
+ if (target === root)
+ throw new Error(`TURNREWIND_PATH_ESCAPE: ${path} (workspace root cannot be restored)`)
let current = root
const suffix = relative(root, target)
@@ -642,7 +647,20 @@ export async function restorePath(store: SnapshotStore, commit: string, path: st
const info = lstatSync(target)
if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)
- rmSync(target, { recursive: info.isDirectory(), force: true })
+ if (info.isDirectory()) {
+ // The turn replaced a file with a directory, or the user built a
+ // directory at this path after the snapshot. Recursively deleting it
+ // can destroy unrelated files that the turn never touched (files
+ // ignored by git are not even in the snapshot). Refuse loudly; only
+ // an EMPTY directory is removed, since it holds nothing to lose.
+ const contents = readdirSync(target)
+ if (contents.length > 0)
+ throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is now a non-empty directory; undo will not recursively delete it (remove it manually if intended)`)
+ rmSync(target, { force: true })
+ }
+ else {
+ rmSync(target, { force: true })
+ }
}
return { path, result: 'removed' }
}
@@ -660,6 +678,11 @@ export async function restorePath(store: SnapshotStore, commit: string, path: st
try {
if (existsSync(target)) {
const info = lstatSync(target)
+ // A directory (even an empty one) at the target is refused: restoring a
+ // file over it must never recurse into unrelated content, with or
+ // without --force. The user removes the directory manually instead.
+ if (info.isDirectory())
+ throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a directory; undo will not delete it to restore a file`)
if (info.isSymbolicLink() || !info.isFile())
throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)
// Move the old content aside instead of deleting it: the swap keeps a
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
index aa2754bb..08d42045 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
@@ -511,26 +511,67 @@ export interface UndoNoticeInput {
}
/** undo 完成事务:turn → undone、operation → applied、notice 入队。 */
-export function completeUndoWithNotice(db: Ledger, turnId: string, notice: UndoNoticeInput): void {
+export interface UndoCompletion {
+ noticeId: string
+ sessionId: string
+ workspaceKey: string
+ targetTurnId: string
+ restoredPaths: string[]
+ /** 恢复失败的单路径清单(含原因),随 operation.error 与 notice 持久化。 */
+ notRestored: { path: string, reason: string }[]
+ operationId: string
+ createdAt: string
+}
+
+/**
+ * 完成一次 undo 的唯一入口:单事务内校验并落 turn/operation/notice。
+ *
+ * - turn 允许从 settled 或 interrupted 进入 undone(interrupted turn 的文件
+ * 同样会被恢复,状态必须跟着走,否则会残留在可撤销列表里被重复 undo);
+ * - 两个 UPDATE 各带状态条件,changes !== 1 即状态漂移:事务回滚且
+ * operation 落 needs-recovery,交给启动围栏拦截该 workspace;
+ * - 未恢复路径写入 operation.error 与 notice,让审计和 redo 知道部分失败。
+ */
+export function completeUndoTransaction(db: Ledger, completion: UndoCompletion): 'undone' | 'needs-recovery' {
+ const summary = completion.notRestored.length > 0
+ ? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')
+ : null
db.exec('BEGIN')
try {
- db.prepare('UPDATE turns SET status = \'undone\' WHERE turn_id = ? AND status = \'settled\'').run(turnId)
+ const turn = db.prepare(`
+ UPDATE turns SET status = 'undone', settled_at = ?
+ WHERE turn_id = ? AND status IN ('settled', 'interrupted') AND reversible = 1
+ `).run(new Date().toISOString(), completion.targetTurnId)
+ if (turn.changes !== 1)
+ throw new Error(`TURN_STATE_MISMATCH: turn ${completion.targetTurnId} is not in a restorable state`)
+ const operation = db.prepare(`
+ UPDATE operations SET outcome = 'applied', settled_at = ?, error = ?
+ WHERE operation_id = ? AND outcome = 'applying'
+ `).run(new Date().toISOString(), summary, completion.operationId)
+ if (operation.changes !== 1)
+ throw new Error(`OPERATION_STATE_MISMATCH: operation ${completion.operationId} is not applying`)
db.prepare(`
INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at, kind)
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, 'undo')
`).run(
- notice.noticeId,
- notice.sessionId,
- notice.workspaceKey,
- notice.targetTurnId,
- JSON.stringify([notice.targetTurnId]),
- JSON.stringify(notice.paths),
- notice.createdAt,
+ completion.noticeId,
+ completion.sessionId,
+ completion.workspaceKey,
+ completion.targetTurnId,
+ JSON.stringify([completion.targetTurnId]),
+ JSON.stringify([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)]),
+ completion.createdAt,
)
db.exec('COMMIT')
+ return 'undone'
}
catch (error) {
db.exec('ROLLBACK')
+ // 账本未能完成:operation 落 needs-recovery,启动围栏将拦截该 workspace
+ db.prepare(`
+ UPDATE operations SET outcome = 'needs-recovery', settled_at = ?, error = ?
+ WHERE operation_id = ? AND outcome = 'applying'
+ `).run(new Date().toISOString(), String((error as Error).message), completion.operationId)
throw error
}
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
index 0d08b10f..d5e99679 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
@@ -37,7 +37,7 @@ import { isSystemSensitiveWorkspace } from './guard'
import {
claimPendingPlan,
completeRedoWithNotice,
- completeUndoWithNotice,
+ completeUndoTransaction,
createOperation,
createPendingPlan,
getLatestAppliedUndo,
@@ -383,7 +383,7 @@ export async function executeUndoRestore(
try {
const targets = skipConflicts ? entries.filter(entry => !entry.conflict) : entries
const restoredPaths: string[] = []
- const failedPaths: { path: string, error: string }[] = []
+ const failedPaths: { path: string, reason: string }[] = []
for (const entry of targets) {
try {
await restorePath(runtime.store, target.before_ref!, entry.path)
@@ -393,27 +393,31 @@ export async function executeUndoRestore(
// One unrestorable file (oversized blob, unsupported target) must not
// abort the whole undo: the other files still restore, and the failure
// is reported per path instead of triggering a full rollback.
- failedPaths.push({ path: entry.path, error: String((error as Error).message ?? error) })
+ failedPaths.push({ path: entry.path, reason: String((error as Error).message ?? error) })
}
}
const skippedPaths = skipConflicts
? entries.filter(entry => entry.conflict).map(entry => entry.path)
: []
- completeUndoWithNotice(runtime.db, target.turn_id, {
+ // 单事务完成 turn/operation/notice;含 notRestored 明细,部分失败
+ // 持久化进 operation.error 与 notice(P0-5)。状态漂移或事务失败时
+ // operation 落 needs-recovery,由启动围栏拦截(P0-3)。
+ completeUndoTransaction(runtime.db, {
noticeId: randomUUID(),
sessionId,
workspaceKey,
targetTurnId: target.turn_id,
- paths: restoredPaths,
+ restoredPaths,
+ notRestored: failedPaths,
+ operationId,
createdAt: new Date().toISOString(),
})
- settleOperation(runtime.db, operationId, 'applied')
runtime.parentRef = beforeRef
let text = `Undid turn ${target.turn_id} and restored ${restoredPaths.length} file(s). The next model request will receive a rewind notice.`
if (skippedPaths.length > 0)
text += ` Skipped ${skippedPaths.length} conflicted file(s): ${skippedPaths.join(', ')}.`
if (failedPaths.length > 0)
- text += ` Not restored (${failedPaths.length} file(s)): ${failedPaths.map(failure => `${failure.path} (${failure.error.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.error})`).join('; ')}.`
+ text += ` Not restored (${failedPaths.length} file(s)): ${failedPaths.map(failure => `${failure.path} (${failure.reason.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.reason})`).join('; ')}.`
return text
}
catch (error) {
diff --git a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
index 587c420f..141f6b89 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { it } from 'vitest'
import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from '../src/host/service/git-snapshot'
-import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../src/host/service/ledger'
+import { completeUndoTransaction, createOperation, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../src/host/service/ledger'
import { initGitWorkspace } from './git-test-utils.js'
it('captures and restores modified, added, and deleted files', async () => {
@@ -73,12 +73,15 @@ it('allows sequential undo of an interrupted turn after a later turn', async ()
settleTurn(db, 'session:B', 'refs/turnrewind/b-after')
for (const file of await snapshotDiff(store, beforeB.commit, afterB.commit)) await restorePath(store, beforeB.commit, file)
- completeUndoWithNotice(db, 'session:B', {
+ createOperation(db, { operationId: 'op-b', kind: 'undo', targetTurnId: 'session:B', requestedAt: '2026-01-01T00:01:30.000Z' })
+ completeUndoTransaction(db, {
noticeId: 'notice-b',
sessionId: 'session',
workspaceKey: workspace.toLowerCase(),
targetTurnId: 'session:B',
- paths: filesB,
+ restoredPaths: filesB,
+ notRestored: [],
+ operationId: 'op-b',
createdAt: '2026-01-01T00:02:00.000Z',
})
assert.equal(getLatestTurn(db, 'session', workspace.toLowerCase()).turn_id, 'session:A')
diff --git a/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js b/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js
index 63d59add..ca5b60a8 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { it } from 'vitest'
-import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'
+import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'
it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))
@@ -49,12 +49,15 @@ it('marks undo and queues its one-time notice atomically', async () => {
beforeRef: 'refs/turnrewind/undo-before',
})
settleTurn(db, 'session:undo', 'refs/turnrewind/undo-after')
- completeUndoWithNotice(db, 'session:undo', {
+ createOperation(db, { operationId: 'op-undo', kind: 'undo', targetTurnId: 'session:undo', requestedAt: '2026-01-01T00:00:30.000Z' })
+ completeUndoTransaction(db, {
noticeId: 'notice-undo',
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: 'session:undo',
- paths: ['src/reverted.ts'],
+ restoredPaths: ['src/reverted.ts'],
+ notRestored: [],
+ operationId: 'op-undo',
createdAt: '2026-01-01T00:01:00.000Z',
})
assert.equal(getTurn(db, 'session:undo').status, 'undone')
@@ -152,12 +155,15 @@ it('merges a C-B-A undo sequence into one complete notice', async () => {
['session:B', 'b.ts', '2026-01-01T00:04:00.000Z'],
['session:A', 'a.ts', '2026-01-01T00:05:00.000Z'],
]) {
- completeUndoWithNotice(db, turnId, {
+ createOperation(db, { operationId: `op-${turnId}`, kind: 'undo', targetTurnId: turnId, requestedAt: time })
+ completeUndoTransaction(db, {
noticeId: `notice-${turnId}`,
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: turnId,
- paths: [path],
+ restoredPaths: [path],
+ notRestored: [],
+ operationId: `op-${turnId}`,
createdAt: time,
})
}
@@ -227,12 +233,15 @@ it('selects an interrupted turn after a later turn is undone', async () => {
beforeRef: 'refs/turnrewind/later-before',
})
settleTurn(db, 'session:later', 'refs/turnrewind/later-after')
- completeUndoWithNotice(db, 'session:later', {
+ createOperation(db, { operationId: 'op-later', kind: 'undo', targetTurnId: 'session:later', requestedAt: '2026-01-01T00:01:30.000Z' })
+ completeUndoTransaction(db, {
noticeId: 'notice-later',
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: 'session:later',
- paths: ['later.txt'],
+ restoredPaths: ['later.txt'],
+ notRestored: [],
+ operationId: 'op-later',
createdAt: '2026-01-01T00:02:00.000Z',
})
assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
@@ -262,14 +271,15 @@ it('redoes an applied undo and queues a redo notice atomically', async () => {
requestedAt: '2026-01-01T00:01:00.000Z',
beforeRef: 'refs/turnrewind/operation-op-undo',
})
- settleOperation(db, 'op-undo', 'applied')
- completeUndoWithNotice(db, 'session:1', {
- noticeId: 'notice-undo',
+ completeUndoTransaction(db, {
+ noticeId: 'notice-undo-2',
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: 'session:1',
- paths: ['a.ts'],
- createdAt: '2026-01-01T00:01:01.000Z',
+ restoredPaths: ['a.ts'],
+ notRestored: [],
+ operationId: 'op-undo',
+ createdAt: '2026-01-01T00:01:00.000Z',
})
assert.equal(getTurn(db, 'session:1').status, 'undone')
assert.equal(getLatestAppliedUndo(db, 'session', 'workspace').operation_id, 'op-undo')
@@ -284,6 +294,7 @@ it('redoes an applied undo and queues a redo notice atomically', async () => {
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: 'session:1',
+ turns: ['session:1'],
paths: ['a.ts'],
createdAt: '2026-01-01T00:02:00.000Z',
})
@@ -321,12 +332,15 @@ it('lists reversible turns newest-first and marks dead snapshots skipped', async
})
settleTurn(db, turnId, `refs/turnrewind/turn-${turnId}-after`)
}
- completeUndoWithNotice(db, 'session:3', {
+ createOperation(db, { operationId: 'op-session-3', kind: 'undo', targetTurnId: 'session:3', requestedAt: '2026-01-01T00:02:30.000Z' })
+ completeUndoTransaction(db, {
noticeId: 'notice-3',
sessionId: 'session',
workspaceKey: 'workspace',
targetTurnId: 'session:3',
- paths: ['a.txt'],
+ restoredPaths: ['a.txt'],
+ notRestored: [],
+ operationId: 'op-session-3',
createdAt: '2026-01-01T00:03:00.000Z',
})
const candidates = listReversibleTurns(db, 'session', 'workspace')
@@ -454,3 +468,99 @@ it('prunes only long-consumed notices and keeps the dedup rows', async () => {
await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
}
})
+
+it('completes an interrupted turn undo in one transaction', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-interrupted-undo-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, { turnId: 'session:9', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/i1-before' })
+ settleInterruptedTurn(db, 'session:9', 'refs/turnrewind/i1-after', 'turn ended with error')
+ createOperation(db, { operationId: 'op-int', kind: 'undo', targetTurnId: 'session:9', requestedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/op-before' })
+
+ const outcome = completeUndoTransaction(db, {
+ noticeId: 'n-int',
+ sessionId: 'session',
+ workspaceKey: 'ws',
+ targetTurnId: 'session:9',
+ restoredPaths: ['a.txt'],
+ notRestored: [],
+ operationId: 'op-int',
+ createdAt: '2026-01-01T00:01:00.000Z',
+ })
+ assert.equal(outcome, 'undone')
+ assert.equal(getTurn(db, 'session:9').status, 'undone')
+ const op = db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-int')
+ assert.equal(op.outcome, 'applied')
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})
+
+it('surfaces partial restore failures in operation and notice', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-partial-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, { turnId: 'session:p', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/p-before' })
+ settleTurn(db, 'session:p', 'refs/turnrewind/p-after')
+ createOperation(db, { operationId: 'op-p', kind: 'undo', targetTurnId: 'session:p', requestedAt: '2026-01-01T00:00:00.000Z' })
+
+ completeUndoTransaction(db, {
+ noticeId: 'n-p',
+ sessionId: 'session',
+ workspaceKey: 'ws',
+ targetTurnId: 'session:p',
+ restoredPaths: ['a.txt'],
+ notRestored: [{ path: 'big.bin', reason: 'over the size limit' }],
+ operationId: 'op-p',
+ createdAt: '2026-01-01T00:01:00.000Z',
+ })
+ const op = db.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('op-p')
+ assert.equal(op.outcome, 'applied')
+ assert.match(op.error, /big\.bin \(over the size limit\)/)
+ const notice = db.prepare('SELECT paths_json FROM rewind_notices WHERE notice_id = ?').get('n-p')
+ const paths = JSON.parse(notice.paths_json)
+ assert.deepEqual(paths.sort(), ['a.txt', 'big.bin'])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})
+
+it('lands needs-recovery when the turn state drifted after files were restored', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-mismatch-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, { turnId: 'session:m', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/m-before' })
+ createOperation(db, { operationId: 'op-m', kind: 'undo', targetTurnId: 'session:m', requestedAt: '2026-01-01T00:00:00.000Z' })
+ // Simulate the crash window: files restored on disk, but the turn state
+ // drifted elsewhere. No turn rows may update.
+ db.prepare("UPDATE turns SET status = 'failed' WHERE turn_id = ?").run('session:m')
+
+ assert.throws(
+ () => completeUndoTransaction(db, {
+ noticeId: 'n-m',
+ sessionId: 'session',
+ workspaceKey: 'ws',
+ targetTurnId: 'session:m',
+ restoredPaths: ['a.txt'],
+ notRestored: [],
+ operationId: 'op-m',
+ createdAt: '2026-01-01T00:01:00.000Z',
+ }),
+ /TURN_STATE_MISMATCH/,
+ )
+ const op = db.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('op-m')
+ assert.equal(op.outcome, 'needs-recovery')
+ assert.match(op.error, /TURN_STATE_MISMATCH/)
+ const notices = db.prepare('SELECT COUNT(*) c FROM rewind_notices').get().c
+ assert.equal(notices, 0)
+ assert.deepEqual(listNeedsRecoveryWorkspaces(db), ['ws'])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})
diff --git a/test/ledger.test.js b/test/ledger.test.js
new file mode 100644
index 00000000..0482bca1
--- /dev/null
+++ b/test/ledger.test.js
@@ -0,0 +1,460 @@
+import assert from 'node:assert/strict'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { it } from 'vitest'
+import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'
+
+it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:1',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/turn-session-1-before',
+ })
+ settleTurn(db, 'session:1', 'refs/turnrewind/turn-session-1-after')
+ assert.equal(getTurn(db, 'session:1').status, 'settled')
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:1')
+ assert.equal(getLatestSnapshotRef(db, 'workspace'), 'refs/turnrewind/turn-session-1-after')
+
+ insertTurn(db, {
+ turnId: 'session:2',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/turn-session-2-before',
+ })
+ settleNoopTurn(db, 'session:2', 'refs/turnrewind/turn-session-2-after')
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:1')
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('marks undo and queues its one-time notice atomically', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-undo-notice-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:undo',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/undo-before',
+ })
+ settleTurn(db, 'session:undo', 'refs/turnrewind/undo-after')
+ completeUndoWithNotice(db, 'session:undo', {
+ noticeId: 'notice-undo',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:undo',
+ paths: ['src/reverted.ts'],
+ createdAt: '2026-01-01T00:01:00.000Z',
+ })
+ assert.equal(getTurn(db, 'session:undo').status, 'undone')
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(notices.length, 1)
+ assert.equal(notices[0].notice_id, 'notice-undo')
+ assert.deepEqual(notices[0].paths, ['src/reverted.ts'])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('merges multiple pending rewind notices and delivers them once', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-test-'))
+ const db = openLedger(root)
+ try {
+ queueRewindNotice(db, {
+ noticeId: 'notice-one',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:1',
+ paths: ['src/old.ts'],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ })
+ queueRewindNotice(db, {
+ noticeId: 'notice-two',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:2',
+ paths: ['src/new.ts'],
+ createdAt: '2026-01-01T00:01:00.000Z',
+ })
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(notices.length, 2)
+ assert.deepEqual(notices.map(notice => notice.notice_id), ['notice-one', 'notice-two'])
+ assert.deepEqual(notices.map(notice => notice.turns), [['session:1'], ['session:2']])
+ assert.deepEqual(notices.map(notice => notice.paths), [['src/old.ts'], ['src/new.ts']])
+ assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('records a skipped turn with a single unsupported-workspace heads-up', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-skip-test-'))
+ const db = openLedger(root)
+ try {
+ const turn = {
+ sessionId: 'session',
+ workspaceKey: 'c:\\users\\someone',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ }
+ recordSkippedTurn(db, { ...turn, turnId: 'session:1' }, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
+ recordSkippedTurn(db, { ...turn, turnId: 'session:2' }, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
+ assert.equal(getTurn(db, 'session:1').status, 'skipped')
+ assert.equal(getTurn(db, 'session:2').status, 'skipped')
+ const notices = claimRewindNotices(db, 'session', 'c:\\users\\someone')
+ assert.equal(notices.length, 1)
+ assert.equal(notices[0].kind, 'unsupported')
+ assert.equal(notices[0].reason, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
+ assert.equal(claimRewindNotices(db, 'session', 'c:\\users\\someone').length, 0)
+ recordSkippedTurn(db, { ...turn, turnId: 'session:3' }, 'TURNREWIND_WORKSPACE_TOO_LARGE: budget')
+ assert.equal(db.prepare(`SELECT COUNT(*) AS count FROM rewind_notices WHERE kind = 'unsupported'`).get().count, 1)
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('merges a C-B-A undo sequence into one complete notice', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-cba-test-'))
+ const db = openLedger(root)
+ try {
+ for (const [turnId, time] of [
+ ['session:A', '2026-01-01T00:00:00.000Z'],
+ ['session:B', '2026-01-01T00:01:00.000Z'],
+ ['session:C', '2026-01-01T00:02:00.000Z'],
+ ]) {
+ insertTurn(db, {
+ turnId,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: time,
+ beforeRef: `${turnId}-before`,
+ })
+ settleTurn(db, turnId, `${turnId}-after`)
+ }
+ for (const [turnId, path, time] of [
+ ['session:C', 'c.ts', '2026-01-01T00:03:00.000Z'],
+ ['session:B', 'b.ts', '2026-01-01T00:04:00.000Z'],
+ ['session:A', 'a.ts', '2026-01-01T00:05:00.000Z'],
+ ]) {
+ completeUndoWithNotice(db, turnId, {
+ noticeId: `notice-${turnId}`,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: turnId,
+ paths: [path],
+ createdAt: time,
+ })
+ }
+ const notices = claimRewindNotices(db, 'session', 'workspace')
+ assert.deepEqual(notices.map(notice => notice.turns), [['session:C'], ['session:B'], ['session:A']])
+ assert.deepEqual(notices.map(notice => notice.paths), [['c.ts'], ['b.ts'], ['a.ts']])
+ assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('keeps an interrupted turn reversible when it captured file changes', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-interrupt-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:settled',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/settled-before',
+ })
+ settleTurn(db, 'session:settled', 'refs/turnrewind/settled-after')
+ insertTurn(db, {
+ turnId: 'session:interrupted',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/interrupted-before',
+ })
+ settleInterruptedTurn(
+ db,
+ 'session:interrupted',
+ 'refs/turnrewind/interrupted-after',
+ 'agent became idle after interruption',
+ )
+ assert.equal(getTurn(db, 'session:interrupted').status, 'interrupted')
+ assert.equal(getTurn(db, 'session:interrupted').reversible, 1)
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('selects an interrupted turn after a later turn is undone', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-sequence-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:interrupted',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/interrupted-before',
+ })
+ settleInterruptedTurn(db, 'session:interrupted', 'refs/turnrewind/interrupted-after', 'interrupted')
+ insertTurn(db, {
+ turnId: 'session:later',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/later-before',
+ })
+ settleTurn(db, 'session:later', 'refs/turnrewind/later-after')
+ completeUndoTransaction(db, {
+ noticeId: 'notice-later',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:later',
+ restoredPaths: ['later.txt'],
+ notRestored: [],
+ operationId: 'op-later',
+ createdAt: '2026-01-01T00:02:00.000Z',
+ })
+ assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('redoes an applied undo and queues a redo notice atomically', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-redo-test-'))
+ const db = openLedger(root)
+ try {
+ insertTurn(db, {
+ turnId: 'session:1',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/turn-1-before',
+ })
+ settleTurn(db, 'session:1', 'refs/turnrewind/turn-1-after')
+ createOperation(db, {
+ operationId: 'op-undo',
+ kind: 'undo',
+ targetTurnId: 'session:1',
+ requestedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/operation-op-undo',
+ })
+ settleOperation(db, 'op-undo', 'applied')
+ completeUndoTransaction(db, {
+ noticeId: 'notice-undo',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:1',
+ restoredPaths: ['a.ts'],
+ notRestored: [],
+ operationId: 'op-undo',
+ createdAt: '2026-01-01T00:01:01.000Z',
+ })
+ assert.equal(getTurn(db, 'session:1').status, 'undone')
+ assert.equal(getLatestAppliedUndo(db, 'session', 'workspace').operation_id, 'op-undo')
+
+ // The undo notice is delivered first.
+ const undoNotices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(undoNotices.length, 1)
+ assert.equal(undoNotices[0].kind, 'undo')
+
+ completeRedoWithNotice(db, 'op-undo', 'session:1', {
+ noticeId: 'notice-redo',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:1',
+ paths: ['a.ts'],
+ createdAt: '2026-01-01T00:02:00.000Z',
+ })
+ assert.equal(getTurn(db, 'session:1').status, 'settled')
+ assert.equal(getTurn(db, 'session:1').reversible, 1)
+ // A redone operation is no longer a redo candidate.
+ assert.equal(getLatestAppliedUndo(db, 'session', 'workspace'), undefined)
+
+ const redoNotices = claimRewindNotices(db, 'session', 'workspace')
+ assert.equal(redoNotices.length, 1)
+ assert.equal(redoNotices[0].kind, 'redo')
+ assert.deepEqual(redoNotices[0].paths, ['a.ts'])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('lists reversible turns newest-first and marks dead snapshots skipped', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-deadref-test-'))
+ const db = openLedger(root)
+ try {
+ for (const [turnId, time] of [
+ ['session:1', '2026-01-01T00:00:00.000Z'],
+ ['session:2', '2026-01-01T00:01:00.000Z'],
+ ['session:3', '2026-01-01T00:02:00.000Z'],
+ ]) {
+ insertTurn(db, {
+ turnId,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: time,
+ beforeRef: `refs/turnrewind/turn-${turnId}-before`,
+ })
+ settleTurn(db, turnId, `refs/turnrewind/turn-${turnId}-after`)
+ }
+ completeUndoWithNotice(db, 'session:3', {
+ noticeId: 'notice-3',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:3',
+ paths: ['a.txt'],
+ createdAt: '2026-01-01T00:03:00.000Z',
+ })
+ const candidates = listReversibleTurns(db, 'session', 'workspace')
+ assert.deepEqual(candidates.map(turn => turn.turn_id), ['session:2', 'session:1'])
+ markTurnSnapshotMissing(db, 'session:2')
+ assert.equal(getTurn(db, 'session:2').reversible, 0)
+ assert.match(getTurn(db, 'session:2').error, /snapshot repository was wiped/)
+ assert.deepEqual(listReversibleTurns(db, 'session', 'workspace').map(turn => turn.turn_id), ['session:1'])
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('claims a pending plan exactly once and serializes cancel/apply outcomes', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-plan-claim-test-'))
+ const db = openLedger(root)
+ try {
+ const planId = createPendingPlan(db, {
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ turnId: 'session:1',
+ paths: ['a.txt'],
+ })
+ const first = claimPendingPlan(db, planId, 'session')
+ assert.equal(first.ok, true)
+ assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'applying')
+ assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
+ assert.equal(markPendingPlanCancelled(db, planId, 'session'), false)
+
+ releasePendingPlanClaim(db, planId)
+ assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'pending')
+ const second = claimPendingPlan(db, planId, 'session')
+ assert.equal(second.ok, true)
+ markPendingPlanApplied(db, planId, 'session', 'applied once')
+ assert.deepEqual(getPendingPlanStatus(db, planId, 'session'), { status: 'applied', resultText: 'applied once' })
+ assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
+ }
+ finally {
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('fences applying operations as recovery-required on reopen', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-operation-recovery-test-'))
+ const first = openLedger(root)
+ insertTurn(first, {
+ turnId: 'session:applying',
+ sessionId: 'session',
+ workspaceKey: 'workspace-recovery',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/applying-before',
+ })
+ settleTurn(first, 'session:applying', 'refs/turnrewind/applying-after')
+ createOperation(first, {
+ operationId: 'operation-applying',
+ kind: 'undo',
+ targetTurnId: 'session:applying',
+ requestedAt: '2026-01-01T00:01:00.000Z',
+ beforeRef: 'refs/turnrewind/operation-before',
+ })
+ first.close()
+
+ const reopened = openLedger(root)
+ try {
+ const operation = reopened.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('operation-applying')
+ assert.equal(operation.outcome, 'needs-recovery')
+ assert.match(operation.error, /restarted while the operation was applying/u)
+ assert.deepEqual(listNeedsRecoveryWorkspaces(reopened), ['workspace-recovery'])
+ }
+ finally {
+ reopened.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('marks an interrupted active turn abandoned on reopen', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-recovery-test-'))
+ const first = openLedger(root)
+ insertTurn(first, {
+ turnId: 'session:active',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/active-before',
+ })
+ first.close()
+ const reopened = openLedger(root)
+ try {
+ assert.equal(getTurn(reopened, 'session:active').status, 'abandoned')
+ assert.equal(getTurn(reopened, 'session:active').reversible, 0)
+ }
+ finally {
+ reopened.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('prunes only long-consumed notices and keeps the dedup rows', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-prune-'))
+ try {
+ const db = openLedger(root)
+ db.exec('BEGIN')
+ // Old consumed row (past the cutoff) and a fresh consumed row.
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
+ VALUES ('old', 's1', 'ws1', 't1', '[]', '[]', 'undo', 'consumed', ?, ?)`).run('2020-01-01T00:00:00.000Z', '2020-01-01T00:00:01.000Z')
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
+ VALUES ('fresh', 's2', 'ws1', 't2', '[]', '[]', 'undo', 'consumed', ?, ?)`).run(new Date().toISOString(), new Date().toISOString())
+ // A pending row must survive regardless of age.
+ db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at)
+ VALUES ('pending', 's3', 'ws1', 't3', '[]', '[]', 'unsupported', 'pending', '2020-01-01T00:00:00.000Z')`).run()
+ db.exec('COMMIT')
+
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
+ const removed = pruneConsumedNotices(db)
+ assert.equal(removed, 1)
+ const survivors = db.prepare('SELECT notice_id FROM rewind_notices ORDER BY notice_id').all().map(row => row.notice_id)
+ assert.deepEqual(survivors, ['fresh', 'pending'])
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
+ db.close()
+ }
+ finally {
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})