DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): atomic restore via bak-swap with startup sweep
yingtianlan5cea66b461b0
diff --git a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md b/docs/TURN_REWIND_GIT_DIR_PROGRESS.mdindex e95fdd4a..21a3f3a3 100644--- a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md+++ b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md@@ -105,6 +105,15 @@ Failed: 0- rewind_notices 膨胀:新增 pruneConsumedNotices(consumed 且 claimed_at > 7 天删除,保留 pending 与近期行以维持 unsupported 弹窗去重语义),插件启动时执行一次;- 「git 全程异步」措辞修正为「git 子进程模型」,如实标注两处同步路径(工作区解析 spawnSync、冲突检测同步读盘)与异步化待办。+### 原子替换已落地(2026-09-02 第三批)++- restorePath 从「删除→改名」改为 **bak-swap 原子替换**:目标先改名为 .turnrewind-restore.bak(同卷原子),临时文件再改名就位,成功后才删 bak——崩溃窗口内磁盘上始终保有完整副本(新内容或 bak 之一),文件不再可能凭空消失;+- 二次 rename 失败时自愈回滚(bak 改回目标);+- 启动清扫 restoreCrashedSwaps:挂在 ensureRuntime 首次接触 workspace 时执行——目标缺失 + bak 在场 → 复活旧内容(日志告警);目标在场 + bak 在场 → 清 debris;+- 快照排除规则新增 *.turnrewind-restore.bak,防止崩溃残留被下次 capture 吸进快照进而被 undo 复活;+- Windows 实测发现并修复竞态:Defender/索引器对新鲜文件短暂持锁(EPERM/EBUSY)会打断 bak 的 rename/delete——rmSyncWithRetry + sweep 重试(30ms x 5);该竞态此前也是 oversize 测试偶发失败的根因;+- 4 个新测试:干净恢复零残留、crash 窗口复活(含嵌套目录)、debris 清扫、bak 不进快照。回归 17 文件 / 82 测试全绿。+### 可选优化1. 连通性检查的性能优化:当前每次 capture 走全链 `rev-list`(O(链上对象总数))。优化方向:常态走 `--not <parent>` 的增量检查 + 源对象库 mtime 变化时触发全链检查。大仓库上需先实测 capture 耗时;diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.jsindex bb827147..98160b91 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js@@ -1,7 +1,7 @@import { Buffer } from 'node:buffer'import { spawn } from 'node:child_process'import { createHash, randomUUID } from 'node:crypto'-import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { dirname, join, relative, resolve, sep } from 'node:path'import process from 'node:process'@@ -19,6 +19,7 @@ const SNAPSHOT_PATHSPECS = [':(exclude,glob).turnrewind/**',':(exclude,glob)**/.turnrewind/**',':(exclude,glob)**/*.turnrewind-*.tmp',+ ':(exclude,glob)**/*.turnrewind-restore.bak',]const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'@@ -587,6 +588,43 @@ export function currentState(workspaceDir, path) {return { kind: 'file', digest: digest(readFileSync(target)) }}+/**+ * Crash-safe restore window. The pre-atomic sequence was delete-then-rename:+ * a crash between those two steps left the target missing and its only copy+ * in a .tmp file nobody resurrected. The swap keeps a full copy on disk at+ * every instant:+ *+ * target -> target.turnrewind-restore.bak (rename, atomic)+ * temp -> target (rename, atomic)+ * bak -> deleted (only after success)+ *+ * A crash anywhere leaves either the new content or the .bak; the startup+ * sweep (restoreCrashedSwaps) resurrects a .bak whose target is missing.+ */+const BAK_SUFFIX = '.turnrewind-restore.bak'++/**+ * Remove one path, retrying briefly: Windows antivirus/indexers hold+ * short-lived handles on freshly written files, and a transient EPERM/EBUSY+ * on the .bak delete must not fail an otherwise successful restore.+ */+function rmSyncWithRetry(target, attempts = 5) {+ for (let attempt = 0; ; attempt += 1) {+ try {+ rmSync(target, { force: true })+ return+ }+ catch (error) {+ const retryable = error?.code === 'EBUSY' || error?.code === 'EPERM' || error?.code === 'EACCES'+ if (retryable && attempt < attempts) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30)+ continue+ }+ throw error+ }+ }+}+export async function restorePath(store, commit, path) {const target = assertSafePath(store.workspaceDir, path)if (!await commitEntry(store, commit, path)) {@@ -608,14 +646,40 @@ export async function restorePath(store, commit, path) {mkdirSync(dirname(target), { recursive: true })const temp = `${target}.turnrewind-${randomUUID()}.tmp`writeFileSync(temp, bytes, { flag: 'wx' })+ let baktry {if (existsSync(target)) {const info = lstatSync(target)if (info.isSymbolicLink() || !info.isFile())throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)- rmSync(target, { force: true })+ // Move the old content aside instead of deleting it: the swap keeps a+ // complete copy on disk across both renames.+ bak = `${target}${BAK_SUFFIX}`+ rmSync(bak, { force: true })+ renameSync(target, bak)+ }+ try {+ renameSync(temp, target)}- renameSync(temp, target)+ catch (error) {+ // The swap failed halfway: put the old content back before reporting.+ if (bak !== undefined) {+ try {+ if (!existsSync(target))+ renameSync(bak, target)+ else+ rmSync(bak, { force: true })+ }+ catch { /* best-effort self-heal; a leftover .bak stays recoverable */ }+ }+ throw error+ }+ // New content is in place; the old copy is now redundant. The delete is+ // retried: a transient antivirus handle on the fresh .bak must not turn+ // a completed restore into a reported failure (the sweep cleans a+ // leftover .bak anyway).+ if (bak !== undefined)+ rmSyncWithRetry(bak)}catch (error) {rmSync(temp, { force: true })@@ -624,6 +688,59 @@ export async function restorePath(store, commit, path) {return { path, result: 'restored' }}+/**+ * Startup sweep for atomic-swap leftovers. A .turnrewind-restore.bak next to+ * a missing target means the process died between the two renames: resurrect+ * the old content. A .bak next to an existing target is debris from a crash+ * after the second rename (before the delete) - safe to remove. Returns the+ * resurrected workspace-relative paths for logging.+ */+export function restoreCrashedSwaps(workspaceDir) {+ const root = resolve(workspaceDir)+ const resurrected = []+ const visit = (dir) => {+ let entries+ try {+ entries = readdirSync(dir, { withFileTypes: true })+ }+ catch {+ return+ }+ for (const entry of entries) {+ const full = join(dir, entry.name)+ if (entry.isDirectory() && entry.name !== '.git' && !entry.name.endsWith('.turnrewind-restore.bak'))+ visit(full)+ if (entry.isFile() && entry.name.endsWith('.turnrewind-restore.bak')) {+ const target = full.slice(0, -BAK_SUFFIX.length)+ // Windows antivirus/indexers hold brief handles on freshly renamed+ // files; retry a few times before giving this bak up to the fence.+ for (let attempt = 0; ; attempt += 1) {+ try {+ if (!existsSync(target)) {+ renameSync(full, target)+ resurrected.push(relative(root, target))+ }+ else {+ rmSync(full, { force: true })+ }+ break+ }+ catch (error) {+ const retryable = error?.code === 'EBUSY' || error?.code === 'EPERM' || error?.code === 'EACCES'+ if (retryable && attempt < 5) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30)+ continue+ }+ break // deeper damage: leave for the recovery fence+ }+ }+ }+ }+ }+ visit(root)+ return resurrected+}+export function pathIsSafe(workspaceDir, path) {try {assertSafePath(workspaceDir, path)diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.jsindex 76e0c53a..0a8ed794 100644--- a/plugins/dsh-tauri-turnrewind/lib/index.js+++ b/plugins/dsh-tauri-turnrewind/lib/index.js@@ -4,7 +4,7 @@ import { homedir } from 'node:os'import { join, resolve } from 'node:path'import process from 'node:process'import { createDialogProjection } from './core/dialog-projection.js'-import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, MAX_FILE_BYTES, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'+import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, MAX_FILE_BYTES, probeWorkspace, restoreCrashedSwaps, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'import { isSystemSensitiveWorkspace } from './core/guard.js'import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'import { classifyUndo } from './core/planner.js'@@ -870,6 +870,13 @@ function apply(ctx) {const store = createSnapshotStore(dataRoot, workspaceDir)const latest = getLatestSnapshotRef(ledger, workspaceKey)registerWorkspace(ledger, workspaceKey, workspaceDir, store.repoDir)+ // First touch since plugin start: resurrect files left mid-swap by a+ // crash in a previous host process (target missing + .bak present)+ // and clear debris (target present + .bak present) - both shapes only+ // exist inside the atomic-restore crash window.+ const resurrected = restoreCrashedSwaps(workspaceDir)+ for (const path of resurrected)+ console.warn(`turnrewind: resurrected ${path} in ${workspaceDir} from a crashed restore swap`)runtime = {db: ledger,store,diff --git a/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.js b/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.jsnew file mode 100644index 00000000..1cfb3f65--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.js@@ -0,0 +1,97 @@+import assert from 'node:assert/strict'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join, sep } from 'node:path'+import { it } from 'vitest'+import { captureSnapshot, createSnapshotStore, restoreCrashedSwaps, restorePath, stateAt } from '../lib/core/git-snapshot.js'+import { initGitWorkspace } from './git-test-utils.js'++it('restores without leaving any swap debris', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, 'a.txt'), 'v1\n')+ const store = createSnapshotStore(join(root, 'data'), workspace)+ const before = await captureSnapshot(store, 'refs/turnrewind/atomic-1', 'before')+ await writeFile(join(workspace, 'a.txt'), 'v2\n')+ await captureSnapshot(store, 'refs/turnrewind/atomic-2', 'after', 'refs/turnrewind/atomic-1')++ await restorePath(store, before.commit, 'a.txt')+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')+ // No .bak, no .tmp anywhere in the workspace after a clean restore.+ const leftovers = (await readdir(join(workspace))).filter(name => name.includes('turnrewind'))+ assert.deepEqual(leftovers, [])+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})++it('the startup sweep resurrects a target lost mid-swap', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-bak-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, 'a.txt'), 'old content\n')+ // Simulate the crash window: the target was renamed aside, the second+ // rename never happened, so only the .bak exists.+ await mkdir(join(workspace, 'nested'), { recursive: true })+ await writeFile(join(workspace, 'nested', 'b.txt'), 'nested old\n')+ await rename(join(workspace, 'a.txt'), join(workspace, 'a.txt.turnrewind-restore.bak'))+ await rename(join(workspace, 'nested', 'b.txt'), join(workspace, 'nested', 'b.txt.turnrewind-restore.bak'))+ assert.equal(existsSync(join(workspace, 'a.txt')), false)++ const resurrected = restoreCrashedSwaps(workspace)+ assert.deepEqual(resurrected.map(path => path.split(sep).join('/')).sort(), ['a.txt', 'nested/b.txt'])+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'old content\n')+ assert.equal(await readFile(join(workspace, 'nested', 'b.txt'), 'utf8'), 'nested old\n')+ // The workspace is clean again - no bak files remain.+ assert.equal(existsSync(join(workspace, 'a.txt.turnrewind-restore.bak')), false)+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})++it('the startup sweep removes debris when the target survived', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-debris-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ // Crash happened after the second rename, before the bak delete: the new+ // content is in place and the bak is redundant.+ await writeFile(join(workspace, 'a.txt'), 'new content\n')+ await writeFile(join(workspace, 'a.txt.turnrewind-restore.bak'), 'old content\n')++ const resurrected = restoreCrashedSwaps(workspace)+ assert.deepEqual(resurrected, [])+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'new content\n')+ assert.equal(existsSync(join(workspace, 'a.txt.turnrewind-restore.bak')), false)+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})++it('a leftover .bak never enters a snapshot', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-snap-'))+ const workspace = join(root, 'workspace')+ try {+ await initGitWorkspace(workspace)+ await writeFile(join(workspace, 'a.txt'), 'a\n')+ // A bak left by a crashed swap sits next to a missing target.+ await writeFile(join(workspace, 'lost.txt.turnrewind-restore.bak'), 'lost old\n')++ const store = createSnapshotStore(join(root, 'data'), workspace)+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/atomic-snap', 'snap')+ // The bak must not be tracked: restoring it as a normal path would+ // resurrect debris into the workspace on a later undo.+ assert.equal((await stateAt(store, snapshot.commit, 'lost.txt.turnrewind-restore.bak')).kind, 'absent')+ assert.equal((await stateAt(store, snapshot.commit, 'a.txt')).kind, 'file')+ }+ finally {+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })+ }+})