Skip to content

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

fix(turnrewind): run git async and self-heal broken snapshot chains

yingtianlanf2d24370f16d
diff --git a/docs/TURN_REWIND.md b/docs/TURN_REWIND.md
index 2cc5259c..54b5603e 100644
--- a/docs/TURN_REWIND.md
+++ b/docs/TURN_REWIND.md
@@ -246,6 +246,16 @@ operation_paths(operation_id, path, expected_current_digest,
预扫描是同步、带早停的元数据遍历,只发生在 turn 领取时;即使面对 250 GB 目录,代价也是一次有界的扫描而不是全量哈希。配套提供 `purge-workspace` 维护命令,用于清掉旧版本在错误工作区上生成的快照仓库与账本记录。
+### 5.4 Git 执行模型(已落地)
+
+首版用 `spawnSync` 执行全部 git 命令,大工作区上会冻结整个 Host(所有会话、Web UI、健康检查),叠加 Windows Defender 实时扫描时可达分钟级。现已全部改为异步 `spawn`:
+
+- 同一会话的捕获、结算按 FIFO 链串行,`turn/end` 的结算自动排队在基线捕获之后;不同会话之间并行;
+- `agent/inbox/claimed` 同步占位 active 表条目,保证异步基线捕获期间 `/undo` 无法插入;
+- 命令 handler 返回 Promise(内核以 `Promise.resolve(output)` 结算),`/undo` 的 diff、冲突检测与恢复均异步执行;
+- git 可用性在进程内探测一次,缺失时 turn 显式记为 `skipped`(`TURNREWIND_GIT_UNAVAILABLE`),不再静默失败;
+- `parentRef` 指向的快照不存在时(快照目录被清理/损坏),捕获降级为无父基线并在日志留一条 warning,快照链自愈而不是级联失败。
+
## 6. 撤销语义
### 6.1 默认单回合 Undo
@@ -564,7 +574,7 @@ Agent 文本回复成功不是「可撤销」的判断标准;只有结算扫
- 大仓库索引优化、排除规则;
- Git 仓库工作区的增量基线(参考 OpenCode:共享用户仓库 object database、按 `git status` 语义只 stage 变更路径、未跟踪大文件写入快照仓库 `info/exclude`);
-- 快照/恢复全链路异步化,避免阻塞 Host 事件循环;
+- snapshot ref 的数量/容量/保留期治理与定期 gc。
- 配额与 GC;
- worktree 专用恢复域与 UI 状态;
- 诊断页和可导出审计。
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
index 4df7e07a..5c590336 100644
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@ -10,6 +10,9 @@
- 为已领取的 Agent turn 建立私有 Git 快照;
- 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
+- **git 全程异步执行**:快照、diff、恢复都不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行,不同会话并行;
+- **git 可用性探测**:系统没有 git 时,turn 显式记为 `skipped`(原因 `TURNREWIND_GIT_UNAVAILABLE`),而不是静默失败;
+- **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;
- **工作区资格守卫**:家目录、家目录的祖先、盘根目录,以及超过快照预算(文件数 / 总大小 / 单文件大小)的目录不做快照,turn 记为 `skipped` 并向 `/undo` 说明原因(见「工作区资格与快照预算」);
- **不可用弹窗**:客户端半(`lib/client.js`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、每个浏览器只弹一次);
- 注册人类命令 `/undo`;
@@ -295,11 +298,15 @@ coverage/
*.pem
*.key
id_rsa*
-credentials*
-*secret*
-*token*
+credentials.* # 仅根目录
+secrets.* # 仅根目录
```
+注意两点边界:
+
+- 工作区自己的 `.gitignore` 和用户全局 gitignore 同样生效(`git add` 语义),被忽略的文件不会进入快照,也不会被 undo 恢复;
+- 曾经使用的 `*token*`、`*secret*` 等子串规则已移除——它们会静默排除 `token.ts`、`tokenizer.py` 这类正当源码,且被排除路径不出现在 dry-run 列表中,导致 undo 静默漏恢复。
+
这些规则意味着:被排除文件的变化不会进入本 turn 的 Undo 范围。插件仍是实验原型,不应把它当作秘密信息保护工具。
## Debug 安装
@@ -331,11 +338,10 @@ pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
- 接入受控的宿主 sandbox/Tauri bridge;
- 完成 DSH lifecycle integration tests;
-- 快照/扫描改为异步执行(当前 `spawnSync` 会阻塞 Host 事件循环);
+- 快照容量治理:按 turn 数/容量/保留期清理旧 snapshot ref(当前只做断链自愈,不清理历史);
- 完善 Git 仓库工作区的增量基线(参考 OpenCode:共享用户对象库 + 仅 stage 变更路径);
- 完善多 workspace 并发锁;
- 实现父对话递归 undo;
- 实现 redo 和冲突处理 UI;
- 实现消息旁 Undo 按钮;
-- 增加 snapshot 数量/容量清理;
- 明确二进制、重命名、权限位和特殊文件策略。
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index 6bbd2178..4fbefd41 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@ -1,4 +1,5 @@
-import { spawnSync } from 'node:child_process'
+import { Buffer } from 'node:buffer'
+import { spawn } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve, sep } from 'node:path'
@@ -6,6 +7,12 @@ import process from 'node:process'
import { TextDecoder, TextEncoder } from 'node:util'
const MAX_FILE_BYTES = 64 * 1024 * 1024
+const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
+
+// Only high-confidence sensitive names are excluded: substring rules like
+// *token* silently dropped legitimate source files (token.ts and friends) from
+// snapshots, so undo could never restore them — not even the dry-run showed
+// them, because excluded paths never enter the before/after diff.
const EXCLUDE_PATHS = [
':(exclude,glob).git/**',
':(exclude,glob)**/.git/**',
@@ -27,47 +34,110 @@ const EXCLUDE_PATHS = [
':(exclude,glob)**/*.key',
':(exclude,glob)id_rsa*',
':(exclude,glob)**/id_rsa*',
- ':(exclude,glob)credentials*',
- ':(exclude,glob)**/credentials*',
- ':(exclude,glob)*secret*',
- ':(exclude,glob)**/*secret*',
- ':(exclude,glob)*token*',
- ':(exclude,glob)**/*token*',
+ ':(exclude,glob)credentials.*',
+ ':(exclude,glob)secrets.*',
]
-function runGit(repoDir, workspaceDir, args, extraEnv = {}) {
- const result = spawnSync('git', ['-c', 'core.quotepath=false', '--git-dir', repoDir, '--work-tree', workspaceDir, ...args], {
- cwd: workspaceDir,
- encoding: 'utf8',
- env: { ...process.env, ...extraEnv },
- maxBuffer: 16 * 1024 * 1024,
+/**
+ * Run one git command without blocking the host event loop. All snapshot I/O
+ * used to be synchronous, which froze the whole host — every session, the web
+ * UI and the health check — for the duration of `git add` on big workspaces.
+ */
+function runGit(repoDir, workspaceDir, args, extraEnv = {}, maxBytes = MAX_OUTPUT_BYTES) {
+ return new Promise((resolvePromise, rejectPromise) => {
+ const child = spawn('git', ['-c', 'core.quotepath=false', '--git-dir', repoDir, '--work-tree', workspaceDir, ...args], {
+ cwd: workspaceDir,
+ env: { ...process.env, ...extraEnv },
+ })
+ const chunks = []
+ const errors = []
+ let total = 0
+ let settled = false
+
+ const fail = (error) => {
+ if (settled)
+ return
+ settled = true
+ child.kill()
+ rejectPromise(error)
+ }
+ child.stdout.on('data', (chunk) => {
+ if (settled)
+ return
+ total += chunk.length
+ if (total > maxBytes) {
+ fail(new Error(`TURNREWIND_OUTPUT_TOO_LARGE: git output exceeded ${maxBytes} bytes`))
+ return
+ }
+ chunks.push(chunk)
+ })
+ child.stderr.on('data', (chunk) => {
+ if (!settled)
+ errors.push(chunk)
+ })
+ child.on('error', error => fail(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
+ child.on('close', (code) => {
+ if (settled)
+ return
+ settled = true
+ const stdout = Buffer.concat(chunks)
+ if (code !== 0) {
+ const detail = Buffer.concat(errors).toString('utf8').trim() || stdout.toString('utf8').trim() || `exit ${code}`
+ rejectPromise(new Error(`TURNREWIND_GIT_FAILED: ${detail}`))
+ return
+ }
+ resolvePromise(stdout)
+ })
})
- if (result.error)
- throw new Error(`TURNREWIND_GIT_EXEC: ${result.error.message}`)
- if (result.status !== 0) {
- throw new Error(`TURNREWIND_GIT_FAILED: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.status}`}`)
- }
- return result.stdout
}
-function ensureRepository(repoDir, workspaceDir) {
+async function runGitText(repoDir, workspaceDir, args, extraEnv = {}) {
+ const output = await runGit(repoDir, workspaceDir, args, extraEnv)
+ return output.toString('utf8')
+}
+
+let gitProbeResult
+
+/** Resolve once per host process: whether a git executable is usable at all. */
+export function gitAvailable() {
+ gitProbeResult ??= new Promise((resolvePromise) => {
+ const child = spawn('git', ['--version'])
+ let settled = false
+ const settle = value => (settled ? undefined : (settled = true, resolvePromise(value)))
+ child.on('error', () => settle(false))
+ child.on('close', code => settle(code === 0))
+ })
+ return gitProbeResult
+}
+
+async function ensureRepository(repoDir, workspaceDir) {
if (!existsSync(join(repoDir, 'HEAD'))) {
mkdirSync(dirname(repoDir), { recursive: true })
- const result = spawnSync('git', ['init', '--bare', repoDir], { encoding: 'utf8' })
- if (result.error || result.status !== 0) {
- throw new Error(`TURNREWIND_GIT_INIT: ${result.stderr?.trim() || result.error?.message || 'git init failed'}`)
- }
+ await new Promise((resolvePromise, rejectPromise) => {
+ const child = spawn('git', ['init', '--bare', repoDir])
+ const errors = []
+ child.stderr.on('data', chunk => errors.push(chunk))
+ child.on('error', error => rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${error.message}`)))
+ child.on('close', (code) => {
+ if (code !== 0)
+ rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${Buffer.concat(errors).toString('utf8').trim() || 'git init failed'}`))
+ else
+ resolvePromise()
+ })
+ })
}
- runGit(repoDir, workspaceDir, ['config', 'core.bare', 'false'])
- runGit(repoDir, workspaceDir, ['config', 'core.worktree', workspaceDir])
+ await runGitText(repoDir, workspaceDir, ['config', 'core.bare', 'false'])
+ await runGitText(repoDir, workspaceDir, ['config', 'core.worktree', workspaceDir])
}
-function gitRef(repoDir, workspaceDir, ref) {
- const result = spawnSync('git', ['-c', 'core.quotepath=false', '--git-dir', repoDir, 'rev-parse', '--verify', ref], {
- cwd: workspaceDir,
- encoding: 'utf8',
- })
- return result.status === 0 ? result.stdout.trim() : undefined
+async function gitRef(repoDir, workspaceDir, ref) {
+ try {
+ const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', ref])
+ return output.trim()
+ }
+ catch {
+ return undefined
+ }
}
function assertSafePath(workspaceDir, path) {
@@ -98,24 +168,34 @@ export function workspaceHash(workspaceDir) {
return createHash('sha256').update(identity).digest('hex').slice(0, 24)
}
+/** Pure path computation; the repository itself is ensured lazily on capture. */
export function createSnapshotStore(rootDir, workspaceDir) {
const normalizedWorkspace = resolve(workspaceDir)
const repoDir = join(rootDir, 'snapshots', `${workspaceHash(normalizedWorkspace)}.git`)
- ensureRepository(repoDir, normalizedWorkspace)
return { repoDir, workspaceDir: normalizedWorkspace }
}
-/** Capture a complete allowed-path tree, incrementally reusing the parent tree. */
-export function captureSnapshot(store, refName, message, parentRef) {
+/**
+ * Capture a complete allowed-path tree, incrementally reusing the parent tree.
+ * A missing parent (wiped snapshot directory, moved DSH_HOME) degrades to a
+ * fresh baseline instead of failing every future turn.
+ */
+export async function captureSnapshot(store, refName, message, parentRef) {
const { repoDir, workspaceDir } = store
- ensureRepository(repoDir, workspaceDir)
+ await ensureRepository(repoDir, workspaceDir)
+ let parent
+ if (parentRef) {
+ parent = await gitRef(repoDir, workspaceDir, parentRef)
+ if (!parent)
+ console.warn(`turnrewind: snapshot parent ${parentRef} is gone; building a fresh baseline for ${workspaceDir}`)
+ }
const indexPath = join(repoDir, `turnrewind-index-${randomUUID()}`)
try {
const env = { GIT_INDEX_FILE: indexPath }
- if (parentRef)
- runGit(repoDir, workspaceDir, ['read-tree', parentRef], env)
- runGit(repoDir, workspaceDir, ['add', '--all', '--', '.', ...snapshotPathspecs()], env)
- const tree = runGit(repoDir, workspaceDir, ['write-tree'], env).trim()
+ if (parent)
+ await runGit(repoDir, workspaceDir, ['read-tree', parent], env)
+ await runGit(repoDir, workspaceDir, ['add', '--all', '--', '.', ...snapshotPathspecs()], env)
+ const tree = (await runGit(repoDir, workspaceDir, ['write-tree'], env)).toString('utf8').trim()
const identity = {
GIT_AUTHOR_NAME: 'DSH Turn Rewind',
GIT_AUTHOR_EMAIL: 'turnrewind@localhost',
@@ -123,10 +203,10 @@ export function captureSnapshot(store, refName, message, parentRef) {
GIT_COMMITTER_EMAIL: 'turnrewind@localhost',
}
const args = ['commit-tree', tree, '-m', message]
- if (parentRef)
- args.push('-p', parentRef)
- const commit = runGit(repoDir, workspaceDir, args, { ...env, ...identity }).trim()
- runGit(repoDir, workspaceDir, ['update-ref', refName, commit])
+ if (parent)
+ args.push('-p', parent)
+ const commit = (await runGit(repoDir, workspaceDir, args, { ...env, ...identity })).toString('utf8').trim()
+ await runGit(repoDir, workspaceDir, ['update-ref', refName, commit])
return { commit, refName }
}
finally {
@@ -134,29 +214,21 @@ export function captureSnapshot(store, refName, message, parentRef) {
}
}
-export function snapshotDiff(store, beforeCommit, afterCommit) {
- const output = runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '--no-renames', beforeCommit, afterCommit])
- return [...new Set(output.split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
+export async function snapshotDiff(store, beforeCommit, afterCommit) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '--no-renames', beforeCommit, afterCommit])
+ return [...new Set(output.toString('utf8').split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
}
-function commitEntry(store, commit, path) {
- const output = runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', commit, '--', path])
- return output.split(/\r?\n/).includes(path)
+async function commitEntry(store, commit, path) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', commit, '--', path])
+ return output.toString('utf8').split(/\r?\n/).includes(path)
}
-function commitBytes(store, commit, path) {
- const result = spawnSync('git', ['--git-dir', store.repoDir, 'show', `${commit}:${path}`], {
- cwd: store.workspaceDir,
- encoding: null,
- maxBuffer: MAX_FILE_BYTES,
- })
- if (result.error)
- throw new Error(`TURNREWIND_GIT_READ: ${path}: ${result.error.message}`)
- if (result.status !== 0)
- throw new Error(`TURNREWIND_GIT_READ: ${path}`)
- if (result.stdout.length > MAX_FILE_BYTES)
+async function commitBytes(store, commit, path) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['show', `${commit}:${path}`], {}, MAX_FILE_BYTES + 1)
+ if (output.length > MAX_FILE_BYTES)
throw new Error(`TURNREWIND_FILE_TOO_LARGE: ${path}`)
- return result.stdout
+ return output
}
function digest(bytes) {
@@ -171,10 +243,10 @@ function digest(bytes) {
return createHash('sha256').update(comparable).digest('hex')
}
-export function stateAt(store, commit, path) {
- if (!commitEntry(store, commit, path))
+export async function stateAt(store, commit, path) {
+ if (!await commitEntry(store, commit, path))
return { kind: 'absent', digest: null }
- const bytes = commitBytes(store, commit, path)
+ const bytes = await commitBytes(store, commit, path)
return { kind: 'file', digest: digest(bytes) }
}
@@ -188,9 +260,9 @@ export function currentState(workspaceDir, path) {
return { kind: 'file', digest: digest(readFileSync(target)) }
}
-export function restorePath(store, commit, path) {
+export async function restorePath(store, commit, path) {
const target = assertSafePath(store.workspaceDir, path)
- if (!commitEntry(store, commit, path)) {
+ if (!await commitEntry(store, commit, path)) {
if (existsSync(target)) {
const info = lstatSync(target)
if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
@@ -200,7 +272,7 @@ export function restorePath(store, commit, path) {
return { path, result: 'removed' }
}
- const bytes = commitBytes(store, commit, path)
+ const bytes = await commitBytes(store, commit, path)
mkdirSync(dirname(target), { recursive: true })
const temp = `${target}.turnrewind-${randomUUID()}.tmp`
writeFileSync(temp, bytes, { flag: 'wx' })
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
index 34cfa4e0..f6f1235d 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
@@ -117,13 +117,17 @@ export function settleNoopTurn(db, turnId, afterRef) {
.run(new Date().toISOString(), afterRef, 'no file changes', turnId)
}
+export function skipTurn(db, turn, reason) {
+ db.prepare(`
+ INSERT OR REPLACE INTO turns(turn_id, session_id, parent_turn_id, workspace_key, status, started_at, reversible, error)
+ VALUES (?, ?, NULL, ?, 'skipped', ?, 0, ?)
+ `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, reason)
+}
+
export function recordSkippedTurn(db, turn, reason) {
db.exec('BEGIN')
try {
- db.prepare(`
- INSERT OR REPLACE INTO turns(turn_id, session_id, parent_turn_id, workspace_key, status, started_at, reversible, error)
- VALUES (?, ?, NULL, ?, 'skipped', ?, 0, ?)
- `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, reason)
+ skipTurn(db, turn, reason)
// Queue one heads-up per session and workspace; repeated skips stay silent.
const existing = db.prepare(`
SELECT 1 FROM rewind_notices WHERE session_id = ? AND workspace_key = ? AND kind = 'unsupported' LIMIT 1
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index 0bf7a19b..8af83331 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -3,9 +3,9 @@ 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, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'
+import { captureSnapshot, createSnapshotStore, currentState, gitAvailable, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'
import { assessWorkspace } from './core/guard.js'
-import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'
+import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
@@ -119,14 +119,14 @@ function workspaceHasActiveTurn(active, workspaceKey) {
return false
}
-function settleActiveTurn(ledger, active, key, reason) {
+async function settleActiveTurn(ledger, active, key, reason) {
const current = active.get(key)
if (!current)
return
try {
const afterRef = refSuffix(current.turnId, 'after')
- captureSnapshot(current.runtime.store, afterRef, `turnrewind after ${current.turnId}`, current.beforeRef)
- const changed = snapshotDiff(current.runtime.store, current.beforeRef, afterRef)
+ await captureSnapshot(current.runtime.store, afterRef, `turnrewind after ${current.turnId}`, current.runtime.parentRef)
+ const changed = await snapshotDiff(current.runtime.store, current.beforeRef, afterRef)
if (changed.length === 0) {
settleNoopTurn(ledger, current.turnId, afterRef)
}
@@ -146,10 +146,11 @@ function settleActiveTurn(ledger, active, key, reason) {
}
}
-function settleSessionTurns(ledger, active, sessionId, reason) {
- for (const [key] of active) {
- if (key.startsWith(`${sessionId}:`))
- settleActiveTurn(ledger, active, key, reason)
+async function settleSessionTurns(ledger, active, sessionId, exceptKey, reason) {
+ for (const [key] of [...active.entries()]) {
+ if (key === exceptKey || !key.startsWith(`${sessionId}:`))
+ continue
+ await settleActiveTurn(ledger, active, key, reason)
}
}
@@ -189,13 +190,13 @@ async function applyUndo(runtime, active, invocation) {
runtime.undoing = true
try {
- const paths = snapshotDiff(runtime.store, target.before_ref, target.after_ref)
+ const paths = await snapshotDiff(runtime.store, target.before_ref, target.after_ref)
if (paths.length === 0)
return { kind: 'success', text: 'No file changes were recorded for this turn.' }
const conflicts = []
for (const path of paths) {
- const expected = stateAt(runtime.store, target.after_ref, path)
+ const expected = await stateAt(runtime.store, target.after_ref, path)
const actual = currentState(workspaceDir, path)
if (classifyUndo(actual, expected) === 'conflict')
conflicts.push(path)
@@ -209,7 +210,7 @@ async function applyUndo(runtime, active, invocation) {
const operationId = randomUUID()
const beforeRef = `refs/turnrewind/operation-${operationId}`
- captureSnapshot(runtime.store, beforeRef, `turnrewind undo ${target.turn_id}`, runtime.parentRef)
+ await captureSnapshot(runtime.store, beforeRef, `turnrewind undo ${target.turn_id}`, runtime.parentRef)
createOperation(runtime.db, {
operationId,
kind: 'undo',
@@ -219,7 +220,7 @@ async function applyUndo(runtime, active, invocation) {
})
try {
- for (const path of paths) restorePath(runtime.store, target.before_ref, path)
+ for (const path of paths) await restorePath(runtime.store, target.before_ref, path)
completeUndoWithNotice(runtime.db, target.turn_id, {
noticeId: randomUUID(),
sessionId: invocation.agent.session.id,
@@ -236,7 +237,7 @@ async function applyUndo(runtime, active, invocation) {
try {
// `beforeRef` is the state immediately before this operation. Restore every
// touched path from it so a mid-operation error does not leave a partial undo.
- for (const path of paths) restorePath(runtime.store, beforeRef, path)
+ for (const path of paths) await restorePath(runtime.store, beforeRef, path)
settleOperation(runtime.db, operationId, 'rolled_back', error)
return { kind: 'error', text: `Undo failed and the pre-undo file state was restored: ${String(error)}` }
}
@@ -260,6 +261,18 @@ function apply(ctx) {
// from the session list it already receives, no conversation API needed.
ctx.effect(() => ctx.sessionProjections.register(createDialogProjection()), 'turnrewind projection')
+ // Per-session FIFO chain: baseline capture, settle and undo bookkeeping for
+ // one session never interleave. Git now runs asynchronously, so ordering is
+ // enforced here instead of by the event loop blocking.
+ const sessionChains = new Map()
+
+ function enqueueTurnTask(sessionId, task) {
+ const previous = sessionChains.get(sessionId) ?? Promise.resolve()
+ const next = previous.then(task)
+ sessionChains.set(sessionId, next.catch(() => {}))
+ return next
+ }
+
function ensureRuntime(agent) {
const workspaceDir = workspaceForAgent(agent)
if (!workspaceDir)
@@ -325,43 +338,78 @@ function apply(ctx) {
const runtime = ensureRuntime(payload.agent)
if (!runtime)
return
- if (runtime.undoing) {
- console.error(`turnrewind: skipped turn ${key} while an undo is running`)
+ if (runtime.undoing || active.has(key)) {
+ console.error(`turnrewind: skipped turn ${key} while an undo is running or on duplicate claim`)
return
}
- if (active.has(key)) {
- console.error(`turnrewind: skipped duplicate claim for turn ${key}`)
- return
- }
- // A model switch can open B immediately after A is interrupted. Finalize A
- // before capturing B's baseline so B does not absorb A's partial files.
- settleSessionTurns(ledger, active, sessionId, 'interrupted by a newer turn in the same session')
- try {
- const turnId = key
- const beforeRef = refSuffix(turnId, 'before')
- captureSnapshot(runtime.store, beforeRef, `turnrewind before ${turnId}`, runtime.parentRef)
- insertTurn(ledger, {
- turnId,
- sessionId,
- parentTurnId: undefined,
- workspaceKey: runtime.workspaceKey,
- startedAt: new Date().toISOString(),
- beforeRef,
- })
- active.set(key, { runtime, sessionId, workspaceKey: runtime.workspaceKey, turnId, beforeRef, turn: payload.turn })
- }
- catch (error) {
- console.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)
- }
+ // Reserve the slot synchronously: the baseline capture below is async, and
+ // /undo must never start while it is still writing the snapshot index.
+ const beforeRef = refSuffix(key, 'before')
+ const entry = { runtime, sessionId, workspaceKey: runtime.workspaceKey, turnId: key, beforeRef, turn: payload.turn }
+ active.set(key, entry)
+ enqueueTurnTask(sessionId, async () => {
+ if (active.get(key) !== entry)
+ return
+ if (!(await gitAvailable())) {
+ active.delete(key)
+ const reason = 'TURNREWIND_GIT_UNAVAILABLE: the git executable was not found on PATH; file undo is disabled'
+ try {
+ recordSkippedTurn(ledger, {
+ turnId: key,
+ sessionId,
+ workspaceKey: runtime.workspaceKey,
+ startedAt: new Date().toISOString(),
+ }, reason)
+ }
+ catch (error) {
+ console.error(`turnrewind: failed to record skipped turn ${key}: ${String(error)}`)
+ }
+ console.error(`turnrewind: skipped turn ${key}: ${reason}`)
+ return
+ }
+ // A model switch can open B immediately after A is interrupted. Finalize A
+ // before capturing B's baseline so B does not absorb A's partial files.
+ await settleSessionTurns(ledger, active, sessionId, key, 'interrupted by a newer turn in the same session')
+ try {
+ await captureSnapshot(runtime.store, beforeRef, `turnrewind before ${key}`, runtime.parentRef)
+ insertTurn(ledger, {
+ turnId: key,
+ sessionId,
+ parentTurnId: undefined,
+ workspaceKey: runtime.workspaceKey,
+ startedAt: new Date().toISOString(),
+ beforeRef,
+ })
+ }
+ catch (error) {
+ active.delete(key)
+ // Transient capture failure (disk full, permissions): record the skip
+ // for /undo feedback, but without the persistent unsupported heads-up.
+ try {
+ skipTurn(ledger, {
+ turnId: key,
+ sessionId,
+ workspaceKey: runtime.workspaceKey,
+ startedAt: new Date().toISOString(),
+ }, `TURNREWIND_CAPTURE_FAILED: ${String(error)}`)
+ }
+ catch (ledgerError) {
+ console.error(`turnrewind: failed to record skipped turn ${key}: ${String(ledgerError)}`)
+ }
+ console.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)
+ }
+ })
})
ctx.on('session/event', (session, event) => {
if (event.type !== 'turn/end' || typeof event.data?.turn !== 'number')
return
const key = activeKey(session.id, event.data.turn)
+ if (!active.has(key))
+ return
const reason = event.data.reason?.kind
const interrupted = reason === 'aborted' || reason === 'error' || reason === 'cancelled'
- settleActiveTurn(ledger, active, key, interrupted ? `turn ended with ${reason}` : undefined)
+ enqueueTurnTask(session.id, () => settleActiveTurn(ledger, active, key, interrupted ? `turn ended with ${reason}` : undefined))
})
ctx.on('agent/turn-stopping', () => {
// A normal turn reaches the durable turn/end event immediately after this
@@ -374,8 +422,13 @@ function apply(ctx) {
console.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)
})
ctx.on('agent/status', ({ agent, status }) => {
- if (status === 'idle')
- settleSessionTurns(ledger, active, agent.session.id, 'agent became idle after interruption')
+ if (status !== 'idle')
+ return
+ const sessionId = agent.session.id
+ for (const key of [...active.keys()]) {
+ if (key.startsWith(`${sessionId}:`))
+ enqueueTurnTask(sessionId, () => settleActiveTurn(ledger, active, key, 'agent became idle after interruption'))
+ }
})
ctx.effect(() => () => ledger.close(), 'turnrewind ledger')
ctx.effect(() => () => {
diff --git a/plugins/dsh-tauri-turnrewind/package.json b/plugins/dsh-tauri-turnrewind/package.json
index b248eba3..a5468955 100644
--- a/plugins/dsh-tauri-turnrewind/package.json
+++ b/plugins/dsh-tauri-turnrewind/package.json
@@ -1,7 +1,7 @@
{
"name": "dsh-tauri-turnrewind",
"type": "module",
- "version": "0.1.0-dev.3",
+ "version": "0.1.0-dev.4",
"description": "Local turn-aware workspace undo for DeepSeek Harness",
"exports": {
".": "./lib/index.js",
diff --git a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
index d81f225c..36d752ed 100644
--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
@@ -3,7 +3,7 @@ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from '../lib/core/git-snapshot.js'
+import { captureSnapshot, createSnapshotStore, currentState, gitAvailable, restorePath, snapshotDiff, stateAt } from '../lib/core/git-snapshot.js'
import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../lib/core/ledger.js'
it('captures and restores modified, added, and deleted files', async () => {
@@ -15,19 +15,19 @@ it('captures and restores modified, added, and deleted files', async () => {
await writeFile(join(workspace, 'deleted.txt'), 'to delete')
const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = captureSnapshot(store, 'refs/turnrewind/test-before', 'before')
+ const before = await captureSnapshot(store, 'refs/turnrewind/test-before', 'before')
await writeFile(join(workspace, 'modified.txt'), 'after')
await rm(join(workspace, 'deleted.txt'))
await writeFile(join(workspace, 'added.txt'), 'new')
- const after = captureSnapshot(store, 'refs/turnrewind/test-after', 'after', before.commit)
+ const after = await captureSnapshot(store, 'refs/turnrewind/test-after', 'after', before.commit)
- assert.deepEqual(snapshotDiff(store, before.commit, after.commit).sort(), ['added.txt', 'deleted.txt', 'modified.txt'])
- assert.notEqual(stateAt(store, before.commit, 'modified.txt').digest, stateAt(store, after.commit, 'modified.txt').digest)
+ assert.deepEqual((await snapshotDiff(store, before.commit, after.commit)).sort(), ['added.txt', 'deleted.txt', 'modified.txt'])
+ assert.notEqual((await stateAt(store, before.commit, 'modified.txt')).digest, (await stateAt(store, after.commit, 'modified.txt')).digest)
- restorePath(store, before.commit, 'modified.txt')
- restorePath(store, before.commit, 'deleted.txt')
- restorePath(store, before.commit, 'added.txt')
+ await restorePath(store, before.commit, 'modified.txt')
+ await restorePath(store, before.commit, 'deleted.txt')
+ await restorePath(store, before.commit, 'added.txt')
assert.equal(await readFile(join(workspace, 'modified.txt'), 'utf8'), 'before')
assert.equal(await readFile(join(workspace, 'deleted.txt'), 'utf8'), 'to delete')
@@ -47,9 +47,9 @@ it('allows sequential undo of an interrupted turn after a later turn', async ()
try {
await mkdir(workspace, { recursive: true })
const store = createSnapshotStore(join(root, 'data'), workspace)
- const beforeA = captureSnapshot(store, 'refs/turnrewind/a-before', 'A before')
+ const beforeA = await captureSnapshot(store, 'refs/turnrewind/a-before', 'A before')
for (const file of filesA) await writeFile(join(workspace, file), 'A')
- const afterA = captureSnapshot(store, 'refs/turnrewind/a-after', 'A after', beforeA.commit)
+ const afterA = await captureSnapshot(store, 'refs/turnrewind/a-after', 'A after', beforeA.commit)
insertTurn(db, {
turnId: 'session:A',
sessionId: 'session',
@@ -59,9 +59,9 @@ it('allows sequential undo of an interrupted turn after a later turn', async ()
})
settleInterruptedTurn(db, 'session:A', 'refs/turnrewind/a-after', 'interrupted')
- const beforeB = captureSnapshot(store, 'refs/turnrewind/b-before', 'B before', afterA.commit)
+ const beforeB = await captureSnapshot(store, 'refs/turnrewind/b-before', 'B before', afterA.commit)
for (const file of filesB) await writeFile(join(workspace, file), 'B')
- const afterB = captureSnapshot(store, 'refs/turnrewind/b-after', 'B after', beforeB.commit)
+ const afterB = await captureSnapshot(store, 'refs/turnrewind/b-after', 'B after', beforeB.commit)
insertTurn(db, {
turnId: 'session:B',
sessionId: 'session',
@@ -71,7 +71,7 @@ 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 snapshotDiff(store, beforeB.commit, afterB.commit)) restorePath(store, beforeB.commit, file)
+ for (const file of await snapshotDiff(store, beforeB.commit, afterB.commit)) await restorePath(store, beforeB.commit, file)
completeUndoWithNotice(db, 'session:B', {
noticeId: 'notice-b',
sessionId: 'session',
@@ -82,7 +82,7 @@ it('allows sequential undo of an interrupted turn after a later turn', async ()
})
assert.equal(getLatestTurn(db, 'session', workspace.toLowerCase()).turn_id, 'session:A')
- for (const file of snapshotDiff(store, beforeA.commit, afterA.commit)) restorePath(store, beforeA.commit, file)
+ for (const file of await snapshotDiff(store, beforeA.commit, afterA.commit)) await restorePath(store, beforeA.commit, file)
for (const file of [...filesA, ...filesB]) await assert.rejects(stat(join(workspace, file)))
}
finally {
@@ -99,11 +99,11 @@ it('handles non-ASCII paths without reporting a false restore', async () => {
await mkdir(workspace, { recursive: true })
await writeFile(join(workspace, fileName), 'before')
const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = captureSnapshot(store, 'refs/turnrewind/unicode-before', 'before')
+ const before = await captureSnapshot(store, 'refs/turnrewind/unicode-before', 'before')
await writeFile(join(workspace, fileName), 'after')
- const after = captureSnapshot(store, 'refs/turnrewind/unicode-after', 'after', before.commit)
- assert.deepEqual(snapshotDiff(store, before.commit, after.commit), [fileName])
- restorePath(store, before.commit, fileName)
+ const after = await captureSnapshot(store, 'refs/turnrewind/unicode-after', 'after', before.commit)
+ assert.deepEqual(await snapshotDiff(store, before.commit, after.commit), [fileName])
+ await restorePath(store, before.commit, fileName)
assert.equal(await readFile(join(workspace, fileName), 'utf8'), 'before')
}
finally {
@@ -118,11 +118,11 @@ it('does not treat CRLF conversion as a file conflict', async () => {
await mkdir(workspace, { recursive: true })
await writeFile(join(workspace, 'line-endings.txt'), 'before\nline\n')
const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = captureSnapshot(store, 'refs/turnrewind/crlf-before', 'before')
+ const before = await captureSnapshot(store, 'refs/turnrewind/crlf-before', 'before')
await writeFile(join(workspace, 'line-endings.txt'), 'after\nline\n')
- const after = captureSnapshot(store, 'refs/turnrewind/crlf-after', 'after', before.commit)
+ const after = await captureSnapshot(store, 'refs/turnrewind/crlf-after', 'after', before.commit)
await writeFile(join(workspace, 'line-endings.txt'), 'after\r\nline\r\n')
- assert.equal(currentState(workspace, 'line-endings.txt').digest, stateAt(store, after.commit, 'line-endings.txt').digest)
+ assert.equal(currentState(workspace, 'line-endings.txt').digest, (await stateAt(store, after.commit, 'line-endings.txt')).digest)
}
finally {
await rm(root, { recursive: true, force: true })
@@ -140,3 +140,38 @@ it('rejects paths outside the workspace', async () => {
await rm(root, { recursive: true, force: true })
}
})
+
+it('rebuilds a fresh baseline when the parent snapshot is gone', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-orphan-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(workspace, { recursive: true })
+ await writeFile(join(workspace, 'a.txt'), 'one')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const first = await captureSnapshot(store, 'refs/turnrewind/orphan-first', 'first')
+
+ // Simulate the snapshot repository being wiped out from under the ledger:
+ // without the fallback, every later capture would fail on read-tree.
+ // The parent is passed by ref name, exactly like the ledger stores it.
+ await rm(store.repoDir, { recursive: true, force: true })
+ await writeFile(join(workspace, 'a.txt'), 'two')
+ const rebuilt = await captureSnapshot(store, 'refs/turnrewind/orphan-second', 'second', 'refs/turnrewind/orphan-first')
+ assert.notEqual(rebuilt.commit, first.commit)
+ assert.equal((await stateAt(store, rebuilt.commit, 'a.txt')).kind, 'file')
+
+ // The next turn keeps building on the recovered chain.
+ await writeFile(join(workspace, 'b.txt'), 'new')
+ const third = await captureSnapshot(store, 'refs/turnrewind/orphan-third', 'third', rebuilt.commit)
+ assert.deepEqual(await snapshotDiff(store, rebuilt.commit, third.commit), ['b.txt'])
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('probes git availability once per process', async () => {
+ const first = await gitAvailable()
+ const second = await gitAvailable()
+ assert.equal(first, second)
+ assert.equal(typeof first, 'boolean')
+})
diff --git a/plugins/dsh-tauri-turnrewind/test/security.test.js b/plugins/dsh-tauri-turnrewind/test/security.test.js
index ef0b24c1..2b0c5e7c 100644
--- a/plugins/dsh-tauri-turnrewind/test/security.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/security.test.js
@@ -3,7 +3,7 @@ import { mkdir, mkdtemp, readdir, rm, symlink, writeFile } from 'node:fs/promise
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, currentState, stateAt } from '../lib/core/git-snapshot.js'
+import { captureSnapshot, createSnapshotStore, currentState, restorePath, stateAt } from '../lib/core/git-snapshot.js'
it('does not capture common secret files into a snapshot', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-secret-test-'))
@@ -12,13 +12,17 @@ it('does not capture common secret files into a snapshot', async () => {
await mkdir(workspace, { recursive: true })
await writeFile(join(workspace, '.env'), 'TOKEN=do-not-store')
await writeFile(join(workspace, 'credentials.json'), '{"token":"do-not-store"}')
+ await writeFile(join(workspace, 'secrets.yaml'), 'key: do-not-store')
+ await writeFile(join(workspace, 'server.pem'), '-----BEGIN')
await writeFile(join(workspace, 'safe.txt'), 'safe')
const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = captureSnapshot(store, 'refs/turnrewind/security', 'security')
+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/security', 'security')
- assert.equal(stateAt(store, snapshot.commit, '.env').kind, 'absent')
- assert.equal(stateAt(store, snapshot.commit, 'credentials.json').kind, 'absent')
- assert.equal(stateAt(store, snapshot.commit, 'safe.txt').kind, 'file')
+ assert.equal((await stateAt(store, snapshot.commit, '.env')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'credentials.json')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'secrets.yaml')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'server.pem')).kind, 'absent')
+ assert.equal((await stateAt(store, snapshot.commit, 'safe.txt')).kind, 'file')
const snapshotFiles = await readdir(join(root, 'data', 'snapshots'))
assert.equal(snapshotFiles.length, 1)
}
@@ -27,7 +31,32 @@ it('does not capture common secret files into a snapshot', async () => {
}
})
-it('does not follow a symlinked workspace path during state inspection', async () => {
+it('keeps legitimate source files whose names resemble secrets', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-token-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(join(workspace, 'src'), { recursive: true })
+ await mkdir(join(workspace, 'docs'), { recursive: true })
+ await writeFile(join(workspace, 'src', 'token.ts'), 'export const token = 1')
+ await writeFile(join(workspace, 'src', 'tokenizer.py'), 'def tokenize(): pass')
+ await writeFile(join(workspace, 'src', 'secret_manager.js'), 'export const hide = 1')
+ await writeFile(join(workspace, 'docs', 'credentials.module.ts'), 'export const config = 1')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/token-source', 'token source')
+
+ // These were silently excluded by the old *token*/*secret*/credentials*
+ // globs, so undo could never restore them and the dry-run never showed them.
+ assert.equal((await stateAt(store, snapshot.commit, 'src/token.ts')).kind, 'file')
+ assert.equal((await stateAt(store, snapshot.commit, 'src/tokenizer.py')).kind, 'file')
+ assert.equal((await stateAt(store, snapshot.commit, 'src/secret_manager.js')).kind, 'file')
+ assert.equal((await stateAt(store, snapshot.commit, 'docs/credentials.module.ts')).kind, 'file')
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('refuses symlinked workspace paths during inspection and restore', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-test-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
@@ -45,7 +74,14 @@ it('does not follow a symlinked workspace path during state inspection', async (
}
const store = createSnapshotStore(join(root, 'data'), workspace)
assert.throws(() => currentState(workspace, 'linked/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
- assert.throws(() => stateAt(store, captureSnapshot(store, 'refs/turnrewind/symlink', 'symlink').commit, 'linked/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/symlink', 'symlink')
+ // The snapshot stores the link itself; paths below it are never tracked.
+ assert.equal((await stateAt(store, snapshot.commit, 'linked/secret.txt')).kind, 'absent')
+ // Restore refuses to traverse or replace a symlinked path.
+ await assert.rejects(
+ () => restorePath(store, snapshot.commit, 'linked/secret.txt'),
+ /TURNREWIND_SYMLINK_UNSUPPORTED/,
+ )
}
finally {
await rm(root, { recursive: true, force: true })