Skip to content

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

feat(turnrewind): refuse snapshot symlinks instead of faking files (P1-3)

yingtianlan9bf50fa0b7d9
diff --git a/packages/dsh-tauri-turnrewind-ts/README.md b/packages/dsh-tauri-turnrewind-ts/README.md
index dd05cccb..589f15ef 100644
--- a/packages/dsh-tauri-turnrewind-ts/README.md
+++ b/packages/dsh-tauri-turnrewind-ts/README.md
@@ -348,7 +348,7 @@ pnpm --filter dsh-tauri-turnrewind typecheck
pnpm --filter dsh-tauri-turnrewind test
```
-当前 17 个测试文件、82 个测试,覆盖:Git 快照(增删改恢复、中文路径、CRLF、路径逃逸、符号链接、ignore 委托、alternates 复用与自愈)、原子 bak-swap 恢复与崩溃清扫、Git 状态零污染(HEAD/branch/index/status/refs/stash 不变)、linked worktree 隔离、oversized blob 单文件报告、账本生命周期、pending plan 原子 claim、interrupted turn、barrier 时序、undo/redo 往返、client 纯函数(输出解析/plan 状态判定/会话归属)。
+当前 18 个测试文件、97 个测试,覆盖:Git 快照(增删改恢复、中文路径、CRLF、路径逃逸、symlink 路径拒绝与快照 symlink 策略、ignore 委托、alternates 复用与自愈)、原子 bak-swap 恢复与崩溃清扫、Git 状态零污染(HEAD/branch/index/status/refs/stash 不变)、linked worktree 隔离、oversized blob 单文件报告、账本生命周期(含 needs-recovery 围栏)、pending plan 原子 claim 与预览绑定漂移校验、interrupted turn、barrier 时序、跨进程 workspace 锁、undo 入口与 redo 冻结、client 纯函数(输出解析/plan 状态判定/会话归属)。
## 当前限制
@@ -357,8 +357,13 @@ pnpm --filter dsh-tauri-turnrewind test
- 接入受控的宿主 sandbox/Tauri bridge;
- 完成真实 DSH lifecycle integration tests;
- 快照容量治理:按 turn 数/容量/保留期清理旧 snapshot ref(当前只做断链自愈,不清理历史);
-- 完善多 workspace 并发锁;
- 实现父对话递归 undo;
- 实现消息旁 Undo 按钮;
-- 明确二进制、重命名、权限位和特殊文件策略;
+- 明确二进制、重命名、权限位等策略(symlink 已定义:捕获进快照但 undo 标注 `[unsupported]` 并跳过,见下文「符号链接策略」);
- 重新开放 redo:移除解析层禁用分支、恢复端到端 redo 测试(底层加固已完成,见「已禁用:redo」)。
+
+### 符号链接策略(P1-3)
+
+- 工作区内指向外部的 symlink 路径:从不遍历、从不写入(`TURNREWIND_SYMLINK_UNSUPPORTED`);
+- 快照中记录的 symlink 条目(git mode `120000`):`stateAt` 报告为 `unsupported`,预览卡与 dry-run 标注 `[unsupported]` 并单独列出;undo 执行时跳过该路径并计入「未恢复」清单,绝不把 link target 文本伪装成普通文件写回;`restorePath` 内有同规则双保险;
+- turn 把 symlink 替换为普通文件(或反向)时,类型变化按 modified 处理;含 symlink 的 undo 结果中该文件始终出现在「未恢复」明细与 notice 里,需要用户手工重建。
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts b/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
index c3e5b78c..e9c694a9 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
@@ -39,12 +39,17 @@ export function parseUndoOutput(raw: string | undefined): ParsedUndoOutput {
// falling into the synthetic conflict fallback.
let path = listed[2]!.trimStart()
let conflict = false
- if (/\s{2,}\[conflict\]$/.test(path)) {
+ // padEnd makes `created`/`deleted` rows carry two spaces before a flag
+ // while `modified` rows carry one — accept any run of whitespace so the
+ // flag strips reliably for every change kind.
+ if (/\s+\[conflict\]$/.test(path)) {
conflict = true
- path = path.replace(/\s{2,}\[conflict\]$/, '')
+ path = path.replace(/\s+\[conflict\]$/, '')
}
- if (/\s{2,}\[too large\]$/.test(path))
- path = path.replace(/\s{2,}\[too large\]$/, '')
+ if (/\s+\[too large\]$/.test(path))
+ path = path.replace(/\s+\[too large\]$/, '')
+ if (/\s+\[unsupported\]$/.test(path))
+ path = path.replace(/\s+\[unsupported\]$/, '')
result.files.push({ path, change: listed[1] as ParsedUndoFile['change'], additions: 0, deletions: 0, diff: [], conflict })
continue
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
index 7226b49e..88f6d6c9 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
@@ -23,6 +23,9 @@ export const SYNC_GIT_TIMEOUT_MS = 15 * 1000
/** 快照 refs 允许的前缀(拒绝其他 refs 命名空间与路径穿越)。 */
export const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'
+/** Git symlink 条目的 mode 值(P1-3:stateAt/restore 据此拒绝,而非伪装成文件)。 */
+export const GIT_SYMLINK_MODE = '120000'
+
/** 原子替换的 bak 后缀。 */
export const BAK_SUFFIX = '.turnrewind-restore.bak'
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
index de7dc30a..0c66b691 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
@@ -42,6 +42,7 @@ import {
GIT_PROBE_RETRY_MS,
GIT_PROBE_TIMEOUT_MS,
GIT_SUBPROCESS_TIMEOUT_MS,
+ GIT_SYMLINK_MODE,
MAX_FILE_BYTES,
MAX_OUTPUT_BYTES,
SNAPSHOT_PATHSPECS,
@@ -476,9 +477,9 @@ function truncateDiff(text: string, maxLines: number = DEFAULT_MAX_DIFF_LINES):
export async function classifyPathChange(store: SnapshotStore, beforeCommit: string, afterCommit: string, path: string): Promise<PathChange> {
const before = await stateAt(store, beforeCommit, path)
const after = await stateAt(store, afterCommit, path)
- if (before.kind === 'absent' && after.kind === 'file')
+ if (before.kind === 'absent' && (after.kind === 'file' || after.kind === 'unsupported'))
return 'created'
- if ((before.kind === 'file' || before.kind === 'tooLarge') && after.kind === 'absent')
+ if ((before.kind === 'file' || before.kind === 'tooLarge' || before.kind === 'unsupported') && after.kind === 'absent')
return 'deleted'
return 'modified'
}
@@ -563,6 +564,23 @@ async function commitEntrySize(store: SnapshotStore, commit: string, path: strin
return undefined
}
+/**
+ * Git mode of one committed path ('100644' regular, '100755' executable,
+ * '120000' symlink, '160000' submodule), or undefined when absent.
+ * P1-3: symlinks are identified here so stateAt/restore can refuse them
+ * instead of silently writing the link target as file content.
+ */
+async function commitEntryMode(store: SnapshotStore, commit: string, path: string): Promise<string | undefined> {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '-z', commit, '--', path])
+ for (const line of output.toString('utf8').split('\0')) {
+ // mode SP type SP oid TAB path
+ const tab = line.lastIndexOf('\t')
+ if (tab !== -1 && line.slice(tab + 1) === path)
+ return line.slice(0, tab).split(' ')[0]
+ }
+ return undefined
+}
+
async function commitBytes(store: SnapshotStore, commit: string, path: string): Promise<Buffer> {
const output = await runGit(store.repoDir, store.workspaceDir, ['show', `${commit}:${path}`], {}, MAX_FILE_BYTES + 1)
if (output.length > MAX_FILE_BYTES)
@@ -584,7 +602,12 @@ function digest(bytes: Buffer): string {
export async function stateAt(store: SnapshotStore, commit: string, path: string): Promise<PathState> {
// stateAt only inspects the private snapshot repo (commit:path revisions),
- // never the filesystem, so a symlinked or odd path simply reads as absent.
+ // never the filesystem.
+ // P1-3: a symlink entry ('120000') must not masquerade as a regular file —
+ // its blob is just the link target text. Report it as unsupported so the
+ // plan flags it and restore refuses, instead of writing wrong content.
+ if ((await commitEntryMode(store, commit, path)) === GIT_SYMLINK_MODE)
+ return { kind: 'unsupported', digest: null }
if (!await commitEntry(store, commit, path))
return { kind: 'absent', digest: null }
// Oversized blobs are reported instead of thrown: the caller can mark the
@@ -666,6 +689,12 @@ export async function restorePath(store: SnapshotStore, commit: string, path: st
return { path, result: 'removed' }
}
+ // P1-3: a symlink entry must never be "restored" by writing the link target
+ // text as a regular file. Fail this one path with a stable code so the undo
+ // loop reports it as not restored instead of corrupting the workspace type.
+ if ((await commitEntryMode(store, commit, path)) === GIT_SYMLINK_MODE)
+ throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a symlink in the snapshot; undo cannot restore symlinks (recreate the link manually if intended)`)
+
// Restoring an oversized blob would require materializing it through the
// same output-limited channel. Fail this one path with a stable code so the
// undo loop can report it as not restored instead of dying mid-plan.
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
index 6c5eed11..140a106c 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
@@ -286,6 +286,7 @@ export async function buildPlanEntries(runtime: WorkspaceRuntime, workspaceDir:
change: await classifyPathChange(runtime.store, target.before_ref!, target.after_ref!, path),
conflict: !await diskMatchesSnapshot(runtime, workspaceDir, target.after_ref!, path),
tooLarge: beforeState.kind === 'tooLarge',
+ unsupported: beforeState.kind === 'unsupported',
}
}))
}
@@ -305,12 +306,14 @@ export interface PlanFormatOptions {
export async function formatPlan(runtime: WorkspaceRuntime, target: TurnRow, entries: PlanEntry[], options: PlanFormatOptions): Promise<string> {
const conflicts = entries.filter(entry => entry.conflict)
const oversized = entries.filter(entry => entry.tooLarge)
+ const unsupported = entries.filter(entry => entry.unsupported)
const lines: string[] = []
lines.push(`${options.preview ? 'Undo preview' : options.dryRun ? 'Undo plan' : 'Undo preflight'}: turn ${target.turn_id}; ${entries.length} file(s) (${summarizeChanges(entries)}); ${conflicts.length} conflict(s).`)
for (const entry of entries) {
const flag = entry.conflict ? ' [conflict]' : ''
const sizeFlag = entry.tooLarge ? ' [too large]' : ''
- lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}${sizeFlag}`)
+ const unsupportedFlag = entry.unsupported ? ' [unsupported]' : ''
+ lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}${sizeFlag}${unsupportedFlag}`)
}
if (oversized.length > 0) {
lines.push('')
@@ -318,6 +321,12 @@ export async function formatPlan(runtime: WorkspaceRuntime, target: TurnRow, ent
for (const entry of oversized)
lines.push(` ${entry.path}`)
}
+ if (unsupported.length > 0) {
+ lines.push('')
+ lines.push('Unrestorable entries (symlinks and other unsupported types in the before snapshot) will be reported as not restored; recreate them manually if intended:')
+ for (const entry of unsupported)
+ lines.push(` ${entry.path}`)
+ }
if (options.preview || options.withDiffs) {
lines.push('')
lines.push('Undo will apply (turn output → restored state):')
@@ -427,6 +436,12 @@ export async function executeUndoRestore(
const restoredPaths: string[] = []
const failedPaths: { path: string, reason: string }[] = []
for (const entry of targets) {
+ // P1-3: symlink/其他不可恢复类型的快照条目直接跳过并上报,
+ // 不再伪装成普通文件写回(restorePath 内还有同规则的双保险)。
+ if (entry.unsupported) {
+ failedPaths.push({ path: entry.path, reason: 'TURNREWIND_UNSUPPORTED_TARGET: snapshot entry is a symlink or otherwise unrestorable' })
+ continue
+ }
try {
await restorePath(runtime.store, target.before_ref!, entry.path)
restoredPaths.push(entry.path)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
index bb1d4be5..aaade57e 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
@@ -72,6 +72,8 @@ export interface PlanEntry {
conflict: boolean
/** before 快照超限:恢复会失败并计入未恢复清单。 */
tooLarge: boolean
+ /** before 快照中的条目不可恢复(symlink 等):恢复会跳过并计入未恢复清单。 */
+ unsupported: boolean
}
/** /undo 命令解析结果(confirm/cancel 为标志;plan id 或 turn id 落在 turnId)。 */
diff --git a/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js b/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
index 0f270ad7..011db284 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
@@ -55,6 +55,18 @@ it('resolveOwnerSessionId never guesses from missing or invalid ids', () => {
assert.equal(client.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: '' } }), 'session-a')
})
+it('parseUndoOutput strips the unsupported flag from unrestorable entries', () => {
+ const parsed = client.parseUndoOutput([
+ 'Undo preflight: turn s:1; 2 file(s) (modified 2, created 0, deleted 0); 0 conflict(s).',
+ ' modified link [unsupported]',
+ ' modified keep.txt',
+ ].join('\n'))
+ assert.deepEqual(
+ parsed.files.map(file => [file.path, file.conflict]),
+ [['link', false], ['keep.txt', false]],
+ )
+})
+
it('parseUndoOutput still extracts the pending plan id', () => {
const parsed = client.parseUndoOutput([
'Undo preflight: turn s:1; 1 file(s); 0 conflicts.',
diff --git a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
index 141f6b89..05a1872c 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { it } from 'vitest'
@@ -7,6 +7,41 @@ import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState,
import { completeUndoTransaction, createOperation, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../src/host/service/ledger'
import { initGitWorkspace } from './git-test-utils.js'
+it('reports snapshot symlinks as unsupported and refuses to restore them', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-snap-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await initGitWorkspace(workspace)
+ await writeFile(join(workspace, 'target.txt'), 'target\n')
+ try {
+ await symlink(join(workspace, 'target.txt'), join(workspace, 'link'))
+ }
+ catch (error) {
+ if (error.code === 'EPERM' || error.code === 'EACCES')
+ return
+ throw error
+ }
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const snapshot = await captureSnapshot(store, 'refs/turnrewind/symlink-snap', 'snap')
+
+ // The snapshot entry has git mode 120000: stateAt reports unsupported
+ // instead of masquerading the link target text as file content (P1-3).
+ assert.equal((await stateAt(store, snapshot.commit, 'link')).kind, 'unsupported')
+
+ // Restore refuses even when the disk link is gone — the blob is only the
+ // link target text and must never be written as a regular file.
+ await rm(join(workspace, 'link'))
+ await assert.rejects(
+ () => restorePath(store, snapshot.commit, 'link'),
+ /TURNREWIND_UNSUPPORTED_TARGET.*symlink/u,
+ )
+ assert.equal(await readFile(join(workspace, 'target.txt'), 'utf8'), 'target\n')
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
it('captures and restores modified, added, and deleted files', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-test-'))
const workspace = join(root, 'workspace')
diff --git a/packages/dsh-tauri-turnrewind-ts/test/security.test.js b/packages/dsh-tauri-turnrewind-ts/test/security.test.js
index 181add3c..9b8a8e2a 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/security.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/security.test.js
@@ -1,9 +1,11 @@
import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readdir, rm, symlink, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
-import { join } from 'pathe'
+import { join, resolve } from 'pathe'
import { it } from 'vitest'
import { captureSnapshot, createSnapshotStore, currentState, restorePath, stateAt } from '../src/host/service/git-snapshot'
+import { insertTurn, openLedger, settleTurn } from '../src/host/service/ledger'
+import { applyUndo } from '../src/index'
import { initGitWorkspace } from './git-test-utils.js'
it('delegates secret-file exclusion to the source repository ignore rules', async () => {
@@ -154,3 +156,69 @@ it('refuses symlinked workspace paths during inspection and restore', async () =
await rm(root, { recursive: true, force: true })
}
})
+
+it('keeps snapshot symlinks unrestorable and reported by undo', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-undo-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await initGitWorkspace(workspace)
+ await writeFile(join(workspace, 'keep.txt'), 'before\n')
+ await writeFile(join(workspace, 'original.txt'), 'original\n')
+ try {
+ await symlink('original.txt', join(workspace, 'link'))
+ }
+ catch (error) {
+ if (error.code === 'EPERM' || error.code === 'EACCES')
+ return
+ throw error
+ }
+ const db = openLedger(join(root, 'ledger'))
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ await captureSnapshot(store, 'refs/turnrewind/sl-before', 'before')
+
+ // The turn: replace the symlink with a regular file and edit keep.txt.
+ await rm(join(workspace, 'link'))
+ await writeFile(join(workspace, 'link'), 'now-a-file\n')
+ await writeFile(join(workspace, 'keep.txt'), 'after\n')
+ await captureSnapshot(store, 'refs/turnrewind/sl-after', 'after', 'refs/turnrewind/sl-before')
+ insertTurn(db, {
+ turnId: 'session:1',
+ sessionId: 'session',
+ workspaceKey: resolve(workspace).toLowerCase(),
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/sl-before',
+ })
+ settleTurn(db, 'session:1', 'refs/turnrewind/sl-after')
+
+ const runtime = {
+ db,
+ store,
+ workspaceKey: resolve(workspace).toLowerCase(),
+ parentRef: 'refs/turnrewind/sl-after',
+ undoing: false,
+ }
+ const invocation = (rawInput = '') => ({
+ rawInput,
+ agent: { session: { id: 'session', header: { cwd: workspace } } },
+ })
+
+ // The preview flags the symlink entry as unsupported (P1-3).
+ const preview = await applyUndo(runtime, new Map(), invocation())
+ assert.equal(preview.kind, 'success')
+ assert.match(preview.text, /link \[unsupported\]/u)
+ assert.match(preview.text, /Unrestorable entries/u)
+
+ // Confirm: keep.txt restores normally; the link is reported as not
+ // restored and stays a regular file instead of receiving target text.
+ const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]
+ const confirmed = await applyUndo(runtime, new Map(), invocation(`--confirm ${planId}`))
+ assert.equal(confirmed.kind, 'success')
+ assert.match(confirmed.text, /Not restored \(1 file\(s\)\): link/u)
+ assert.equal(await readFile(join(workspace, 'link'), 'utf8'), 'now-a-file\n')
+ assert.equal(await readFile(join(workspace, 'keep.txt'), 'utf8'), 'before\n')
+ db.close()
+ }
+ finally {
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
+ }
+})