DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): freeze redo at the entry with its recovery path hardened
yingtianlanc9026680503c
diff --git a/docs/TURN_REWIND_REVIEW_2026-09-03.md b/docs/TURN_REWIND_REVIEW_2026-09-03.mdindex 3b4fa73d..c5606322 100644--- a/docs/TURN_REWIND_REVIEW_2026-09-03.md+++ b/docs/TURN_REWIND_REVIEW_2026-09-03.md@@ -20,6 +20,25 @@因此当前适合继续在可丢弃的测试工作区验证,不建议在真实用户工作区中启用。+## 1.1 修复状态更新(2026-09-04)++本报告发布后,P0 修复已在 `dsh/turnrewind-ts-test` 分支完成并合入主分支,随后进行了复核与补充修复。当前状态:++| 项 | 状态 | 处理方式 |+| --- | --- | --- |+| P0-1 目录递归删除 | ✅ 已修复 | `assertSafePath` 拒绝 workspace 根;restore 只删空目录,非空目录与非普通文件一律拒绝(含 `--force`) |+| P0-2 interrupted turn 账本错误 | ✅ 已修复 | `completeUndoTransaction` 接受 settled/interrupted,`changes !== 1` 即回滚 |+| P0-3 恢复与账本非原子 | ✅ 已修复 | turn/operation/notice 单事务提交,失败落 `needs-recovery` |+| P0-4 redo 无失败恢复 | ✅ 以禁用方式关闭 | **产品决策:redo 功能冻结**。底层加固(applying operation / 失败明细 / needs-recovery 事务)已实现并保留测试,入口在 `applyUndo` 顶部直接拒绝;重新开放只需替换闸门行 |+| P0-5 单路径失败无持久记录 | ✅ 已修复 | `notRestored` 明细写入 `operation.error` 与 notice paths |+| P1-1 ~ P1-5 | ⬜ 未处理 | workspace 持久锁、plan 版本绑定、symlink、mode、TOCTOU(root 拒绝已随 P0-1 落地) |+| P2-5 同步 rev-parse | ✅ 已修复 | 60s TTL 进程级缓存 |+| P2-6 status route 方法限制 | ✅ 已修复 | `jsonRoute` 支持 `methods`,status 限 GET |+| P2-7 客户端样式规范 | ✅ 已修复 | 样式迁移至 css-render 对象树,effect 管理挂载/卸载 |+| P2-1/P2-2/P2-4 | ⬜ 未处理 | 子树 undo、文档冲突、容量治理(README 的 redo 章节已同步本次变更) |++验证:17 个测试文件 / 85 个测试全部通过;typecheck、eslint(0 errors)、build(publint 通过)均绿。附带清理:删除根目录误提交的 `test/ledger.test.js`、去除 `client/index.ts` 中重复的样式挂载 effect。+## 2. 审查范围### 2.1 源码diff --git a/packages/dsh-tauri-turnrewind-ts/README.md b/packages/dsh-tauri-turnrewind-ts/README.mdindex 1c0e1614..dd05cccb 100644--- a/packages/dsh-tauri-turnrewind-ts/README.md+++ b/packages/dsh-tauri-turnrewind-ts/README.md@@ -21,12 +21,12 @@- **两阶段 `/undo`**:先出预览卡(红绿 diff + `+x -y` 徽标 + 文件清单),卡内 ✓/✗ 按钮确认执行或取消——不看预览就不会误执行;计划 5 分钟过期,确认时二次校验磁盘;- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖,并给出「turn 产物 → 当前磁盘」的冲突 diff;- 冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)直接执行;-- `/undo --redo` 重做最近一次已应用的 undo(磁盘在 undo 后被改动则拒绝);+- `/undo --redo`(重做最近一次已应用的 undo)**已禁用**:入口在解析层直接拒绝,底层恢复路径加固代码保留但未开放(见「已禁用:redo」);- 注册人类命令 `/undo`;- `/undo` 默认处理当前会话最新的单个可恢复 turn,也可指定完整 turn ID;- 同一 workspace 的活动 turn 或 undo 操作互斥;-- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;**redo 路径尚未接入该机制**(已知缺陷,功能冻结中,见「已知缺陷:redo」);当前只能先人工检查 workspace,再停止 Host 并使用 purge 工具(见下文「清理已膨胀的快照数据」)清理该 workspace 的 turnrewind 数据后恢复使用;-- 每次 Undo/Redo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;+- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo 与 Redo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;当前只能先人工检查 workspace,再停止 Host 并使用 purge 工具(见下文「清理已膨胀的快照数据」)清理该 workspace 的 turnrewind 数据后恢复使用;+- 每次 Undo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。## 使用方法@@ -60,14 +60,14 @@其他:```text-/undo --redo # 重做最近一次已应用的 undo/undo --cancel <plan-id> # 取消一个待确认的预览计划```-当前不支持:+当前不支持 / 已禁用:```text-/undo --subtree+/undo --redo # 已禁用(功能冻结),入口直接拒绝+/undo --subtree # 未实现```父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。@@ -318,9 +318,13 @@ commit history**如果不希望秘密文件进入快照**:把它们加进源仓库的 ignore 规则(对 git 和本插件同时生效)。也可以在 `/undo --dry-run` 的文件清单里核对实际被追踪的范围。插件仍是实验原型,不应把它当作秘密信息保护工具。-### 已知缺陷:redo(暂缓)+### 已禁用:redo(功能冻结)-`/undo --redo` 的执行段**尚未**接入 operation 记录与失败回滚:执行中任一文件恢复失败(超大文件、目标路径变为 symlink/目录、rename 失败)会留下「部分 redo」状态,无回滚、无 `needs-recovery` 标记,重启后围栏不会拦截该 workspace。该功能目前按计划冻结、后续启用时与 undo 路径对齐(`createOperation` → 失败回滚 → `needs-recovery`)后再开放;在此之前请勿在含 >64 MB 文件或路径状态复杂的 turn 上使用 redo。+`/undo --redo` 已在解析层禁用:任何包含 `--redo` 的输入都会得到「temporarily disabled」错误,不会触发快照校验或文件恢复。++禁用原因(2026-09-03 审查报告 P0-4):redo 的执行段此前未接入 operation 记录与失败回滚,执行中任一文件恢复失败会留下「部分 redo」状态,无 `needs-recovery` 围栏。++底层加固已经完成并保留(未开放):redo 现在与 undo 共用同一套机制——`createOperation` 登记 applying operation → 单路径失败计入 `notRestored` 明细 → `completeRedoTransaction` 在单事务内结算旧 undo operation / turn / 新 operation / notice,事务失败时 redo operation 落 `needs-recovery` 由启动围栏拦截。重新开放只需移除 `parseUndoInput` 中的 `--redo` 拒绝分支并恢复对应测试。## Debug 安装@@ -357,4 +361,4 @@ pnpm --filter dsh-tauri-turnrewind test- 实现父对话递归 undo;- 实现消息旁 Undo 按钮;- 明确二进制、重命名、权限位和特殊文件策略;-- redo 执行段接入 operation 记录与失败回滚(见「已知缺陷:redo」)。+- 重新开放 redo:移除解析层禁用分支、恢复端到端 redo 测试(底层加固已完成,见「已禁用:redo」)。diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts b/packages/dsh-tauri-turnrewind-ts/src/client/index.tsindex 206733f9..711fd594 100644--- a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/client/index.ts@@ -39,7 +39,6 @@ export function apply(ctx: ClientContext): void {// 样式挂载:css-render 对象树,apply 生命周期内挂载/卸载。ctx.effect(() => mountDialogStyles(), 'turnrewind dialog styles')ctx.effect(() => mountCommandViewStyles(), 'turnrewind command-view styles')- ctx.effect(() => mountCommandViewStyles(), 'turnrewind command-view styles')const t = (key: LocaleKey): string => {const active = locale.getLocale().activediff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.tsindex 08d42045..9922a562 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts@@ -501,15 +501,6 @@ export function pruneConsumedNotices(db: Ledger, maxAgeMs: number = 7 * 24 * 60return Number(db.prepare('DELETE FROM rewind_notices WHERE status = \'consumed\' AND claimed_at < ?').run(cutoff).changes)}-export interface UndoNoticeInput {- noticeId: string- sessionId: string- workspaceKey: string- targetTurnId: string- paths: string[]- createdAt: string-}-/** undo 完成事务:turn → undone、operation → applied、notice 入队。 */export interface UndoCompletion {noticeId: string@@ -576,29 +567,76 @@ export function completeUndoTransaction(db: Ledger, completion: UndoCompletion):}}-/** redo 完成事务:旧 undo operation → redone、turn 回 settled、notice 入队。 */-export function completeRedoWithNotice(db: Ledger, operationId: string, turnId: string, notice: UndoNoticeInput): void {+/** redo 完成事务的输入:旧 undo operation + 本次 redo 自己的 applying operation。 */+export interface RedoCompletion {+ noticeId: string+ sessionId: string+ workspaceKey: string+ targetTurnId: string+ /** 被重做的旧 undo operation(applied 状态)。 */+ redoneOperationId: string+ /** 本次 redo 登记的 operation(applying 状态)。 */+ operationId: string+ restoredPaths: string[]+ /** 重做失败的单路径清单(含原因),随 operation.error 与 notice 持久化。 */+ notRestored: { path: string, reason: string }[]+ createdAt: string+}++/**+ * 完成一次 redo 的唯一入口:单事务内校验并落旧 operation/turn/新 operation/notice。+ *+ * - 旧 undo operation 只能从 applied → redone,turn 只能从 undone → settled,+ * 任一 UPDATE 命中数 !== 1 即状态漂移:事务回滚且本次 redo operation 落+ * needs-recovery,交给启动围栏拦截该 workspace(与 undo 路径对等,P0-4);+ * - 未恢复路径写入 operation.error 与 notice,部分重做同样留下持久审计。+ */+export function completeRedoTransaction(db: Ledger, completion: RedoCompletion): 'settled' | 'needs-recovery' {+ const summary = completion.notRestored.length > 0+ ? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')+ : nulldb.exec('BEGIN')try {- db.prepare('UPDATE operations SET outcome = \'redone\', settled_at = ? WHERE operation_id = ?')- .run(new Date().toISOString(), operationId)- db.prepare('UPDATE turns SET status = \'settled\', reversible = 1 WHERE turn_id = ? AND status = \'undone\'').run(turnId)+ const previous = db.prepare(`+ UPDATE operations SET outcome = 'redone', settled_at = ?+ WHERE operation_id = ? AND kind = 'undo' AND outcome = 'applied'+ `).run(new Date().toISOString(), completion.redoneOperationId)+ if (previous.changes !== 1)+ throw new Error(`OPERATION_STATE_MISMATCH: undo operation ${completion.redoneOperationId} is no longer applied`)+ const turn = db.prepare(`+ UPDATE turns SET status = 'settled', reversible = 1, settled_at = ?+ WHERE turn_id = ? AND status = 'undone'+ `).run(new Date().toISOString(), completion.targetTurnId)+ if (turn.changes !== 1)+ throw new Error(`TURN_STATE_MISMATCH: turn ${completion.targetTurnId} is not undone`)+ 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', ?, 'redo')`).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 'settled'}catch (error) {db.exec('ROLLBACK')+ // 账本未能完成:redo 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.tsindex d5e99679..e2fb7fa9 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts@@ -36,7 +36,7 @@ import { isSystemSensitiveWorkspace } from './guard'import {claimPendingPlan,- completeRedoWithNotice,+ completeRedoTransaction,completeUndoTransaction,createOperation,createPendingPlan,@@ -53,7 +53,7 @@ import {import { classifyUndo } from './planner'-// ————————————————— redo(与 JS 版同语义;生产加固仍为待办) —————————————————+// ————————————————— redo(与 undo 同等的生产加固:applying operation / 失败明细 / needs-recovery) —————————————————async function applyRedo(runtime: WorkspaceRuntime, invocation: UndoInvocation, workspaceDir: string, workspaceKey: string): Promise<UndoOutcome> {const op = getLatestAppliedUndo(runtime.db, invocation.agent.session.id, workspaceKey)@@ -93,18 +93,48 @@ async function applyRedo(runtime: WorkspaceRuntime, invocation: UndoInvocation,const operationId = randomUUID()const beforeRef = `refs/turnrewind/redo-${operationId}`await captureSnapshot(runtime.store, beforeRef, `turnrewind redo ${turn.turn_id}`, runtime.parentRef)- for (const path of paths)- await restorePath(runtime.store, turn.after_ref, path)- completeRedoWithNotice(runtime.db, op.operation_id, turn.turn_id, {+ // redo 与 undo 对等:先登记 applying operation,崩溃/账本失败时由+ // needs-recovery 围栏接管,不再留下无围栏的部分 redo(P0-4)。+ createOperation(runtime.db, {+ operationId,+ kind: 'redo',+ targetTurnId: turn.turn_id,+ requestedAt: new Date().toISOString(),+ beforeRef,+ })+ const restoredPaths: string[] = []+ const failedPaths: { path: string, reason: string }[] = []+ for (const path of paths) {+ try {+ await restorePath(runtime.store, turn.after_ref, path)+ restoredPaths.push(path)+ }+ catch (error) {+ // 与 undo 相同的单路径策略:一个文件失败不炸整体,失败明细持久化。+ failedPaths.push({ path, reason: String((error as Error).message ?? error) })+ }+ }+ completeRedoTransaction(runtime.db, {noticeId: randomUUID(),sessionId: invocation.agent.session.id,workspaceKey,targetTurnId: turn.turn_id,- paths,+ redoneOperationId: op.operation_id,+ operationId,+ restoredPaths,+ notRestored: failedPaths,createdAt: new Date().toISOString(),})runtime.parentRef = beforeRef- return { kind: 'success', text: `re-applied ${paths.length} file(s). The next model request will receive a rewind notice.` }+ let text = `re-applied ${restoredPaths.length} file(s). The next model request will receive a rewind notice.`+ if (failedPaths.length > 0)+ 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 { kind: 'success', text }+ }+ catch (error) {+ // completeRedoTransaction 已把本次 redo operation 落 needs-recovery,+ // 启动围栏会拦截该 workspace;这里只负责把原因带给用户。+ return { kind: 'error', text: String((error as Error)?.message ?? error) }}finally {runtime.undoing = false@@ -486,6 +516,11 @@ export async function applyUndo(const parsed = parseUndoInput(invocation.rawInput)if ('error' in parsed)return { kind: 'error', text: parsed.error }+ // 功能冻结闸门(2026-09-03 审查 P0-4 决策):redo 先禁用、暂不开放。+ // 底层加固已落地并保留测试(applying operation / 失败明细 / needs-recovery+ // 事务),重新开放时把本分支换回 `return applyRedo(...)` 即可。+ if (parsed.redo)+ return { kind: 'error', text: '/undo --redo is temporarily disabled. The most recent undo cannot be re-applied for now.' }const workspaceDir = env.workspaceForAgent(invocation.agent)if (!workspaceDir) {diff --git a/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js b/packages/dsh-tauri-turnrewind-ts/test/ledger.test.jsindex 89a4683c..341fb112 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, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleTurn } from '../src/host/service/ledger'+import { claimPendingPlan, claimRewindNotices, completeRedoTransaction, 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-'))@@ -289,19 +289,30 @@ it('redoes an applied undo and queues a redo notice atomically', async () => {assert.equal(undoNotices.length, 1)assert.equal(undoNotices[0].kind, 'undo')- completeRedoWithNotice(db, 'op-undo', 'session:1', {+ createOperation(db, {+ operationId: 'op-redo',+ kind: 'redo',+ targetTurnId: 'session:1',+ requestedAt: '2026-01-01T00:02:00.000Z',+ beforeRef: 'refs/turnrewind/redo-op-redo',+ })+ completeRedoTransaction(db, {noticeId: 'notice-redo',sessionId: 'session',workspaceKey: 'workspace',targetTurnId: 'session:1',- turns: ['session:1'],- paths: ['a.ts'],+ redoneOperationId: 'op-undo',+ operationId: 'op-redo',+ restoredPaths: ['a.ts'],+ notRestored: [],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)+ // The redo itself is recorded as an applied operation.+ assert.equal(db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-redo').outcome, 'applied')const redoNotices = claimRewindNotices(db, 'session', 'workspace')assert.equal(redoNotices.length, 1)@@ -314,6 +325,74 @@ it('redoes an applied undo and queues a redo notice atomically', async () => {}})+it('fences a redo whose undo operation is no longer applied as needs-recovery', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-redo-fence-test-'))+ const db = openLedger(root)+ try {+ insertTurn(db, {+ turnId: 'session:1',+ sessionId: 'session',+ workspaceKey: 'workspace-fence',+ 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',+ })+ // The undo transaction completes: turn is undone, old op applied.+ completeUndoTransaction(db, {+ noticeId: 'notice-undo',+ sessionId: 'session',+ workspaceKey: 'workspace-fence',+ targetTurnId: 'session:1',+ restoredPaths: ['a.ts'],+ notRestored: [],+ operationId: 'op-undo',+ createdAt: '2026-01-01T00:01:00.000Z',+ })+ // Consume the legitimate undo notice so the final assertion can require+ // that no ADDITIONAL (redo) notice leaked from the failed transaction.+ assert.equal(claimRewindNotices(db, 'session', 'workspace-fence').length, 1)+ createOperation(db, {+ operationId: 'op-redo',+ kind: 'redo',+ targetTurnId: 'session:1',+ requestedAt: '2026-01-01T00:02:00.000Z',+ })+ // Another writer flipped the old undo operation out from under us: the+ // redo must roll back and fence this workspace via needs-recovery.+ settleOperation(db, 'op-undo', 'rolled_back')+ assert.throws(+ () => completeRedoTransaction(db, {+ noticeId: 'notice-redo',+ sessionId: 'session',+ workspaceKey: 'workspace-fence',+ targetTurnId: 'session:1',+ redoneOperationId: 'op-undo',+ operationId: 'op-redo',+ restoredPaths: ['a.ts'],+ notRestored: [],+ createdAt: '2026-01-01T00:02:00.000Z',+ }),+ /OPERATION_STATE_MISMATCH/u,+ )+ // The redo operation was fenced; the workspace lands in the recovery list.+ assert.equal(db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-redo').outcome, 'needs-recovery')+ assert.deepEqual(listNeedsRecoveryWorkspaces(db), ['workspace-fence'])+ // Nothing from the failed transaction leaked: turn is still undone, no redo notice.+ assert.equal(getTurn(db, 'session:1').status, 'undone')+ assert.equal(claimRewindNotices(db, 'session', 'workspace-fence').length, 0)+ }+ 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)diff --git a/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js b/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.jsindex 7ca04fed..b4495c0a 100644--- a/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js+++ b/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js@@ -107,47 +107,21 @@ it('forces a restore over a conflicted file', async () => {}})-it('round-trips undo and redo', { timeout: 30000 }, async () => {+it('applies a confirmed undo and reports redo as disabled', { timeout: 30000 }, async () => {const { root, workspace, db, runtime, active, invocation } = await setupTurn()try {const undo = await undoWithConfirm(runtime, active, invocation)assert.equal(undo.kind, 'success')assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')await assert.rejects(stat(join(workspace, 'c.txt')))+ assert.equal(getTurn(db, 'session:1').status, 'undone')- const redo = await applyUndo(runtime, active, invocation('--redo'))- assert.equal(redo.kind, 'success')- assert.match(redo.text, /re-applied 2 file\(s\)/u)- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')- assert.equal(await readFile(join(workspace, 'c.txt'), 'utf8'), 'new\n')- assert.equal(getTurn(db, 'session:1').status, 'settled')-- // The turn is reversible again after the redo.- const undoAgain = await undoWithConfirm(runtime, active, invocation)- assert.equal(undoAgain.kind, 'success')- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')-- // A second redo targets the new undo operation.- const redoAgain = await applyUndo(runtime, active, invocation('--redo'))- assert.equal(redoAgain.kind, 'success')- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')- }- finally {- db.close()- await rm(root, { recursive: true, force: true })- }-})--it('blocks redo when the disk changed after the undo', async () => {- const { root, workspace, db, runtime, active, invocation } = await setupTurn()- try {- const undo = await undoWithConfirm(runtime, active, invocation)- assert.equal(undo.kind, 'success')- await writeFile(join(workspace, 'a.txt'), 'edited-after-undo\n')+ // Redo is frozen at the parser: even with a clean workspace the entry+ // refuses before any snapshot/conflict work happens.const redo = await applyUndo(runtime, active, invocation('--redo'))assert.equal(redo.kind, 'error')- assert.match(redo.text, /Redo is blocked/u)- assert.match(redo.text, /\+edited-after-undo/u)+ assert.match(redo.text, /temporarily disabled/u)+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')assert.equal(getTurn(db, 'session:1').status, 'undone')}finally {diff --git a/test/ledger.test.js b/test/ledger.test.jsdeleted file mode 100644index 0482bca1..00000000--- a/test/ledger.test.js+++ /dev/null@@ -1,460 +0,0 @@-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 })- }-})