DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): correctness hardening sweep (audit P2-11 + P1-4 leftovers)
yingtianlanb18ecd956253
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.tsindex 14ee3edb..26553c9d 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts@@ -75,7 +75,7 @@ export interface HostApplyContext {webServer: { register: (route: unknown) => () => void }on: (event: string, listener: (...args: any[]) => void) => voideffect: (factory: () => (() => void) | void, label?: string) => () => void- logger?: { warn?: (message: string) => void }+ logger?: { warn?: (message: string) => void, error?: (message: string) => void }}interface ActiveEntry {@@ -191,6 +191,21 @@ export function apply(ctx: HostApplyContext): void {// validation, conflict checks and the private snapshot repository remain.const dataRoot = rootDir()const ledger = openLedger(dataRoot)+ // P2-11: 日志统一走 ctx.logger(宿主注入的结构化日志),console 仅兜底。+ const log = {+ warn: (message: string): void => {+ if (ctx.logger?.warn)+ ctx.logger.warn(message)+ else+ console.warn(message)+ },+ error: (message: string): void => {+ if (ctx.logger?.error)+ ctx.logger.error(message)+ else+ console.error(message)+ },+ }// P1-6:needs-recovery 围栏改为实时查库(hasNeedsRecoveryWorkspace),// 运行期落围栏的 workspace 立即被拦截,不再依赖启动时加载的内存快照。// One-shot at startup: consumed notices older than a week have no readers@@ -248,14 +263,14 @@ export function apply(ctx: HostApplyContext): void {// exist inside the atomic-restore crash window.const resurrected = restoreCrashedSwaps(workspaceDir)for (const path of resurrected)- console.warn(`turnrewind: resurrected ${path} in ${workspaceDir} from a crashed restore swap`)+ log.warn(`turnrewind: resurrected ${path} in ${workspaceDir} from a crashed restore swap`)// 容量治理(P2-4):workspace 首次触碰是安全点(无活动 turn、无 undo)。// 超出保留条数的 turn 标记过期;仓库超限整仓重建(下次 capture 自愈基线)。const retention = enforceRetention(ledger, store)if (retention.expiredByCount > 0)- console.warn(`turnrewind: retention expired ${retention.expiredByCount} turn(s) in ${workspaceDir} (kept the most recent ones)`)+ log.warn(`turnrewind: retention expired ${retention.expiredByCount} turn(s) in ${workspaceDir} (kept the most recent ones)`)if (retention.rebuilt)- console.warn(`turnrewind: snapshot repository for ${workspaceDir} rebuilt by retention (${retention.repoSizeMb.toFixed(1)} MB over the cap; ${retention.expiredByRebuild} turn(s) archived)`)+ log.warn(`turnrewind: snapshot repository for ${workspaceDir} rebuilt by retention (${retention.repoSizeMb.toFixed(1)} MB over the cap; ${retention.expiredByRebuild} turn(s) archived)`)runtime = {db: ledger,store,@@ -281,9 +296,9 @@ export function apply(ctx: HostApplyContext): void {}}catch (error) {- console.error(`turnrewind: failed to record skipped turn ${turnId}: ${String(error)}`)+ log.error(`turnrewind: failed to record skipped turn ${turnId}: ${String(error)}`)}- console.error(`turnrewind: skipped turn ${turnId}: ${reason}`)+ log.error(`turnrewind: skipped turn ${turnId}: ${reason}`)}function reserveTurnBaseline(agent: { session: { id: string, header?: { cwd?: string } } }, turn: number): ActiveEntry | undefined {@@ -416,7 +431,7 @@ export function apply(ctx: HostApplyContext): void {recordSkipped(key, sessionId, runtime.workspaceKey, startedAt, reason, false)settleDeferred(baseline, { ok: false, reason })if (!disposed && !runtime.disposed)- console.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)+ log.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)}}void enqueueTurnTask(sessionId, baselineTask).catch((error: unknown) => {@@ -429,7 +444,7 @@ export function apply(ctx: HostApplyContext): void {recordSkipped(key, sessionId, runtime.workspaceKey, startedAt, reason, false)settleDeferred(baseline, { ok: false, reason })if (!disposed && !runtime.disposed)- console.error(`turnrewind: baseline queue failed for ${key}: ${String(error)}`)+ log.error(`turnrewind: baseline queue failed for ${key}: ${String(error)}`)})return entry}@@ -574,7 +589,7 @@ export function apply(ctx: HostApplyContext): void {if (disposed)return { kind: 'reject' }if (!entry && workspaceForAgent(agent) && !untrackedTurns.has(key) && !endedTurns.has(key))- console.error(`turnrewind: no baseline reservation for ${key}; turn is explicitly untracked`)+ log.error(`turnrewind: no baseline reservation for ${key}; turn is explicitly untracked`)const decision = await next()if (decision.kind === 'reject' || signal.aborted || disposed)return decision@@ -622,7 +637,7 @@ export function apply(ctx: HostApplyContext): void {ctx.on('agent/error', (payload: { agent: { session: { id: string } }, turn: number, error: unknown }) => {// Keep the active record until turn/end or the idle fallback. In particular,// model switching can emit an error before the final partial writes finish.- console.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)+ log.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)})ctx.on('agent/status', ({ agent, status }: { agent: { session: { id: string } }, status: string }) => {if (disposed || status !== 'idle')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.tsindex 2ad0a2cb..26118a12 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@@ -290,6 +290,17 @@ function normalizeSnapshotRef(ref: string): string {return ref}+/**+ * P2-11: 所有插值进 git 参数的 commit/reffed 参数统一过校验——只接受+ * `refs/turnrewind/*` ref 名或 40 位 SHA(gitRef/captureSnapshot 的返回+ * 形态)。ledger 之外的取值在这里被拦下,而不是散落到各 git 子进程。+ */+function assertCommitRef(commit: string): string {+ if (typeof commit !== 'string' || !(commit.startsWith(SNAPSHOT_REF_PREFIX) || /^[0-9a-f]{40}$/.test(commit)))+ throw new Error(`TURNREWIND_REF_UNSUPPORTED: ${String(commit)}`)+ return commit+}+export async function gitRef(repoDir: string, workspaceDir: string, ref: string): Promise<string | undefined> {try {const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', normalizeSnapshotRef(ref)])@@ -461,6 +472,8 @@ async function captureInto(store: SnapshotStore, refName: string, message: strin}export async function snapshotDiff(store: SnapshotStore, beforeCommit: string, afterCommit: string): Promise<string[]> {+ assertCommitRef(beforeCommit)+ assertCommitRef(afterCommit)const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '-z', '--no-renames', beforeCommit, afterCommit])return [...new Set(output.toString('utf8').split('\0').filter(Boolean))]}@@ -487,6 +500,8 @@ export async function classifyPathChange(store: SnapshotStore, beforeCommit: str/** Unified diff of one path between two snapshot commits, truncated to maxLines. */export async function snapshotFileDiff(store: SnapshotStore, fromCommit: string, toCommit: string, path: string, maxLines?: number): Promise<string> {+ assertCommitRef(fromCommit)+ assertCommitRef(toCommit)const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--no-renames', fromCommit, toCommit, '--', path])return truncateDiff(output.toString('utf8'), maxLines)}@@ -525,6 +540,7 @@ async function hashDiskFile(store: SnapshotStore, workspaceDir: string, path: st* snapshot repo; the user's own repository is never touched.*/export async function diffAgainstDisk(store: SnapshotStore, commit: string, path: string, maxLines?: number): Promise<string> {+ assertCommitRef(commit)const from = await blobFor(store, commit, path)const to = await hashDiskFile(store, store.workspaceDir, path)if (to === undefined)@@ -543,11 +559,12 @@ export async function diffAgainstDisk(store: SnapshotStore, commit: string, path}/**- * 一次 `ls-tree -l` 读取条目的 mode 与 size:stateAt/restorePath/blobFor+ * 一次 `ls-tree -l` 读取条目的 mode、type 与 size:stateAt/restorePath/blobFor* 共用,避免同一路径多次子进程调用。size 为 undefined 表示未知(submodule)。*/interface CommitEntryInfo {mode: string+ type: stringsize: number | undefined}@@ -561,6 +578,7 @@ async function commitEntryInfo(store: SnapshotStore, commit: string, path: strinconst size = Number(meta.at(-1))return {mode: meta[0] ?? '100644',+ type: meta[1] ?? 'blob',size: Number.isFinite(size) && meta.at(-1) !== '-' ? size : undefined,}}@@ -593,10 +611,13 @@ export async function stateAt(store: SnapshotStore, commit: string, path: string// 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.+ // P2-11: gitlink/submodule 条目(type 'commit')同样 unsupported——blob 是+ // commit hash,写回会是错误内容。+ assertCommitRef(commit)const info = await commitEntryInfo(store, commit, path)if (!info)return { kind: 'absent', digest: null }- if (info.mode === GIT_SYMLINK_MODE)+ if (info.mode === GIT_SYMLINK_MODE || info.type === 'commit')return { kind: 'unsupported', digest: null }// Oversized blobs are reported instead of thrown: the caller can mark the// entry and continue, so one huge file never aborts a whole undo preview.@@ -658,6 +679,7 @@ function rmSyncWithRetry(target: string, attempts: number = 5): void {* sweep (restoreCrashedSwaps) resurrects a .bak whose target is missing.*/export async function restorePath(store: SnapshotStore, commit: string, path: string): Promise<RestoreResult> {+ assertCommitRef(commit)let target = assertSafePath(store.workspaceDir, path)const entry = await commitEntryInfo(store, commit, path)// P1-5: the git subprocess above opens a TOCTOU window — an external@@ -690,11 +712,11 @@ export async function restorePath(store: SnapshotStore, commit: string, path: streturn { 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 (entry.mode === 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)`)+ // P1-3/P2-11: symlink 与 gitlink/submodule 条目绝不能以普通文件形式写回+ // (前者内容是 link target,后者是 commit hash)。单路径稳定错误码,+ // undo 循环计入未恢复清单而不是破坏工作区类型。+ if (entry.mode === GIT_SYMLINK_MODE || entry.type === 'commit')+ throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a symlink or submodule in the snapshot; undo cannot restore it (recreate it 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@@ -782,8 +804,14 @@ export function restoreCrashedSwaps(workspaceDir: string): string[] {}for (const entry of entries) {const full = join(dir, entry.name)- if (entry.isDirectory() && entry.name !== '.git' && !entry.name.endsWith(BAK_SUFFIX))+ // P2-11: Windows junction 的 Dirent 可能报 isDirectory()——递归进+ // junction 会越过 workspace 边界。目录在进入前先 lstat 排除 reparse+ // point(symlink/junction 均命中 isSymbolicLink)。+ if (entry.isDirectory() && entry.name !== '.git' && !entry.name.endsWith(BAK_SUFFIX)) {+ if (lstatSync(full, { throwIfNoEntry: false })?.isSymbolicLink())+ continuevisit(full)+ }if (entry.isFile() && entry.name.endsWith(BAK_SUFFIX)) {const target = full.slice(0, -BAK_SUFFIX.length)// Windows antivirus/indexers hold brief handles on freshly renameddiff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/guard.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/guard.tsindex 6e88fff7..78ded50d 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/guard.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/guard.ts@@ -40,6 +40,13 @@ function foldCase(path: string): string {export function isSystemSensitiveWorkspace(workspaceDir: string): boolean {const workspace = foldCase(normalizeDir(workspaceDir))+ // P2-11: UNC 共享(//server/share/...)——分享根(仅 server/share 两段)+ // 是一整台机器的导出面,快照范围不可控,直接拒绝;更深的子目录允许。+ if (workspace.startsWith('//')) {+ const segments = workspace.split('/').filter(Boolean)+ if (segments.length <= 2)+ return true+ }const home = foldCase(normalizeDir(homedir()))if (workspace === home)return truediff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.tsindex 4db9824f..8fb2efd3 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts@@ -163,6 +163,16 @@ export function openLedger(rootDir: string): Ledger {// refuses new rewind work until purged). Expired plans are swept too.db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)db.prepare(`UPDATE operations SET outcome = 'needs-recovery', settled_at = COALESCE(settled_at, ?), error = 'plugin restarted while the operation was applying; workspace recovery is required' WHERE outcome = 'applying'`).run(new Date().toISOString())+ // P2-11: 崩溃残留的 applying plan 精确清扫——+ // 目标 turn 已 undone → undo 事务实际完成:plan 标 applied(结果如实);+ // 否则执行状态未知(操作已转 needs-recovery 围栏接管):plan 转 expired。+ db.prepare(`+ UPDATE pending_plans SET status = 'applied',+ result_text = COALESCE(result_text, 'host restarted while this plan was applying; the undo was applied')+ WHERE status = 'applying'+ AND EXISTS (SELECT 1 FROM turns WHERE turns.turn_id = pending_plans.turn_id AND turns.status = 'undone')+ `).run()+ db.prepare(`UPDATE pending_plans SET status = 'expired', result_text = COALESCE(result_text, 'host restarted while this plan was applying') WHERE status = 'applying'`).run()prunePendingPlans(db)return db}@@ -551,6 +561,15 @@ export function pruneConsumedNotices(db: Ledger, maxAgeMs: number = 7 * 24 * 60return Number(db.prepare('DELETE FROM rewind_notices WHERE status = \'consumed\' AND claimed_at < ?').run(cutoff).changes)}+/** notice 路径清单上限(P1-4):超出部分以摘要行代替,防账本行与模型上下文膨胀。 */+export const MAX_NOTICE_PATHS = 500++function capNoticePaths(paths: string[]): string[] {+ return paths.length > MAX_NOTICE_PATHS+ ? [...paths.slice(0, MAX_NOTICE_PATHS), `…and ${paths.length - MAX_NOTICE_PATHS} more path(s)`]+ : paths+}+/** undo 完成事务:turn → undone、operation → applied、notice 入队。 */export interface UndoCompletion {noticeId: string@@ -600,7 +619,7 @@ export function completeUndoTransaction(db: Ledger, completion: UndoCompletion):completion.workspaceKey,completion.targetTurnId,JSON.stringify([completion.targetTurnId]),- JSON.stringify([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)]),+ JSON.stringify(capNoticePaths([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)])),completion.createdAt,)db.exec('COMMIT')@@ -674,7 +693,7 @@ export function completeRedoTransaction(db: Ledger, completion: RedoCompletion):completion.workspaceKey,completion.targetTurnId,JSON.stringify([completion.targetTurnId]),- JSON.stringify([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)]),+ JSON.stringify(capNoticePaths([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)])),completion.createdAt,)db.exec('COMMIT')diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.tsindex bac3c0ab..7f379547 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts@@ -320,18 +320,35 @@ export interface PlanFormatOptions {withDiffs?: boolean}+export interface PlanFormatOptions {+ preview?: boolean+ dryRun?: boolean+ withDiffs?: boolean+}++/** P1-4:计划输出的规模上限——清单条数与逐文件 diff 都有界,防 UI/上下文膨胀。 */+const MAX_LISTED_FILES = 200+const MAX_DIFF_FILES = 50++function capList<T>(items: T[], max: number): { shown: T[], total: number, omitted: number } {+ return { shown: items.slice(0, max), total: items.length, omitted: Math.max(0, items.length - max) }+}++function omittedNote(omitted: number, label: string): string {+ return ` …and ${omitted} more ${label} (not listed)`+}+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]' : ''- const unsupportedFlag = entry.unsupported ? ' [unsupported]' : ''- lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}${sizeFlag}${unsupportedFlag}`)- }+ const listing = capList(entries.map(entry => `${entry.change.padEnd(8)} ${entry.path}${entry.conflict ? ' [conflict]' : ''}${entry.tooLarge ? ' [too large]' : ''}${entry.unsupported ? ' [unsupported]' : ''}`), MAX_LISTED_FILES)+ for (const line of listing.shown)+ lines.push(` ${line}`)+ if (listing.omitted > 0)+ lines.push(omittedNote(listing.omitted, 'file(s)'))if (oversized.length > 0) {lines.push('')lines.push(`Oversized files (over the ${MAX_FILE_BYTES / (1024 * 1024)} MB restore limit) cannot be restored by this undo; they will be reported as not restored:`)@@ -347,20 +364,26 @@ export async function formatPlan(runtime: WorkspaceRuntime, target: TurnRow, entif (options.preview || options.withDiffs) {lines.push('')lines.push('Undo will apply (turn output → restored state):')- for (const entry of entries) {+ const diffFiles = capList(entries, MAX_DIFF_FILES)+ for (const entry of diffFiles.shown) {const diff = await snapshotFileDiff(runtime.store, target.after_ref!, target.before_ref!, entry.path)lines.push(`--- ${entry.path}`)lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')}+ if (diffFiles.omitted > 0)+ lines.push(omittedNote(diffFiles.omitted, 'diff(s)'))}if (conflicts.length > 0) {lines.push('')lines.push('Conflicts (turn output → current disk; undo would overwrite these changes):')- for (const entry of conflicts) {+ const conflictFiles = capList(conflicts, MAX_DIFF_FILES)+ for (const entry of conflictFiles.shown) {const diff = await safeDiffAgainstDisk(runtime.store, target.after_ref!, entry.path)lines.push(`--- ${entry.path}`)lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')}+ if (conflictFiles.omitted > 0)+ lines.push(omittedNote(conflictFiles.omitted, 'conflict diff(s)'))if (!options.dryRun && !options.preview)lines.push('Re-run with --skip-conflicts to restore only the non-conflicted files, or --force to overwrite the conflicts.')}