Skip to content

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

wip(turnrewind): prototype git directory snapshot mode

yingtianlan802c1b1fcc20
diff --git a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
new file mode 100644
index 00000000..e10fc9c4
--- /dev/null
+++ b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
@@ -0,0 +1,135 @@
+# turn-rewind Git 目录模式:当前进度与后续规划
+
+> 状态:**WIP / 实验性开发分支**
+>
+> 基线:桌面仓库 `6808c65`
+>
+> 目标:把 turn-rewind 调整为更接近 OpenCode 的 Git snapshot 模型,减少重复的目录扫描和自定义敏感文件规则;本文件描述当前独立实验分支,不代表主功能分支已经采用该方案。
+
+## 1. 方案结论
+
+“Git 目录模式”在本分支中采用 **OpenCode 风格的独立 snapshot Git 仓库**,而不是直接把 turnrewind 的 refs/objects 写入用户项目的 `.git`:
+
+```text
+用户项目工作树
+ ├─ 用户自己的 .git / HEAD / branch / index
+ └─ 用户自己的 .gitignore / global ignore / info/exclude
+
+DSH_HOME
+ ├─ ledger.sqlite
+ └─ snapshots/<workspace-hash>.git
+ ├─ turnrewind refs
+ └─ turnrewind 新产生的对象
+```
+
+这样可以复用 Git 的对象和 ignore 语义,同时继续保证:
+
+- 不修改用户项目 `HEAD`、branch、index、stash 或提交历史;
+- snapshot refs 不进入用户项目的 refs 命名空间;
+- 每次 capture 使用临时 `GIT_INDEX_FILE`,不污染用户真实 index;
+- 非 Git 工作区明确不可用,不再为普通目录创建私有 Git 基线;
+- Undo 仍然执行 workspace-relative 路径检查、冲突检查和恢复失败处理。
+
+## 2. 当前已完成的 WIP 改动
+
+### Host / Git workspace
+
+- 新增 `lib/core/git-workspace.js`:解析真实 Git worktree、worktree git-dir、common-dir、index 和 `info/exclude`;
+- `createSnapshotStore()` 要求 workspace 位于 Git worktree;
+- session cwd 会 canonicalize 到 Git worktree 根目录,子目录不会被当成另一个恢复域;
+- 非 Git 目录会返回 `TURNREWIND_GIT_REQUIRED`,由 turn 记录为不可追踪状态;
+- Host 不再调用旧的全目录预算 probe 作为 Git workspace 的进入条件;
+- 同一 workspace 的 session FIFO、baseline barrier、冲突检测和 `needs-recovery` 仍保留。
+
+### Snapshot store
+
+- snapshot 仍保存在 `$DSH_HOME/snapshots/<workspace-hash>.git`;
+- 私有 snapshot repo 初始化时尝试配置 source Git objects alternates,减少重复复制已经存在的对象;
+- 尝试同步 source `.git/info/exclude`;
+- capture 使用临时 alternate index,最后在 `finally` 中删除;
+- snapshot capture 复用 source workspace 的 `.gitignore` 和 global Git ignore 语义;
+- 自定义敏感文件规则已收窄为 Git 元数据和 turnrewind 临时文件,避免把 `token.ts`、`credentials.module.ts` 等合法源码静默排除;
+- snapshot refs 仅接受 `refs/turnrewind/` 前缀,并拒绝明显的路径穿越形式;
+- Git 路径 diff 继续使用 NUL 分隔。
+
+### 测试
+
+- 新增 `test/git-test-utils.js`,用于创建临时 Git workspace;
+- `git-snapshot.test.js` 的 fixture 已开始迁移到真实 Git workspace;
+- 当前已执行的 Git snapshot 目标测试:
+
+```text
+Test Files: 1 passed
+Tests: 10 passed
+Failed: 0
+```
+
+## 3. 当前未完成项
+
+本分支目前仍是 WIP,不能直接合并或作为生产版本使用。
+
+### 必须完成
+
+1. 把 `lifecycle.test.js`、`barrier.test.js`、`security.test.js` 和其他 snapshot fixture 全部迁移到真实临时 Git workspace;
+2. 重写 `guard.test.js`:从旧的文件数量/总大小/目录深度预算测试改为 Git-required、Git 根目录 canonicalization、普通目录拒绝和系统目录拒绝测试;
+3. 增加用户 Git 状态不变断言:capture 前后 `HEAD`、当前 branch、index、`git status` 均不应被插件改变;
+4. 增加 `.gitignore`、`.git/info/exclude`、global ignore 和 `.gitattributes` 语义测试;
+5. 解决 source object alternates、source index 初始化和 snapshot 私有对象之间的兼容性问题;
+6. 给同一个 Git common-dir 下的 linked worktree 增加 snapshot 隔离测试;
+7. 更新 `maintenance.js`、`purge-workspace.js`、ledger workspace metadata 和 purge 测试,保证只清理 turnrewind 的 snapshot repo,不误删用户 `.git`;
+8. 更新插件 README、`docs/TURN_REWIND.md` 和生产审计报告,明确本模式是实验分支、Git-only workspace 和仍未解决的风险;
+9. 运行完整插件回归、lint、Node import smoke,以及必要的真实 DSH Host 验证。
+
+### 仍需保留的安全边界
+
+即使采用 Git snapshot 简化模式,也不能删除:
+
+- workspace-relative 路径检查和路径逃逸拒绝;
+- symlink、junction、reparse point 的拒绝或明确失败;
+- restore 前的磁盘摘要和冲突二次校验;
+- pending plan 的原子 claim;
+- baseline barrier 与同 session FIFO;
+- operation 中断后的 `needs-recovery` fence;
+- Git 输出限制、NUL 路径解析和临时文件清理;
+- 不触碰用户 HEAD、branch、index、stash 和提交历史。
+
+“减少安全功能”只意味着删除与 Git 已经重复的自定义扫描/规则,不意味着可以取消恢复边界。
+
+## 4. 风险与取舍
+
+| 项目 | 当前取舍 |
+| --- | --- |
+| 快照存储 | 仍为 DSH_HOME 下的独立 Git repo,不污染用户 `.git` |
+| Git 对象复用 | 通过 alternates 尝试复用 source objects;失败时应能回退到独立对象 |
+| Ignore 规则 | 以 source Git ignore 为主,turnrewind 临时文件额外排除 |
+| 非 Git workspace | 不支持,明确记录 `TURNREWIND_GIT_REQUIRED` |
+| 大 workspace | 不再做重复的全目录预算扫描;Git ignore 可减少范围,但快照容量和性能风险仍存在 |
+| 用户手工修改 | 继续做冲突检测,默认不静默覆盖 |
+| 崩溃恢复 | 仍然只有 `needs-recovery` 阻断,尚无自动 journal 重放 |
+| 文件替换 | 现有删除后 rename 的非原子窗口仍未解决 |
+| purge | 仍需补 workspace lock、可恢复事务和运行中 repo 检查 |
+
+## 5. 验证命令
+
+在本分支根目录执行:
+
+```powershell
+pnpm install
+pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=120000 --maxWorkers=1
+pnpm exec eslint plugins/dsh-tauri-turnrewind
+node --input-type=module -e "await import('./plugins/dsh-tauri-turnrewind/lib/index.js')"
+```
+
+完整回归达到全绿前,不能把本分支描述为生产就绪。
+
+## 6. 分支说明
+
+本实验位于独立桌面项目目录,使用独立 Git worktree 分支:
+
+```text
+branch: dsh/turnrewind-git-dir-undo
+base: 6808c65
+status: WIP
+```
+
+本分支用于把 Git 目录模式实验和主 `feature/turn-rewind` 隔离,后续可以单独评审、继续修复或整体丢弃。
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index 2c512cad..9efc50dd 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@ -1,65 +1,26 @@
import { Buffer } from 'node:buffer'
import { spawn } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
-import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
-import { basename, dirname, join, relative, resolve, sep } from 'node:path'
+import { copyFileSync, existsSync, lstatSync, mkdirSync, 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'
import { TextDecoder, TextEncoder } from 'node:util'
+import { gitWorkspace } from './git-workspace.js'
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 = [
+// OpenCode-style storage delegates ordinary ignore behavior to the source
+// repository. Only turnrewind-owned temporary files are excluded explicitly.
+const SNAPSHOT_PATHSPECS = [
':(exclude,glob).git/**',
':(exclude,glob)**/.git/**',
- ':(exclude,glob)node_modules/**',
- ':(exclude,glob)**/node_modules/**',
- ':(exclude,glob)dist/**',
- ':(exclude,glob)**/dist/**',
- ':(exclude,glob)build/**',
- ':(exclude,glob)**/build/**',
- ':(exclude,glob)coverage/**',
- ':(exclude,glob)**/coverage/**',
':(exclude,glob).turnrewind/**',
':(exclude,glob)**/.turnrewind/**',
':(exclude,glob)**/*.turnrewind-*.tmp',
- ':(exclude,glob).env',
- ':(exclude,glob)**/.env',
- ':(exclude,glob).env.*',
- ':(exclude,glob)**/.env.*',
- ':(exclude,glob)**/*.pem',
- ':(exclude,glob)**/*.key',
- ':(exclude,glob)id_rsa*',
- ':(exclude,glob)**/id_rsa*',
- ':(exclude,glob)credentials.json',
- ':(exclude,glob)**/credentials.json',
- ':(exclude,glob)credentials.yaml',
- ':(exclude,glob)**/credentials.yaml',
- ':(exclude,glob)credentials.yml',
- ':(exclude,glob)**/credentials.yml',
- ':(exclude,glob)credentials.toml',
- ':(exclude,glob)**/credentials.toml',
- ':(exclude,glob)credentials.ini',
- ':(exclude,glob)**/credentials.ini',
- ':(exclude,glob)credentials.cfg',
- ':(exclude,glob)**/credentials.cfg',
- ':(exclude,glob)secrets.json',
- ':(exclude,glob)**/secrets.json',
- ':(exclude,glob)secrets.yaml',
- ':(exclude,glob)**/secrets.yaml',
- ':(exclude,glob)secrets.yml',
- ':(exclude,glob)**/secrets.yml',
- ':(exclude,glob)secrets.toml',
- ':(exclude,glob)**/secrets.toml',
- ':(exclude,glob)secrets.ini',
- ':(exclude,glob)**/secrets.ini',
- ':(exclude,glob)secrets.cfg',
- ':(exclude,glob)**/secrets.cfg',
]
+const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'
/**
* Run one git command without blocking the host event loop. All snapshot I/O
@@ -133,7 +94,11 @@ export function gitAvailable() {
return gitProbeResult
}
-async function ensureRepository(repoDir, workspaceDir) {
+async function ensureRepository(store) {
+ const { repoDir, workspaceDir, sourceCommonDir, sourceInfoExclude } = store
+ const source = gitWorkspace(workspaceDir)
+ if (!source || source.gitDir !== store.sourceGitDir)
+ throw new Error(`TURNREWIND_GIT_REPOSITORY: ${workspaceDir} is not the expected Git worktree`)
if (!existsSync(join(repoDir, 'HEAD'))) {
mkdirSync(dirname(repoDir), { recursive: true })
await new Promise((resolvePromise, rejectPromise) => {
@@ -142,20 +107,42 @@ async function ensureRepository(repoDir, workspaceDir) {
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)
+ if (code !== 0) {
rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${Buffer.concat(errors).toString('utf8').trim() || 'git init failed'}`))
- else
- resolvePromise()
+ return
+ }
+ resolvePromise()
})
})
+ await runGitText(repoDir, workspaceDir, ['config', 'core.autocrlf', 'false'])
+ await runGitText(repoDir, workspaceDir, ['config', 'core.symlinks', 'true'])
+ await runGitText(repoDir, workspaceDir, ['config', 'core.longpaths', 'true'])
+
+ // Reuse committed source objects, as OpenCode does, while new snapshot
+ // objects stay in this private repository.
+ const sourceObjects = join(sourceCommonDir, 'objects')
+ if (existsSync(sourceObjects)) {
+ const alternates = join(repoDir, 'objects', 'info', 'alternates')
+ mkdirSync(dirname(alternates), { recursive: true })
+ writeFileSync(alternates, `${sourceObjects}\n`)
+ }
+ }
+ if (sourceInfoExclude && existsSync(sourceInfoExclude)) {
+ const exclude = join(repoDir, 'info', 'exclude')
+ mkdirSync(dirname(exclude), { recursive: true })
+ writeFileSync(exclude, readFileSync(sourceInfoExclude))
}
- await runGitText(repoDir, workspaceDir, ['config', 'core.bare', 'false'])
- await runGitText(repoDir, workspaceDir, ['config', 'core.worktree', workspaceDir])
+}
+
+function normalizeSnapshotRef(ref) {
+ if (typeof ref !== 'string' || !ref.startsWith(SNAPSHOT_REF_PREFIX) || ref.includes('..') || ref.includes('\\') || ref.includes('//'))
+ throw new Error(`TURNREWIND_REF_UNSUPPORTED: ${String(ref)}`)
+ return ref
}
async function gitRef(repoDir, workspaceDir, ref) {
try {
- const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', ref])
+ const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', normalizeSnapshotRef(ref)])
return output.trim()
}
catch {
@@ -190,10 +177,6 @@ function assertSafePath(workspaceDir, path) {
return target
}
-function snapshotPathspecs() {
- return EXCLUDE_PATHS
-}
-
/**
* Canonical workspace identity shared by the ledger key, the snapshot repo
* hash and maintenance purges: case-folded only on case-insensitive platforms,
@@ -208,108 +191,37 @@ export function workspaceHash(workspaceDir) {
return createHash('sha256').update(workspaceKey(workspaceDir)).digest('hex').slice(0, 24)
}
-/** Pure path computation; the repository itself is ensured lazily on capture. */
+/**
+ * Create one OpenCode-style private snapshot repository per Git worktree.
+ * The source Git directory is read-only metadata/object input; the snapshot
+ * repository keeps its own refs and alternate capture index.
+ */
export function createSnapshotStore(rootDir, workspaceDir) {
- const normalizedWorkspace = resolve(workspaceDir)
+ const source = gitWorkspace(workspaceDir)
+ if (!source)
+ throw new Error(`TURNREWIND_GIT_REQUIRED: ${resolve(workspaceDir)} is not a Git worktree`)
+ const normalizedWorkspace = source.workspaceDir
const repoDir = join(rootDir, 'snapshots', `${workspaceHash(normalizedWorkspace)}.git`)
- return { repoDir, workspaceDir: normalizedWorkspace }
-}
-
-// Directories the snapshot walk must not descend into (mirrors EXCLUDE_PATHS).
-const EXCLUDE_DIRS = new Set(['.git', 'node_modules', 'dist', 'build', 'coverage', '.turnrewind'])
-
-function isExcludedPath(relPath, isDir) {
- const base = basename(relPath)
- if (isDir)
- return EXCLUDE_DIRS.has(base)
- if (/\.turnrewind-[0-9a-f-]+\.tmp$/iu.test(base))
- return true
- // Files excluded by EXCLUDE_PATHS: .env, .env.*, *.pem, *.key, id_rsa*,
- // and high-confidence structured credentials/secrets files. Keep source and
- // documentation files such as credentials.module.ts trackable.
- if (/^\.env(?:$|\.)/.test(base))
- return true
- if (/\.(?:pem|key)$/i.test(base))
- return true
- if (base.startsWith('id_rsa') || /^(?:credentials|secrets)\.(?:json|ya?ml|toml|ini|cfg)$/i.test(base))
- return true
- return false
+ return {
+ repoDir,
+ workspaceDir: normalizedWorkspace,
+ sourceGitDir: source.gitDir,
+ sourceCommonDir: source.commonDir,
+ sourceIndexPath: source.indexPath,
+ sourceInfoExclude: source.infoExcludePath,
+ }
}
/**
- * Pre-flight estimate of what a snapshot would track, WITHOUT creating a git repo.
- * Walks the workspace (accepting the same excluded paths as the real snapshot),
- * counting files, total bytes, largest file, and directory nesting depth. It
- * stops as soon as any configured limit is hit, so a huge directory does not
- * get fully walked. Callers should skip snapshot tracking (and undo) entirely
- * when this returns ok=false, so the plugin never bloats its private repo with a
- * big or deeply nested workspace.
- *
- * @param workspaceDir - root directory to estimate.
- * @param limits - optional overrides: maxFileCount, maxTotalBytes,
- * maxFileBytes, maxDepth, maxDirs.
- * @returns { ok: true, fileCount, totalBytes, maxFileBytes, maxDepth, dirCount }
- * or { ok: false, reason }.
+ * Git mode deliberately avoids a second full filesystem budget walk. The
+ * project's Git ignore rules determine the snapshot surface; restore keeps a
+ * per-file size limit because snapshot contents still have to fit in memory.
*/
-export function probeWorkspace(workspaceDir, limits = {}) {
- const maxFileCount = limits.maxFileCount ?? 10000
- const maxTotalBytes = limits.maxTotalBytes ?? 512 * 1024 * 1024
- const maxFileBytes = limits.maxFileBytes ?? 50 * 1024 * 1024
- const maxDepth = limits.maxDepth ?? 20
- const maxDirs = limits.maxDirs ?? 10000
- const root = resolve(workspaceDir)
- let fileCount = 0
- let totalBytes = 0
- let largestFile = 0
- let dirCount = 0
- let deepest = 0
- // Iterative DFS (explicit stack) so deep nesting cannot blow the call stack.
- const stack = [{ absolute: root, depth: 0 }]
- while (stack.length > 0) {
- const { absolute, depth } = stack.pop()
- if (depth > maxDepth)
- return { ok: false, reason: `nesting depth ${depth} exceeds limit (${maxDepth})` }
- deepest = Math.max(deepest, depth)
- let entries
- try {
- entries = readdirSync(absolute, { withFileTypes: true })
- }
- catch {
- continue
- }
- for (const entry of entries) {
- const full = join(absolute, entry.name)
- const rel = relative(root, full)
- if (isExcludedPath(rel, entry.isDirectory()))
- continue
- if (entry.isDirectory()) {
- dirCount += 1
- if (dirCount > maxDirs)
- return { ok: false, reason: `directory count ${dirCount} exceeds limit (${maxDirs})` }
- stack.push({ absolute: full, depth: depth + 1 })
- }
- else if (entry.isFile()) {
- let size
- try {
- size = statSync(full).size
- }
- catch {
- continue
- }
- fileCount += 1
- totalBytes += size
- if (size > largestFile)
- largestFile = size
- if (fileCount > maxFileCount)
- return { ok: false, reason: `file count ${fileCount} exceeds limit (${maxFileCount})` }
- if (size > maxFileBytes)
- return { ok: false, reason: `file ${rel} is ${size} bytes, larger than limit (${maxFileBytes})` }
- if (totalBytes > maxTotalBytes)
- return { ok: false, reason: `total size ${totalBytes} bytes exceeds limit (${maxTotalBytes})` }
- }
- }
- }
- return { ok: true, fileCount, totalBytes, maxFileBytes: largestFile, maxDepth: deepest, dirCount }
+export function probeWorkspace(workspaceDir) {
+ const source = gitWorkspace(workspaceDir)
+ if (!source)
+ return { ok: false, reason: 'TURNREWIND_GIT_REQUIRED: workspace is not a Git worktree' }
+ return { ok: true, workspaceDir: source.workspaceDir, commonDir: source.commonDir }
}
/**
@@ -318,20 +230,24 @@ export function probeWorkspace(workspaceDir, limits = {}) {
* fresh baseline instead of failing every future turn.
*/
export async function captureSnapshot(store, refName, message, parentRef) {
- const { repoDir, workspaceDir } = store
- await ensureRepository(repoDir, workspaceDir)
+ const { repoDir, workspaceDir, sourceIndexPath } = store
+ await ensureRepository(store)
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()}`)
+ const indexPath = join(tmpdir(), `turnrewind-index-${randomUUID()}`)
try {
const env = { GIT_INDEX_FILE: indexPath }
if (parent)
await runGit(repoDir, workspaceDir, ['read-tree', parent], env)
- await runGit(repoDir, workspaceDir, ['add', '--all', '--', '.', ...snapshotPathspecs()], env)
+ else if (existsSync(sourceIndexPath))
+ copyFileSync(sourceIndexPath, indexPath)
+ // Git reads .gitignore and global excludes from the source worktree while
+ // GIT_INDEX_FILE isolates the snapshot from the user's real index.
+ await runGit(repoDir, workspaceDir, ['add', '--all', '--', '.', ...SNAPSHOT_PATHSPECS], env)
const tree = (await runGit(repoDir, workspaceDir, ['write-tree'], env)).toString('utf8').trim()
const identity = {
GIT_AUTHOR_NAME: 'DSH Turn Rewind',
@@ -343,8 +259,9 @@ export async function captureSnapshot(store, refName, message, parentRef) {
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 }
+ const ref = normalizeSnapshotRef(refName)
+ await runGit(repoDir, workspaceDir, ['update-ref', ref, commit])
+ return { commit, refName: ref }
}
finally {
rmSync(indexPath, { force: true })
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js b/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
new file mode 100644
index 00000000..5fa8618d
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
@@ -0,0 +1,53 @@
+import { spawnSync } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { resolve } from 'node:path'
+import process from 'node:process'
+
+const MAX_OUTPUT_BYTES = 1024 * 1024
+
+function runGitSync(workspaceDir, args) {
+ const result = spawnSync('git', ['-c', 'core.quotepath=false', ...args], {
+ cwd: workspaceDir,
+ env: { ...process.env },
+ encoding: 'utf8',
+ maxBuffer: MAX_OUTPUT_BYTES,
+ })
+ if (result.error)
+ return { ok: false, error: result.error }
+ if (result.status !== 0)
+ return { ok: false, stderr: String(result.stderr ?? '').trim(), status: result.status }
+ return { ok: true, stdout: String(result.stdout ?? '').trim() }
+}
+
+/**
+ * Resolve the canonical Git worktree and its metadata without changing Git
+ * state. The caller can use this to require a project Git boundary and to
+ * reuse Git objects/ignore behavior without touching the user's index.
+ */
+export function gitWorkspace(workspaceDir) {
+ const requestedDir = resolve(workspaceDir)
+ const inside = runGitSync(requestedDir, ['rev-parse', '--is-inside-work-tree'])
+ const top = runGitSync(requestedDir, ['rev-parse', '--show-toplevel'])
+ const gitDir = runGitSync(requestedDir, ['rev-parse', '--git-dir'])
+ const commonDir = runGitSync(requestedDir, ['rev-parse', '--git-common-dir'])
+ const index = runGitSync(requestedDir, ['rev-parse', '--git-path', 'index'])
+ const infoExclude = runGitSync(requestedDir, ['rev-parse', '--git-path', 'info/exclude'])
+ if (!inside.ok || inside.stdout !== 'true' || !top.ok || !gitDir.ok || !commonDir.ok || !index.ok)
+ return undefined
+
+ const workspaceRoot = resolve(requestedDir, top.stdout)
+ const resolvedGitDir = resolve(requestedDir, gitDir.stdout)
+ const resolvedCommonDir = resolve(requestedDir, commonDir.stdout)
+ const resolvedIndex = resolve(requestedDir, index.stdout)
+ if (!existsSync(workspaceRoot) || !existsSync(resolvedGitDir) || !existsSync(resolvedCommonDir))
+ return undefined
+
+ return {
+ workspaceDir: workspaceRoot,
+ requestedDir,
+ gitDir: resolvedGitDir,
+ commonDir: resolvedCommonDir,
+ indexPath: resolvedIndex,
+ infoExcludePath: infoExclude.ok ? resolve(requestedDir, infoExclude.stdout) : undefined,
+ }
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index 13ab9804..0ee03089 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -5,7 +5,7 @@ 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, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'
-import { assessWorkspace, defaultBudget } from './core/guard.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, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
@@ -33,12 +33,10 @@ function workspaceForSession(session) {
if (typeof cwd !== 'string' || cwd.length === 0)
return undefined
const resolved = resolve(cwd)
- // Never snapshot the home directory: a full git baseline can walk hundreds
- // of GB and fail on root-owned dirs (docker volumes, container storage).
- // Sessions running from $HOME (e.g. the QQ bridge) simply get no turn snapshots.
- if (resolved === homedir())
+ if (isSystemSensitiveWorkspace(resolved))
return undefined
- return resolved
+ const probe = probeWorkspace(resolved)
+ return probe.ok ? probe.workspaceDir : undefined
}
function workspaceKeyFor(path) {
@@ -46,8 +44,10 @@ function workspaceKeyFor(path) {
}
function workspaceIssue(workspaceDir) {
- const assessment = assessWorkspace(workspaceDir)
- return assessment.eligible ? undefined : assessment.reason
+ if (isSystemSensitiveWorkspace(workspaceDir))
+ return `TURNREWIND_WORKSPACE_UNSUPPORTED: ${workspaceDir} is a system directory`
+ const probe = probeWorkspace(workspaceDir)
+ return probe.ok ? undefined : probe.reason
}
function activeKey(sessionId, turn) {
@@ -530,9 +530,9 @@ async function applyUndo(runtime, active, invocation) {
if (!workspaceDir) {
// The hard guard refused the cwd; report the actual reason when there is one.
const cwd = invocation.agent?.session?.header?.cwd
- const assessment = typeof cwd === 'string' && cwd.length > 0 ? assessWorkspace(resolve(cwd)) : undefined
- if (assessment && !assessment.eligible)
- return { kind: 'error', text: `Undo is unavailable for this workspace. ${assessment.reason}` }
+ const issue = typeof cwd === 'string' && cwd.length > 0 ? workspaceIssue(resolve(cwd)) : undefined
+ if (issue)
+ return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
}
const workspaceKey = workspaceKeyFor(workspaceDir)
@@ -692,26 +692,10 @@ async function applyUndo(runtime, active, invocation) {
}
}
-function apply(ctx, config = {}) {
- // Workspace snapshot guard: before we ever create a private git tracking repo,
- // estimate what it would hold (file count / total bytes / largest file /
- // nesting depth) and refuse to track workspaces that are too big or too deep.
- // Thresholds are configurable via the plugin's `config` (patch insert), i.e. the
- // plugin settings. Defaults keep a normal small/mid workspace trackable while
- // blocking the huge-directory disaster (node_modules-heavy repos, build trees,
- // and anything resembling $HOME).
- // Probe limits share one source of truth with the claim-time guard: the
- // defaultBudget values (and their TURNREWIND_* env overrides) feed the probe,
- // so a workspace either passes both layers or gets the same numbers in both.
- // Depth/dir caps stay probe-only (the metadata guard has no recursion caps).
- const budget = defaultBudget()
- const guard = Object.assign({
- maxFileCount: budget.maxFiles,
- maxTotalBytes: budget.maxTotalBytes,
- maxFileBytes: budget.maxFileBytes,
- maxDepth: 20,
- maxDirs: 10000,
- }, config.guard)
+function apply(ctx) {
+ // Git mode uses the project's Git worktree as the snapshot boundary. Its
+ // ignore rules replace the old full-directory eligibility scan, while path
+ // validation, conflict checks and the private snapshot repository remain.
const dataRoot = rootDir()
const ledger = openLedger(dataRoot)
const recoveryWorkspaces = new Set(listNeedsRecoveryWorkspaces(ledger))
@@ -719,10 +703,6 @@ function apply(ctx, config = {}) {
const untrackedTurns = new Set()
const workspaceStores = new Map()
let disposed = false
- // Workspaces rejected by the guard: key -> reason. Cached so we do not re-walk
- // a huge directory on every turn; an undo for such a workspace is impossible
- // anyway because no snapshot was ever captured.
- const rejectedWorkspaces = new Map()
const commands = ctx.commands
// Client-visible projection: lets the web UI raise the unavailable-dialog
// from the session list it already receives, no conversation API needed.
@@ -852,16 +832,8 @@ function apply(ctx, config = {}) {
if (!workspaceDir)
return undefined
const workspaceKey = workspaceKeyFor(workspaceDir)
- if (rejectedWorkspaces.has(workspaceKey))
- return undefined
let runtime = workspaceStores.get(workspaceKey)
if (!runtime) {
- const probe = probeWorkspace(workspaceDir, guard)
- if (!probe.ok) {
- rejectedWorkspaces.set(workspaceKey, probe.reason)
- ctx.logger?.warn?.(`[turnrewind] skip snapshot tracking for ${workspaceDir}: ${probe.reason}`)
- return undefined
- }
const store = createSnapshotStore(dataRoot, workspaceDir)
const latest = getLatestSnapshotRef(ledger, workspaceKey)
registerWorkspace(ledger, workspaceKey, workspaceDir, store.repoDir)
@@ -921,14 +893,13 @@ function apply(ctx, config = {}) {
const startedAt = new Date().toISOString()
const workspaceDir = workspaceForAgent(agent)
if (!workspaceDir) {
- // The hard guard in workspaceForSession refused the cwd (e.g. $HOME).
- // Keep a durable skipped record so /undo explains why instead of
- // pretending the session has no workspace.
+ // Git-only mode rejects system directories and non-Git workspaces. Keep a
+ // durable skipped record so /undo explains why the turn was not tracked.
const cwd = agent?.session?.header?.cwd
if (typeof cwd === 'string' && cwd.length > 0) {
- const assessment = assessWorkspace(resolve(cwd))
- if (!assessment.eligible)
- recordSkipped(key, sessionId, workspaceKeyFor(resolve(cwd)), startedAt, assessment.reason)
+ const issue = workspaceIssue(resolve(cwd))
+ if (issue)
+ recordSkipped(key, sessionId, workspaceKeyFor(resolve(cwd)), startedAt, issue)
}
return undefined
}
@@ -945,14 +916,8 @@ function apply(ctx, config = {}) {
}
const runtime = ensureRuntime(agent)
- if (!runtime) {
- // Passed the metadata guard but refused by the deeper probe (depth/dir
- // caps): surface that reason instead of staying silent.
- const reason = rejectedWorkspaces.get(workspaceKey)
- if (reason)
- recordSkipped(key, sessionId, workspaceKey, startedAt, `TURNREWIND_WORKSPACE_TOO_LARGE: ${reason}`)
+ if (!runtime)
return undefined
- }
if (runtime.undoing) {
recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_WORKSPACE_BUSY: an undo operation is running')
@@ -1149,9 +1114,9 @@ function apply(ctx, config = {}) {
if (!workspaceDir) {
// The hard guard refused the cwd; report the actual reason when there is one.
const cwd = invocation.agent?.session?.header?.cwd
- const assessment = typeof cwd === 'string' && cwd.length > 0 ? assessWorkspace(resolve(cwd)) : undefined
- if (assessment && !assessment.eligible)
- return { kind: 'error', text: `Undo is unavailable for this workspace. ${assessment.reason}` }
+ const issue = typeof cwd === 'string' && cwd.length > 0 ? workspaceIssue(resolve(cwd)) : undefined
+ if (issue)
+ return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
}
const workspaceIdentity = workspaceKeyFor(workspaceDir)
@@ -1162,11 +1127,7 @@ function apply(ctx, config = {}) {
return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
const runtime = ensureRuntime(invocation.agent)
if (!runtime) {
- // Refused by the deeper probe (depth/dir caps) — surface that reason.
- const reason = rejectedWorkspaces.get(workspaceKeyFor(workspaceDir))
- if (reason)
- return { kind: 'error', text: `Undo is unavailable for this workspace. TURNREWIND_WORKSPACE_TOO_LARGE: ${reason}` }
- return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
+ return { kind: 'error', text: 'Undo is unavailable because the Git workspace could not be initialized.' }
}
return applyUndo(runtime, active, invocation)
},
diff --git a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
index 624d1a89..c97a32f4 100644
--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
@@ -1,17 +1,17 @@
import assert from 'node:assert/strict'
-import { Buffer } from 'node:buffer'
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, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from '../lib/core/git-snapshot.js'
import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../lib/core/ledger.js'
+import { initGitWorkspace } from './git-test-utils.js'
it('captures and restores modified, added, and deleted files', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-test-'))
const workspace = join(root, 'workspace')
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, 'modified.txt'), 'before')
await writeFile(join(workspace, 'deleted.txt'), 'to delete')
@@ -46,7 +46,7 @@ it('allows sequential undo of an interrupted turn after a later turn', async ()
const filesB = ['b-1.txt', 'b-2.txt']
const db = openLedger(join(root, 'ledger'))
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
const store = createSnapshotStore(join(root, 'data'), workspace)
const beforeA = await captureSnapshot(store, 'refs/turnrewind/a-before', 'A before')
for (const file of filesA) await writeFile(join(workspace, file), 'A')
@@ -97,7 +97,7 @@ it('handles non-ASCII paths without reporting a false restore', async () => {
const workspace = join(root, 'workspace')
const fileName = '新建文本文档.txt'
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, fileName), 'before')
const store = createSnapshotStore(join(root, 'data'), workspace)
const before = await captureSnapshot(store, 'refs/turnrewind/unicode-before', 'before')
@@ -116,7 +116,7 @@ it('does not treat CRLF conversion as a file conflict', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-crlf-test-'))
const workspace = join(root, 'workspace')
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, 'line-endings.txt'), 'before\nline\n')
const store = createSnapshotStore(join(root, 'data'), workspace)
const before = await captureSnapshot(store, 'refs/turnrewind/crlf-before', 'before')
@@ -134,7 +134,7 @@ it('classifies path changes and produces codex-style diffs', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-diff-test-'))
const workspace = join(root, 'workspace')
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, 'modified.txt'), 'one\ntwo\n')
await writeFile(join(workspace, 'deleted.txt'), 'gone\n')
@@ -174,7 +174,7 @@ it('truncates long unified diffs', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-truncate-test-'))
const workspace = join(root, 'workspace')
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, 'big.txt'), 'old\n')
const store = createSnapshotStore(join(root, 'data'), workspace)
const before = await captureSnapshot(store, 'refs/turnrewind/truncate-before', 'before')
@@ -194,7 +194,7 @@ it('rejects paths outside the workspace', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-path-test-'))
const workspace = join(root, 'workspace')
try {
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
assert.throws(() => currentState(workspace, '../outside.txt'), /TURNREWIND_PATH_ESCAPE/)
}
finally {
@@ -202,46 +202,19 @@ it('rejects paths outside the workspace', async () => {
}
})
-it('probes a small workspace as trackable and refuses oversized / deep ones', async () => {
+it('accepts Git worktrees and rejects ordinary directories', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-probe-'))
const workspace = join(root, 'ws')
+ const plain = join(root, 'plain')
try {
- await mkdir(workspace, { recursive: true })
- await writeFile(join(workspace, 'a.txt'), 'hello')
- await writeFile(join(workspace, 'b.txt'), 'world')
- // ok: 2 small files
- const small = probeWorkspace(workspace)
- assert.equal(small.ok, true)
- assert.equal(small.fileCount, 2)
-
- // too many files
- for (let i = 0; i < 6; i++) await writeFile(join(workspace, `f${i}.txt`), 'x')
- const many = probeWorkspace(workspace, { maxFileCount: 4 })
- assert.equal(many.ok, false)
- assert.match(many.reason, /file count/)
-
- // single oversized file
- const big = join(workspace, 'big.bin')
- await writeFile(big, Buffer.alloc(300))
- const large = probeWorkspace(workspace, { maxFileBytes: 100 })
- assert.equal(large.ok, false)
- assert.match(large.reason, /larger than limit/)
-
- // deep nesting
- let dir = workspace
- for (let i = 0; i < 6; i++) {
- dir = join(dir, 'd')
- await mkdir(dir)
- }
- const deep = probeWorkspace(workspace, { maxDepth: 3 })
- assert.equal(deep.ok, false)
- assert.match(deep.reason, /nesting depth/)
-
- // excluded dirs (node_modules, .git) are not counted
- await mkdir(join(workspace, 'node_modules'), { recursive: true })
- await writeFile(join(workspace, 'node_modules', 'huge.bin'), Buffer.alloc(1000))
- const withExcluded = probeWorkspace(workspace, { maxFileBytes: 500 })
- assert.equal(withExcluded.ok, true, 'excluded dirs must not be counted')
+ await initGitWorkspace(workspace)
+ await mkdir(plain, { recursive: true })
+ const tracked = probeWorkspace(workspace)
+ assert.equal(tracked.ok, true)
+ assert.equal(tracked.workspaceDir, workspace)
+ const rejected = probeWorkspace(plain)
+ assert.equal(rejected.ok, false)
+ assert.match(rejected.reason, /GIT_REQUIRED/u)
}
finally {
await rm(root, { recursive: true, force: true })
@@ -252,7 +225,7 @@ 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 initGitWorkspace(workspace)
await writeFile(join(workspace, 'a.txt'), 'one')
const store = createSnapshotStore(join(root, 'data'), workspace)
const first = await captureSnapshot(store, 'refs/turnrewind/orphan-first', 'first')
diff --git a/plugins/dsh-tauri-turnrewind/test/git-test-utils.js b/plugins/dsh-tauri-turnrewind/test/git-test-utils.js
new file mode 100644
index 00000000..7453bcfb
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/test/git-test-utils.js
@@ -0,0 +1,27 @@
+import { Buffer } from 'node:buffer'
+import { spawn } from 'node:child_process'
+import { mkdir } from 'node:fs/promises'
+
+export function runGit(cwd, args) {
+ return new Promise((resolvePromise, rejectPromise) => {
+ const child = spawn('git', args, { cwd })
+ const errors = []
+ child.stderr.on('data', chunk => errors.push(chunk))
+ child.on('error', rejectPromise)
+ child.on('close', (code) => {
+ if (code !== 0) {
+ rejectPromise(new Error(`git ${args.join(' ')} failed: ${Buffer.concat(errors).toString('utf8').trim()}`))
+ return
+ }
+ resolvePromise()
+ })
+ })
+}
+
+export async function initGitWorkspace(workspace) {
+ await mkdir(workspace, { recursive: true })
+ await runGit(workspace, ['init', '--quiet'])
+ await runGit(workspace, ['config', 'user.name', 'Turn Rewind Test'])
+ await runGit(workspace, ['config', 'user.email', 'turnrewind-test@localhost'])
+ return workspace
+}
diff --git a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
index b12e4a4b..6867fd21 100644
--- a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
@@ -1,16 +1,17 @@
import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { it } from 'vitest'
import { captureSnapshot, createSnapshotStore } from '../lib/core/git-snapshot.js'
import { getTurn, insertTurn, openLedger, settleTurn } from '../lib/core/ledger.js'
import { applyUndo, waitForTurnBaseline } from '../lib/index.js'
+import { initGitWorkspace } from './git-test-utils.js'
async function setupTurn() {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-lifecycle-test-'))
const workspace = join(root, 'workspace')
- await mkdir(workspace, { recursive: true })
+ await initGitWorkspace(workspace)
await writeFile(join(workspace, 'a.txt'), 'v1\n')
const db = openLedger(join(root, 'ledger'))
const store = createSnapshotStore(join(root, 'data'), workspace)