DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): bind pending plans to their previewed snapshots (P1-2)
yingtianlan37dd7c3700c8
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.tsindex 46b48fe9..1a9fabc1 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts@@ -48,6 +48,7 @@ import {settleTurn,skipTurn,} from './service/ledger'+import { planDrift } from './service/planner'import { applyUndo, buildPlanEntries, executeUndoRestore, turnRefsExist, workspaceForAgent, workspaceHasActiveTurn, workspaceIssue, workspaceKeyFor } from './service/undo'/** 插件名(诊断元数据,与 shared/constants 的 TURNREWIND_PLUGIN_NAME 一致)。 */@@ -441,6 +442,11 @@ export function apply(ctx: HostApplyContext): void {if (target === undefined || target.reversible !== 1 || !target.before_ref || !target.after_ref || !await turnRefsExist(planRuntime.store, target))return [409, { error: 'the planned turn\'s snapshot data no longer exists — run /undo again' }]const paths = await snapshotDiff(planRuntime.store, target.before_ref, target.after_ref)+ // 计划漂移校验(P1-2):与命令路径同一规则——确认时的快照 ref 与+ // 重算 diff 必须与预览一致,否则拒绝并要求重新预览。+ const drift = planDrift(row, target, paths)+ if (drift)+ return [409, { error: `${drift} — run /undo again to refresh the plan` }]if (paths.length === 0) {markPendingPlanApplied(ledger, planId, sessionId, 'No file changes were recorded for this turn.')committed = truediff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.tsindex 9922a562..8ea3eea3 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts@@ -5,7 +5,7 @@* 一次性提示与恢复围栏(needs-recovery)的持久状态都住在这里。*/-import { randomUUID } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import { mkdirSync } from 'node:fs'import { DatabaseSync } from 'node:sqlite'import { dirname, join } from 'pathe'@@ -123,6 +123,10 @@ export interface PendingPlanRow {result_text: string | nullcreated_at: stringexpires_at: string+ /** 预览时的快照绑定(P1-2);旧格式行为 NULL,confirm 时跳过严格校验。 */+ before_ref: string | null+ after_ref: string | null+ paths_digest: string | null}export type Ledger = DatabaseSync@@ -140,6 +144,9 @@ export function openLedger(rootDir: string): Ledger {'ALTER TABLE rewind_notices ADD COLUMN reason TEXT','ALTER TABLE pending_plans ADD COLUMN status TEXT NOT NULL DEFAULT \'pending\'','ALTER TABLE pending_plans ADD COLUMN result_text TEXT',+ 'ALTER TABLE pending_plans ADD COLUMN before_ref TEXT',+ 'ALTER TABLE pending_plans ADD COLUMN after_ref TEXT',+ 'ALTER TABLE pending_plans ADD COLUMN paths_digest TEXT',]) {try {db.exec(migration)@@ -285,6 +292,11 @@ export function listNeedsRecoveryWorkspaces(db: Ledger): string[] {`).all() as { workspace_key: string }[]).map(row => row.workspace_key)}+/** 预览路径集的稳定摘要:排序后 sha256。confirm 时校验计划是否漂移(P1-2)。 */+export function planPathsDigest(paths: string[]): string {+ return createHash('sha256').update([...paths].sort().join('\0')).digest('hex')+}+export function createPendingPlan(db: Ledger, plan: PendingPlan): string {db.exec('BEGIN')try {@@ -294,9 +306,20 @@ export function createPendingPlan(db: Ledger, plan: PendingPlan): string {const planId = randomUUID()const createdAt = new Date().toISOString()db.prepare(`- INSERT INTO pending_plans(plan_id, session_id, workspace_key, turn_id, paths_json, created_at, expires_at)- VALUES (?, ?, ?, ?, ?, ?, ?)- `).run(planId, plan.sessionId, plan.workspaceKey, plan.turnId, JSON.stringify(plan.paths), createdAt, new Date(Date.now() + PENDING_PLAN_TTL_MS).toISOString())+ INSERT INTO pending_plans(plan_id, session_id, workspace_key, turn_id, paths_json, before_ref, after_ref, paths_digest, created_at, expires_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `).run(+ planId,+ plan.sessionId,+ plan.workspaceKey,+ plan.turnId,+ JSON.stringify(plan.paths),+ plan.beforeRef,+ plan.afterRef,+ planPathsDigest(plan.paths),+ createdAt,+ new Date(Date.now() + PENDING_PLAN_TTL_MS).toISOString(),+ )db.exec('COMMIT')return planId}@@ -311,6 +334,9 @@ export interface PendingPlan {workspaceKey: stringturnId: stringpaths: string[]+ /** 预览时的 turn 快照 ref,confirm 时校验未被改写(P1-2)。 */+ beforeRef: string+ afterRef: string}/**diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.tsindex c945f4c9..adab7945 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts@@ -4,6 +4,7 @@import type { DiskState, PathState } from '../types'import type { TurnRow } from './ledger'+import { planPathsDigest } from './ledger'/** 叶序收集 turn 及其全部后代(父撤销的递归范围)。 */export function collectDescendantTurns(turn: TurnRow, childrenByParent: Map<string, TurnRow[]>): TurnRow[] {@@ -49,3 +50,25 @@ export function classifyUndo(current: DiskState, expected: PathState): 'safe' |return 'conflict'return 'safe'}++/** pending plan 中参与漂移校验的绑定列(P1-2)。 */+export interface PendingPlanBinding {+ before_ref: string | null+ after_ref: string | null+ paths_digest: string | null+}++/**+ * 计划漂移校验(P1-2):确认时的 turn 快照 ref 与重算 diff 必须与预览一致,+ * 即「确认的就是预览时看到的」。三列任一为 NULL 视为旧格式 plan(5 分钟+ * TTL 内自然清空),跳过严格校验保持兼容。返回 undefined 表示未漂移。+ */+export function planDrift(plan: PendingPlanBinding, target: TurnRow, currentPaths: string[]): string | undefined {+ if (plan.before_ref === null || plan.after_ref === null || plan.paths_digest === null)+ return undefined+ if (target.before_ref !== plan.before_ref || target.after_ref !== plan.after_ref)+ return 'the turn snapshots no longer match the preview'+ if (planPathsDigest(currentPaths) !== plan.paths_digest)+ return 'the change set no longer matches the preview'+ return undefined+}diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.tsindex e2fb7fa9..fe4d33d1 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts@@ -9,7 +9,7 @@*/import type { PlanEntry, SnapshotStore, UndoInput } from '../types'-import type { Ledger, TurnRow } from './ledger'+import type { Ledger, PendingPlanRow, TurnRow } from './ledger'import { randomUUID } from 'node:crypto'import { resolve } from 'pathe'import { MAX_FILE_BYTES } from '../constants'@@ -51,7 +51,7 @@ import {settleOperation,} from './ledger'-import { classifyUndo } from './planner'+import { classifyUndo, planDrift } from './planner'// ————————————————— redo(与 undo 同等的生产加固:applying operation / 失败明细 / needs-recovery) —————————————————@@ -548,6 +548,7 @@ export async function applyUndo(}let target: TurnRow | undefined+ let planRow: (PendingPlanRow & { paths: string[] }) | undefinedlet pendingPlanClaimed = falselet pendingPlanCommitted = falseconst abortPendingPlanClaim = (): void => {@@ -565,6 +566,7 @@ export async function applyUndo(// Reserve the workspace before the first await so another confirm route// cannot start a concurrent restore during snapshot validation.runtime.undoing = true+ planRow = claim.rowconst pendingTurnId = claim.row.turn_idtarget = getTurn(runtime.db, pendingTurnId)if (!target || !await turnRefsExist(runtime.store, target)) {@@ -616,6 +618,15 @@ export async function applyUndo(runtime.undoing = truetry {const paths = await snapshotDiff(runtime.store, target.before_ref, target.after_ref)+ // 计划漂移校验(P1-2):确认时的快照 ref 与重算 diff 必须与预览一致,+ // 保证「确认的就是预览时看到的」。漂移即释放 claim 并要求重新预览。+ if (planRow) {+ const drift = planDrift(planRow, target, paths)+ if (drift) {+ abortPendingPlanClaim()+ return { kind: 'error', text: `${drift} — run /undo again to preview a fresh plan.` }+ }+ }if (paths.length === 0) {if (pendingPlanClaimed) {markPendingPlanApplied(runtime.db, parsed.turnId!, invocation.agent.session.id, 'No file changes were recorded for this turn.')@@ -645,6 +656,8 @@ export async function applyUndo(workspaceKey,turnId: target.turn_id,paths,+ beforeRef: target.before_ref!,+ afterRef: target.after_ref!,})return {kind: 'success',diff --git a/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js b/packages/dsh-tauri-turnrewind-ts/test/ledger.test.jsindex 341fb112..8d8277c7 100644--- a/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js+++ b/packages/dsh-tauri-turnrewind-ts/test/ledger.test.js@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'pathe'import { it } from 'vitest'-import { claimPendingPlan, claimRewindNotices, completeRedoTransaction, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'+import { claimPendingPlan, claimRewindNotices, completeRedoTransaction, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, planPathsDigest, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))@@ -444,9 +444,17 @@ it('claims a pending plan exactly once and serializes cancel/apply outcomes', asworkspaceKey: 'workspace',turnId: 'session:1',paths: ['a.txt'],+ beforeRef: 'refs/turnrewind/turn-1-before',+ afterRef: 'refs/turnrewind/turn-1-after',})const first = claimPendingPlan(db, planId, 'session')assert.equal(first.ok, true)+ if (first.ok) {+ // The preview binding (P1-2) is persisted with the plan.+ assert.equal(first.row.before_ref, 'refs/turnrewind/turn-1-before')+ assert.equal(first.row.after_ref, 'refs/turnrewind/turn-1-after')+ assert.equal(first.row.paths_digest, planPathsDigest(['a.txt']))+ }assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'applying')assert.equal(claimPendingPlan(db, planId, 'session').ok, false)assert.equal(markPendingPlanCancelled(db, planId, 'session'), false)diff --git a/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js b/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.jsindex b4495c0a..4b3e0f5a 100644--- a/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js+++ b/packages/dsh-tauri-turnrewind-ts/test/lifecycle.test.js@@ -130,6 +130,32 @@ it('applies a confirmed undo and reports redo as disabled', { timeout: 30000 },}})+it('rejects a confirm whose change set drifted from the preview', async () => {+ const { root, workspace, db, runtime, active, invocation } = await setupTurn()+ try {+ const preview = await applyUndo(runtime, active, invocation())+ assert.equal(preview.kind, 'success')+ const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]+ assert.ok(planId, 'preview must carry a pending plan id')++ // Simulate plan drift: the persisted binding no longer matches what the+ // confirm recomputes. The confirm must refuse and release the claim.+ db.prepare('UPDATE pending_plans SET paths_digest = ? WHERE plan_id = ?').run('0'.repeat(64), planId)+ const confirmed = await applyUndo(runtime, active, invocation(`--confirm ${planId}`))+ assert.equal(confirmed.kind, 'error')+ assert.match(confirmed.text, /change set no longer matches/u)++ // Nothing was restored and the plan stays pending for a fresh confirm.+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')+ const row = db.prepare('SELECT status FROM pending_plans WHERE plan_id = ?').get(planId)+ assert.equal(row.status, 'pending')+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})+it('rejects invalid option combinations', async () => {const { root, db, runtime, active, invocation } = await setupTurn()try {diff --git a/packages/dsh-tauri-turnrewind-ts/test/maintenance.test.js b/packages/dsh-tauri-turnrewind-ts/test/maintenance.test.jsindex 5b98f20b..269d1343 100644--- a/packages/dsh-tauri-turnrewind-ts/test/maintenance.test.js+++ b/packages/dsh-tauri-turnrewind-ts/test/maintenance.test.js@@ -140,12 +140,16 @@ it('purges pending plans bound to the workspace', async () => {workspaceKey: workspaceKey(workspace),turnId: 'session:1',paths: ['a.txt'],+ beforeRef: 'refs/turnrewind/turn-1-before',+ afterRef: 'refs/turnrewind/turn-1-after',})createPendingPlan(db, {sessionId: 'session',workspaceKey: workspaceKey(join(root, 'other')),turnId: 'session:2',paths: ['b.txt'],+ beforeRef: 'refs/turnrewind/turn-2-before',+ afterRef: 'refs/turnrewind/turn-2-after',})db.close()diff --git a/packages/dsh-tauri-turnrewind-ts/test/planner.test.js b/packages/dsh-tauri-turnrewind-ts/test/planner.test.jsindex 9346d084..ddec6a26 100644--- a/packages/dsh-tauri-turnrewind-ts/test/planner.test.js+++ b/packages/dsh-tauri-turnrewind-ts/test/planner.test.js@@ -1,6 +1,7 @@import assert from 'node:assert/strict'import { it } from 'vitest'-import { aggregatePathPlan, classifyUndo, collectDescendantTurns } from '../src/host/service/planner'+import { planPathsDigest } from '../src/host/service/ledger'+import { aggregatePathPlan, classifyUndo, collectDescendantTurns, planDrift } from '../src/host/service/planner'it('collects a selected turn subtree in leaf-first order', () => {const root = { turn_id: 'p' }@@ -27,3 +28,28 @@ it('classifies stale content as a conflict', () => {assert.equal(classifyUndo({ kind: 'file', digest: 'new' }, { kind: 'file', digest: 'old' }), 'conflict')assert.equal(classifyUndo({ kind: 'absent', digest: null }, { kind: 'file', digest: 'old' }), 'conflict')})++it('detects pending plan drift against the confirmed turn and diff', () => {+ const target = { turn_id: 's:1', before_ref: 'refs/turnrewind/b', after_ref: 'refs/turnrewind/a' }+ const binding = {+ before_ref: 'refs/turnrewind/b',+ after_ref: 'refs/turnrewind/a',+ paths_digest: planPathsDigest(['a.txt', 'b.txt']),+ }+ // Same refs and the same path set in any order: no drift.+ assert.equal(planDrift(binding, target, ['b.txt', 'a.txt']), undefined)+ // A different change set is drift even when the refs still match.+ assert.match(planDrift(binding, target, ['a.txt']), /change set no longer matches/u)+ // Rewritten turn refs are drift regardless of the recomputed paths.+ assert.match(+ planDrift(binding, { ...target, after_ref: 'refs/turnrewind/a2' }, ['a.txt', 'b.txt']),+ /snapshots no longer match/u,+ )+ // Legacy plans (NULL binding columns) skip strict checks for compatibility.+ assert.equal(planDrift({ before_ref: null, after_ref: null, paths_digest: null }, target, []), undefined)+})++it('produces a stable order-independent paths digest', () => {+ assert.equal(planPathsDigest(['b.txt', 'a.txt']), planPathsDigest(['a.txt', 'b.txt']))+ assert.notEqual(planPathsDigest(['a.txt']), planPathsDigest(['a.txt', 'b.txt']))+})