DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(dsh-tauri-turnrewind): same-page colored undo preview + snapshot guard
miaooo0000OOOOf8ec342dbcbe
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.mdindex 12054096..ddc73b7f 100644--- a/plugins/dsh-tauri-turnrewind/README.md+++ b/plugins/dsh-tauri-turnrewind/README.md@@ -12,11 +12,14 @@- 将快照映射记录到 `$DSH_HOME/turnrewind/ledger.sqlite`;- 注册人类命令 `/undo`;- `/undo` 只处理当前会话最新的单个可恢复 turn;-- `/undo --dry-run` 只输出预检计划,不修改文件;-- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖;+- `/undo --dry-run` 只输出预检计划(逐文件分类:修改/新建/删除),不修改文件;+- `/undo --preview` 额外输出每个文件撤销时将应用的 unified diff;+- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖,并给出「turn 产物 → 当前磁盘」的冲突 diff;+- 冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)处理;+- `/undo --redo` 重做最近一次已应用的 undo(磁盘在 undo 后被改动则拒绝);- 同一 workspace 的活动 turn 或 undo 操作互斥;- 插件重启时将未完成 turn 标记为 abandoned;-- 每次 Undo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;+- 每次 Undo/Redo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。## 使用方法@@ -46,7 +49,11 @@```text/undo/undo --dry-run+/undo --preview/undo <turn-id>+/undo --skip-conflicts+/undo --force+/undo --redo```当前不支持:@@ -55,7 +62,7 @@/undo --subtree```-父对话递归撤销、redo、消息旁 Undo 按钮和设置页模式切换尚未实现。+父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。## Undo 的工作区范围@@ -189,7 +196,7 @@ Undo preflight: turn <turn-id>; 5 file(s); 5 conflict(s): 4.txt, 5.txt, 6.txt, 7Windows 的 `CRLF` 与 Unix 的 `LF` 换行差异会被文本状态比较规范化,不应单独造成冲突。二进制文件仍按原始字节比较。-当前没有“跳过冲突文件”和“强制覆盖冲突文件”的用户命令;遇到冲突应先检查文件,再决定是否手动处理。+冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)处理;默认遇到冲突则拒绝并给出「人改了什么」的 diff。## 多次 Undo 与模型提示@@ -218,6 +225,27 @@ notice 只消费一次。下一次模型 step 后不会重复注入。## Git 与快照存储+### 快照护栏(建 git 追踪前先预估)++在创建任何私有 Git 快照仓库之前,插件会先**预估该工作区会被追踪多少内容**:统计文件数、总大小、单个最大文件、目录嵌套深度(复用与真实快照相同的排除规则,如 node_modules/.git/dist 等不统计)。只要任意一项超过配置阈值,就**不建立 git 追踪**,该工作区的 turn 不会做快照、`/undo` 也不可用(因为没有可恢复内容)。这能避免把巨大或极深的目录(node_modules 密集仓库、构建树、以及任何类似家目录的东西)整盘塞进私有仓库。++阈值是插件设置,可在 profile 的 `cordis.patch.yml` 的插件 config 里调整:++```yaml+- insert:+ - id: turnrewind+ name: dsh-tauri-turnrewind+ config:+ guard:+ maxFileCount: 10000 # 最多追踪文件数+ maxTotalBytes: 536870912 # 总大小上限(512MB)+ maxFileBytes: 52428800 # 单个文件上限(50MB)+ maxDepth: 20 # 目录嵌套深度上限+ maxDirs: 10000 # 目录数上限+```++被护栏拒绝的工作区会在日志里输出 `turnrewind: skip snapshot tracking for <dir>: <reason>`,且结果被缓存(不会每回合重扫大目录)。与 `$HOME` 防护互为兜底:会话 cwd 为家目录时直接拒绝,其他大目录由本护栏拦截。+快照存放在插件私有目录:```textdiff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.jsnew file mode 100644index 00000000..129ddfc8--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/lib/client.js@@ -0,0 +1,163 @@+// dsh-tauri-turnrewind — client bundle (browser).+// Registers a keyed renderer for the `conversation.chat.commandview` slot at+// key "undo", replacing the generic plain-text command card with a diff-aware+// view that renders deletions red and additions green.+//+// Hand-written against the DSH client module contract:+// window.__ModuleLoader__.load({ id, factory }) where factory receives a+// CommonJS-style `require` and must export `apply` (cordis plugin) + `inject`+// (list of cordis services the apply() context needs).+window.__ModuleLoader__.load({+ id: "dsh-tauri-turnrewind/client",+ factory: (require) => {+ var module = { exports: {} };+ var exports = module.exports;+ var React = require("react");+ var jsxRuntime = require("react/jsx-runtime");+ var jsx = jsxRuntime.jsx;+ var jsxs = jsxRuntime.jsxs;++ var inject = ["slots"];++ // ------------------------------------------------------------------+ // Unified-diff line classification.+ // ------------------------------------------------------------------+ function classifyLine(raw) {+ var line = raw;+ if (/^\s*diff --git /.test(line)) return { kind: "meta", text: line.trim() };+ if (/^\s*index /.test(line)) return { kind: "meta", text: line.trim() };+ if (/^\s*---\s+a\//.test(line)) return { kind: "meta", text: line.trim() };+ if (/^\s*\+\+\+\s+b\//.test(line)) return { kind: "meta", text: line.trim() };+ if (/^\s*@@/.test(line)) return { kind: "hunk", text: line.trim() };+ if (/^\s*-/.test(line)) return { kind: "del", text: line.replace(/^\s*-/, "") };+ if (/^\s*\+/.test(line)) return { kind: "add", text: line.replace(/^\s*\+/, "") };+ return { kind: "ctx", text: line.replace(/^\s+/, "") };+ }++ function isDiffLine(raw) {+ return /^\s*(diff --git |index |--- |\+\+\+ |@@|-[^-]|\+[^+]|-$|\+$)/.test(raw);+ }++ // A "section separator" we emit in the preview, e.g. "--- undo-demo.txt".+ function isFileSeparator(raw) {+ return /^---\s+(?!a\/)\S/.test(raw);+ }++ // ------------------------------------------------------------------+ // Rendering.+ // ------------------------------------------------------------------+ var COLORS = {+ delBg: "rgba(248,81,73,0.16)",+ delSign: "#f85149",+ addBg: "rgba(46,160,67,0.16)",+ addSign: "#3fb950",+ hunk: "#79b8ff",+ meta: "#8b949e",+ ctx: "#c9d1d9",+ border: "#30363d",+ bg: "var(--dsw-alias-markdown-code-block, #161b22)",+ label: "var(--dsw-alias-label-tertiary, #8b949e)",+ title: "var(--dsw-alias-label-secondary, #c9d1d9)",+ };++ function diffLineStyle(kind) {+ switch (kind) {+ case "del": return { background: COLORS.delBg, color: COLORS.ctx };+ case "add": return { background: COLORS.addBg, color: COLORS.ctx };+ case "hunk": return { color: COLORS.hunk };+ case "meta": return { color: COLORS.meta };+ default: return { color: COLORS.ctx };+ }+ }++ function signFor(kind) {+ if (kind === "del") return "-";+ if (kind === "add") return "+";+ return " ";+ }++ function DiffLine(props) {+ var entry = props.entry;+ var style = diffLineStyle(entry.kind);+ return jsxs("div", {+ style: Object.assign(+ { display: "flex", fontFamily: "var(--ds-font-family-code, monospace)", fontSize: "12.5px", lineHeight: "20px", paddingLeft: 8, paddingRight: 8, whiteSpace: "pre-wrap", wordBreak: "break-all" },+ style+ ),+ children: [+ jsx("span", {+ style: { width: 16, flex: "none", color: entry.kind === "del" ? COLORS.delSign : entry.kind === "add" ? COLORS.addSign : COLORS.meta, userSelect: "none" },+ children: signFor(entry.kind)+ }),+ jsx("span", { style: { flex: 1 }, children: entry.text })+ ]+ });+ }++ function UndoCommandView(props) {+ var node = props.node || {};+ var outcome = node.outcome;+ var text = outcome && typeof outcome.text === "string" ? outcome.text : "";+ var state = outcome == null ? "running" : outcome.kind === "error" ? "error" : "ok";+ var summary = text ? text.split("\n")[0] : (state === "error" ? "失败" : state === "running" ? "运行中" : "已完成");+ var body = text.indexOf("\n") >= 0 ? text : null;+ var expandedState = React.useState(body !== null);+ var expanded = expandedState[0];+ var setExpanded = expandedState[1];++ var lines = body ? body.split("\n") : [];+ var rows = [];+ for (var i = 0; i < lines.length; i++) {+ var raw = lines[i];+ if (isFileSeparator(raw)) {+ rows.push(jsx("div", {+ style: { fontFamily: "var(--ds-font-family-code, monospace)", fontSize: "12.5px", lineHeight: "20px", paddingLeft: 8, paddingRight: 8, color: COLORS.title, fontWeight: 600 },+ children: raw.replace(/^---\s+/, "")+ }, "fs" + i));+ }+ else if (isDiffLine(raw)) {+ rows.push(jsx(DiffLine, { entry: classifyLine(raw) }, "l" + i));+ }+ else {+ rows.push(jsx("div", {+ style: { fontFamily: "var(--ds-font-family-code, monospace)", fontSize: "12.5px", lineHeight: "20px", paddingLeft: 8, paddingRight: 8, color: COLORS.label, whiteSpace: "pre-wrap", wordBreak: "break-word" },+ children: raw+ }, "p" + i));+ }+ }++ return jsxs("div", {+ style: { border: "1px solid " + COLORS.border, background: COLORS.bg, borderRadius: 12, margin: "4px 0 4px 4px", overflow: "hidden", maxWidth: "100%" },+ children: [+ jsxs("button", {+ type: "button",+ onClick: function () { setExpanded(function (v) { return !v; }); },+ style: { display: "flex", alignItems: "center", gap: 8, width: "100%", textAlign: "left", background: "transparent", border: "none", cursor: "pointer", padding: "8px 12px", color: COLORS.title, fontSize: 13 },+ children: [+ jsx("span", { style: { transform: expanded ? "rotate(90deg)" : "rotate(0deg)", transition: "transform .12s", display: "inline-block", color: COLORS.label }, children: "▸" }),+ jsx("span", { style: { fontWeight: 500 }, children: node.name || "undo" }),+ jsx("span", { style: { color: COLORS.label, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1, minWidth: 0 }, children: summary })+ ]+ }),+ expanded && body !== null ? jsx("div", {+ style: { borderTop: "1px solid " + COLORS.border, paddingTop: 8, paddingBottom: 8, maxHeight: 340, overflow: "auto" },+ children: rows+ }) : null+ ]+ });+ }++ function apply(ctx) {+ ctx.slots.inject("conversation.chat.commandview", function () {+ return ctx.slots.register({+ name: "conversation.chat.commandview",+ key: "undo"+ }, UndoCommandView);+ });+ }++ exports.apply = apply;+ exports.inject = inject;+ return module.exports;+ }+});diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.jsindex 6bbd2178..9c39264c 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js@@ -1,7 +1,7 @@import { spawnSync } from 'node:child_process'import { createHash, randomUUID } from 'node:crypto'-import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'-import { dirname, join, relative, resolve, sep } from 'node:path'+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { basename, dirname, join, relative, resolve, sep } from 'node:path'import process from 'node:process'import { TextDecoder, TextEncoder } from 'node:util'@@ -105,6 +105,99 @@ export function createSnapshotStore(rootDir, workspaceDir) {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)+ // Files excluded by EXCLUDE_PATHS: .env, .env.*, *.pem, *.key, id_rsa*, credentials*, *secret*, *token*+ if (/^\.env($|\.)/.test(base))+ return true+ if (/\.(pem|key)$/i.test(base))+ return true+ if (/^id_rsa/.test(base) || /^credentials/.test(base) || /secret/i.test(base) || /token/i.test(base))+ return true+ return false+}++/**+ * 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 }.+ */+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 }+}+/** Capture a complete allowed-path tree, incrementally reusing the parent tree. */export function captureSnapshot(store, refName, message, parentRef) {const { repoDir, workspaceDir } = store@@ -139,6 +232,93 @@ export function snapshotDiff(store, beforeCommit, afterCommit) {return [...new Set(output.split(/\r?\n/).map(value => value.trim()).filter(Boolean))]}+const DEFAULT_MAX_DIFF_LINES = 120++function truncateDiff(text, maxLines = DEFAULT_MAX_DIFF_LINES) {+ const lines = text.replace(/\n$/u, '').split('\n')+ if (lines.length <= maxLines || lines[0] === '')+ return lines[0] === '' ? '' : lines.join('\n')+ return `${lines.slice(0, maxLines).join('\n')}\n… (${lines.length - maxLines} more line(s) truncated)`+}++/** Classify how one path changed between two snapshots: created, deleted, or modified. */+export function classifyPathChange(store, beforeCommit, afterCommit, path) {+ const before = stateAt(store, beforeCommit, path)+ const after = stateAt(store, afterCommit, path)+ if (before.kind === 'absent' && after.kind === 'file')+ return 'created'+ if (before.kind === 'file' && after.kind === 'absent')+ return 'deleted'+ return 'modified'+}++/** Unified diff of one path between two snapshot commits, truncated to maxLines. */+export function snapshotFileDiff(store, fromCommit, toCommit, path, maxLines) {+ const output = runGit(store.repoDir, store.workspaceDir, ['diff', '--no-renames', fromCommit, toCommit, '--', path])+ return truncateDiff(output, maxLines)+}++// The well-known empty blob is not pre-populated in a fresh private repo, so+// write it on first use (its hash is always e69de29bb2d1d6434b8b29ae775ad8c2e48c5391).+function ensureEmptyBlob(store) {+ if (!store.emptyBlob) {+ const result = spawnSync('git', ['--git-dir', store.repoDir, 'hash-object', '-w', '--stdin'], {+ cwd: store.workspaceDir,+ input: '',+ encoding: 'utf8',+ })+ if (result.error || result.status !== 0)+ throw new Error(`TURNREWIND_GIT_HASH: empty blob: ${result.stderr?.trim() || result.error?.message}`)+ store.emptyBlob = result.stdout.trim()+ }+ return store.emptyBlob+}++function blobFor(store, commit, path) {+ if (!commitEntry(store, commit, path))+ return ensureEmptyBlob(store)+ return runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`]).trim()+}++function hashDiskFile(store, workspaceDir, path) {+ const target = assertSafePath(workspaceDir, path)+ if (!existsSync(target))+ return ensureEmptyBlob(store)+ const info = lstatSync(target)+ if (!info.isFile() || info.size > MAX_FILE_BYTES)+ return undefined+ const result = spawnSync('git', ['--git-dir', store.repoDir, 'hash-object', '-w', '--stdin'], {+ cwd: workspaceDir,+ input: readFileSync(target),+ encoding: 'utf8',+ maxBuffer: MAX_FILE_BYTES,+ })+ if (result.error)+ throw new Error(`TURNREWIND_GIT_HASH: ${path}: ${result.error.message}`)+ if (result.status !== 0)+ throw new Error(`TURNREWIND_GIT_HASH: ${path}: ${result.stderr.trim()}`)+ return result.stdout.trim()+}++/**+ * Unified diff between a path's committed state and its current on-disk content.+ * Used to show what a human (or another session) changed after a turn, i.e. the+ * content an undo would overwrite. The disk content is hashed into the private+ * snapshot repo; the user's own repository is never touched.+ */+export function diffAgainstDisk(store, commit, path, maxLines) {+ const from = blobFor(store, commit, path)+ const to = hashDiskFile(store, store.workspaceDir, path)+ if (to === undefined)+ return '(current file is not a regular file or exceeds the size limit)'+ if (from === to)+ return ''+ const output = runGit(store.repoDir, store.workspaceDir, [+ 'diff', '--no-renames', '--src-prefix=snapshot/', '--dst-prefix=disk/', from, to,+ ])+ return truncateDiff(output, maxLines)+}+function commitEntry(store, commit, path) {const output = runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', commit, '--', path])return output.split(/\r?\n/).includes(path)@@ -172,6 +352,9 @@ function digest(bytes) {}export function stateAt(store, commit, path) {+ // Never inspect state through a path that escapes the workspace or passes+ // through a symlink; treat it as unsupported input instead.+ assertSafePath(store.workspaceDir, path)if (!commitEntry(store, commit, path))return { kind: 'absent', digest: null }const bytes = commitBytes(store, commit, path)diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.jsindex 843be977..a8ce0ae5 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js@@ -68,6 +68,12 @@ export function openLedger(rootDir) {catch {// Column already exists.}+ try {+ db.exec('ALTER TABLE rewind_notices ADD COLUMN kind TEXT NOT NULL DEFAULT \'undo\'')+ }+ catch {+ // Column already exists.+ }db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)return db}@@ -161,8 +167,8 @@ export function settleOperation(db, operationId, outcome, error) {export function queueRewindNotice(db, notice) {db.prepare(`- INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at)- VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at, kind)+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)`).run(notice.noticeId,notice.sessionId,@@ -171,6 +177,7 @@ export function queueRewindNotice(db, notice) {JSON.stringify([notice.targetTurnId]),JSON.stringify(notice.paths),notice.createdAt,+ notice.kind ?? 'undo',)}@@ -203,13 +210,52 @@ export function claimRewindNotices(db, sessionId, workspaceKey) {}))}+export function getLatestAppliedUndo(db, sessionId, workspaceKey) {+ return db.prepare(`+ SELECT o.* FROM operations o+ JOIN turns t ON t.turn_id = o.target_turn_id+ WHERE t.session_id = ? AND t.workspace_key = ?+ AND o.kind = 'undo' AND o.outcome = 'applied'+ ORDER BY o.settled_at DESC LIMIT 1+ `).get(sessionId, workspaceKey)+}+export function completeUndoWithNotice(db, turnId, notice) {db.exec('BEGIN')try {db.prepare(`UPDATE turns SET status = 'undone' WHERE turn_id = ?`).run(turnId)db.prepare(`- INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at)- VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at, kind)+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)+ `).run(+ notice.noticeId,+ notice.sessionId,+ notice.workspaceKey,+ notice.targetTurnId,+ JSON.stringify([notice.targetTurnId]),+ JSON.stringify(notice.paths),+ notice.createdAt,+ notice.kind ?? 'undo',+ )+ db.exec('COMMIT')+ }+ catch (error) {+ db.exec('ROLLBACK')+ throw error+ }+}++/** Atomically mark an undo as redone, restore its turn to settled, and queue a redo notice. */+export function completeRedoWithNotice(db, operationId, turnId, notice) {+ db.exec('BEGIN')+ try {+ db.prepare(`UPDATE operations SET outcome = 'redone', settled_at = ? WHERE operation_id = ?`)+ .run(new Date().toISOString(), operationId)+ db.prepare(`UPDATE turns SET status = 'settled', reversible = 1 WHERE turn_id = ? AND status = 'undone'`)+ .run(turnId)+ db.prepare(`+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, status, created_at, kind)+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, 'redo')`).run(notice.noticeId,notice.sessionId,diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.jsindex d34fbaa4..5a9e9c8b 100644--- a/plugins/dsh-tauri-turnrewind/lib/index.js+++ b/plugins/dsh-tauri-turnrewind/lib/index.js@@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto'import { homedir } from 'node:os'import { join, resolve } from 'node:path'import process from 'node:process'-import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'-import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'+import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from './core/git-snapshot.js'+import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'import { classifyUndo } from './core/planner.js'const name = 'dsh-tauri-turnrewind'@@ -21,7 +21,16 @@ function workspaceForAgent(agent) {function workspaceForSession(session) {const cwd = session?.header?.cwd- return typeof cwd === 'string' && cwd.length > 0 ? resolve(cwd) : undefined+ if (typeof cwd !== 'string' || cwd.length === 0)+ return undefined+ const resolved = resolve(cwd)+ // Never snapshot the home directory: the blocking spawnSync git add walks+ // hundreds of GB, freezes the whole event loop for minutes, and fails 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())+ return undefined+ return resolved}function workspaceKeyFor(path) {@@ -36,10 +45,26 @@ function parseUndoInput(rawInput) {const parts = rawInput.trim().split(/\s+/u).filter(Boolean)let turnIdlet dryRun = false+ let preview = false+ let skipConflicts = false+ let force = false+ let redo = falsefor (const part of parts) {if (part === '--dry-run') {dryRun = true}+ else if (part === '--preview') {+ preview = true+ }+ else if (part === '--skip-conflicts') {+ skipConflicts = true+ }+ else if (part === '--force') {+ force = true+ }+ else if (part === '--redo') {+ redo = true+ }else if (part === '--subtree') {return { error: 'Recursive subtree undo is not available in the MVP.' }}@@ -47,10 +72,14 @@ function parseUndoInput(rawInput) {turnId = part}else {- return { error: 'Usage: /undo [turn-id] [--dry-run]' }+ return { error: 'Usage: /undo [turn-id] [--dry-run|--preview] [--skip-conflicts|--force] or /undo --redo' }}}- return { turnId, dryRun }+ if (skipConflicts && force)+ return { error: '--skip-conflicts and --force are mutually exclusive.' }+ if (redo && (turnId !== undefined || dryRun || preview || skipConflicts || force))+ return { error: '--redo cannot be combined with a turn id or other options.' }+ return { turnId, dryRun, preview, skipConflicts, force, redo }}function assertSessionOwner(target, agent) {@@ -60,16 +89,86 @@ function assertSessionOwner(target, agent) {return undefined}-function formatPlan(target, paths, conflicts, dryRun) {- const mode = dryRun ? 'Undo plan' : 'Undo preflight'- const conflictText = conflicts.length === 0 ? '0 conflicts' : `${conflicts.length} conflict(s): ${conflicts.join(', ')}`- return `${mode}: turn ${target.turn_id}; ${paths.length} file(s); ${conflictText}.`+function indent(text, prefix) {+ return text.split('\n').map(line => `${prefix}${line}`).join('\n')+}++/** Diff a committed path against disk; never let an unsafe path crash the plan. */+function safeDiffAgainstDisk(store, ref, path) {+ try {+ return diffAgainstDisk(store, ref, path)+ }+ catch {+ return '(unable to inspect the on-disk file safely)'+ }+}++/** Conflict check that treats uninspectable paths (symlink, escape) as conflicts. */+function diskMatchesSnapshot(runtime, workspaceDir, ref, path) {+ try {+ return classifyUndo(currentState(workspaceDir, path), stateAt(runtime.store, ref, path)) !== 'conflict'+ }+ catch {+ return false+ }+}++/**+ * Build the read-only undo plan: for every touched path, how the turn changed it+ * (modified/created/deleted) and whether the current on-disk state still matches+ * the turn's after snapshot.+ */+function buildPlanEntries(runtime, workspaceDir, target, paths) {+ return paths.map(path => ({+ path,+ change: classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),+ conflict: !diskMatchesSnapshot(runtime, workspaceDir, target.after_ref, path),+ }))+}++function summarizeChanges(entries) {+ const counts = { modified: 0, created: 0, deleted: 0 }+ for (const entry of entries) counts[entry.change] += 1+ return `modified ${counts.modified}, created ${counts.created}, deleted ${counts.deleted}`+}++function formatPlan(runtime, target, entries, options) {+ const conflicts = entries.filter(entry => entry.conflict)+ const lines = []+ 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]' : ''+ lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}`)+ }+ if (options.preview) {+ lines.push('')+ lines.push('Undo will apply (turn output → restored state):')+ for (const entry of entries) {+ const diff = snapshotFileDiff(runtime.store, target.after_ref, target.before_ref, entry.path)+ lines.push(`--- ${entry.path}`)+ lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')+ }+ }+ if (conflicts.length > 0) {+ lines.push('')+ lines.push('Conflicts (turn output → current disk; undo would overwrite these changes):')+ for (const entry of conflicts) {+ const diff = safeDiffAgainstDisk(runtime.store, target.after_ref, entry.path)+ lines.push(`--- ${entry.path}`)+ lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')+ }+ 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.')+ }+ return lines.join('\n')}function createRewindNoticeMessage(notice) {const paths = notice.paths.map(path => `- ${path}`).join('\n')const turns = notice.turns.length > 0 ? notice.turns.join(', ') : notice.target_turn_id- const text = `[Turn rewind notice]\nThe workspace was reverted by these undo operations: ${turns}.\n\nReverted files in this operation:\n${paths}\n\nTreat the current files on disk as authoritative. Do not assume any reverted changes still exist; re-read the listed files before making further edits.`+ const text = notice.kind === 'redo'+ ? `[Turn rewind notice]\nA previous undo was redone; the file changes of these turns were re-applied: ${turns}.\n\nRe-applied files:\n${paths}\n\nTreat the current files on disk as authoritative. Re-read the listed files before making further edits.`+ : `[Turn rewind notice]\nThe workspace was reverted by these undo operations: ${turns}.\n\nReverted files in this operation:\n${paths}\n\nTreat the current files on disk as authoritative. Do not assume any reverted changes still exist; re-read the listed files before making further edits.`return {id: `turnrewind-notice-${notice.notice_id}`,role: 'user',@@ -125,6 +224,65 @@ function settleSessionTurns(ledger, active, sessionId, reason) {}}+/** Redo the most recently applied undo. Restores each touched path to the turn's+ * after-snapshot (its post-image), but only if disk still matches the undone+ * state — otherwise the undo result would silently clobber later human edits. */+async function applyRedo(runtime, invocation, workspaceDir, workspaceKey) {+ const op = getLatestAppliedUndo(runtime.db, invocation.agent.session.id, workspaceKey)+ if (!op) {+ return { kind: 'error', text: 'No previously applied undo is available to redo.' }+ }+ const turn = getTurn(runtime.db, op.target_turn_id)+ if (!turn || !turn.before_ref || !turn.after_ref) {+ return { kind: 'error', text: 'The undone turn no longer has a recoverable snapshot.' }+ }+ const paths = snapshotDiff(runtime.store, turn.before_ref, turn.after_ref)+ if (paths.length === 0)+ return { kind: 'success', text: 'No file changes were recorded for this turn.' }++ const conflicts = []+ for (const path of paths) {+ const expected = stateAt(runtime.store, turn.before_ref, path)+ const actual = currentState(workspaceDir, path)+ if (classifyUndo(actual, expected) === 'conflict')+ conflicts.push(path)+ }+ if (conflicts.length > 0) {+ const lines = []+ lines.push(`Redo is blocked: ${conflicts.length} conflicted file(s) were edited after the undo.`)+ lines.push('')+ lines.push('Conflicts (undone state → current disk; redo would overwrite these changes):')+ for (const path of conflicts) {+ const diff = safeDiffAgainstDisk(runtime.store, turn.before_ref, path)+ lines.push(`--- ${path}`)+ lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')+ }+ return { kind: 'error', text: lines.join('\n') }+ }++ runtime.undoing = true+ try {+ const operationId = randomUUID()+ const beforeRef = `refs/turnrewind/redo-${operationId}`+ captureSnapshot(runtime.store, beforeRef, `turnrewind redo ${turn.turn_id}`, runtime.parentRef)+ for (const path of paths)+ restorePath(runtime.store, turn.after_ref, path)+ completeRedoWithNotice(runtime.db, op.operation_id, turn.turn_id, {+ noticeId: randomUUID(),+ sessionId: invocation.agent.session.id,+ workspaceKey,+ targetTurnId: turn.turn_id,+ paths,+ createdAt: new Date().toISOString(),+ })+ runtime.parentRef = beforeRef+ return { kind: 'success', text: `re-applied ${paths.length} file(s). The next model request will receive a rewind notice.` }+ }+ finally {+ runtime.undoing = false+ }+}+async function applyUndo(runtime, active, invocation) {const parsed = parseUndoInput(invocation.rawInput)if (parsed.error)@@ -140,6 +298,9 @@ async function applyUndo(runtime, active, invocation) {if (runtime.undoing)return { kind: 'error', text: 'Another undo operation is already running in this workspace.' }+ if (parsed.redo)+ return applyRedo(runtime, invocation, workspaceDir, workspaceKey)+const target = parsed.turnId? getTurn(runtime.db, parsed.turnId): getLatestTurn(runtime.db, invocation.agent.session.id, workspaceKey)@@ -165,19 +326,16 @@ async function applyUndo(runtime, active, invocation) {if (paths.length === 0)return { kind: 'success', text: 'No file changes were recorded for this turn.' }- const conflicts = []- for (const path of paths) {- const expected = stateAt(runtime.store, target.after_ref, path)- const actual = currentState(workspaceDir, path)- if (classifyUndo(actual, expected) === 'conflict')- conflicts.push(path)- }- if (parsed.dryRun || conflicts.length > 0) {- return {- kind: conflicts.length > 0 && !parsed.dryRun ? 'error' : 'success',- text: formatPlan(target, paths, conflicts, parsed.dryRun),- }- }+ const entries = buildPlanEntries(runtime, workspaceDir, target, paths)+ const conflicts = entries.filter(entry => entry.conflict)++ // Read-only plan/preview: never touch disk.+ if (parsed.dryRun || parsed.preview)+ return { kind: 'success', text: formatPlan(runtime, target, entries, parsed) }++ // Default policy refuses to overwrite anything it cannot attribute.+ if (conflicts.length > 0 && !parsed.skipConflicts && !parsed.force)+ return { kind: 'error', text: formatPlan(runtime, target, entries, parsed) }const operationId = randomUUID()const beforeRef = `refs/turnrewind/operation-${operationId}`@@ -191,18 +349,25 @@ async function applyUndo(runtime, active, invocation) {})try {- for (const path of paths) restorePath(runtime.store, target.before_ref, path)+ const targets = parsed.skipConflicts ? entries.filter(entry => !entry.conflict) : entries+ for (const entry of targets)+ restorePath(runtime.store, target.before_ref, entry.path)+ const restoredPaths = targets.map(entry => entry.path)+ const skippedPaths = conflicts.map(entry => entry.path)completeUndoWithNotice(runtime.db, target.turn_id, {noticeId: randomUUID(),sessionId: invocation.agent.session.id,workspaceKey,targetTurnId: target.turn_id,- paths,+ paths: restoredPaths,createdAt: new Date().toISOString(),})settleOperation(runtime.db, operationId, 'applied')runtime.parentRef = beforeRef- return { kind: 'success', text: `Undid turn ${target.turn_id} and restored ${paths.length} file(s). The next model request will receive a rewind notice.` }+ let text = `Undid turn ${target.turn_id} and restored ${restoredPaths.length} file(s). The next model request will receive a rewind notice.`+ if (skippedPaths.length > 0)+ text += ` Skipped ${skippedPaths.length} conflicted file(s): ${skippedPaths.join(', ')}.`+ return { kind: 'success', text }}catch (error) {try {@@ -223,10 +388,28 @@ async function applyUndo(runtime, active, invocation) {}}-function apply(ctx) {+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).+ const guard = Object.assign({+ maxFileCount: 10000,+ maxTotalBytes: 512 * 1024 * 1024,+ maxFileBytes: 50 * 1024 * 1024,+ maxDepth: 20,+ maxDirs: 10000,+ }, config.guard)const ledger = openLedger(ROOT_DIR)const active = new Map()const workspaceStores = new Map()+ // 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.commandsfunction ensureRuntime(agent) {@@ -234,8 +417,16 @@ function apply(ctx) {if (!workspaceDir)return undefinedconst workspaceKey = workspaceKeyFor(workspaceDir)+ if (rejectedWorkspaces.has(workspaceKey))+ return undefinedlet 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(ROOT_DIR, workspaceDir)const latest = getLatestSnapshotRef(ledger, workspaceKey)registerWorkspace(ledger, workspaceKey, workspaceDir, store.repoDir)@@ -343,4 +534,4 @@ function apply(ctx) {}), 'turnrewind command')}-export { apply, inject, name }+export { apply, applyUndo, inject, name }diff --git a/plugins/dsh-tauri-turnrewind/package.json b/plugins/dsh-tauri-turnrewind/package.jsonindex 37df4034..7d541964 100644--- a/plugins/dsh-tauri-turnrewind/package.json+++ b/plugins/dsh-tauri-turnrewind/package.json@@ -5,10 +5,23 @@"description": "Local turn-aware workspace undo for DeepSeek Harness","main": "lib/index.js","files": ["README.md", "cordis.patch.yml", "lib"],+ "exports": {+ ".": "./lib/index.js",+ "./client": "./lib/client.js",+ "./cordis.patch.yml": "./cordis.patch.yml",+ "./package.json": "./package.json"+ },"dsh": {"runtime": "host","bundle": {"patch": "./cordis.patch.yml"+ },+ "client": {+ "inject": [+ "@deepseek-ai/dsh-client-runtime",+ "@deepseek-ai/dsh-client-ui-conversation"+ ],+ "platform": "web"}},"engines": {diff --git a/plugins/dsh-tauri-turnrewind/pnpm-lock.yaml b/plugins/dsh-tauri-turnrewind/pnpm-lock.yamlnew file mode 100644index 00000000..50729709--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/pnpm-lock.yaml@@ -0,0 +1,699 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ devDependencies:+ vitest:+ specifier: ^4.1.11+ version: 4.1.11([email protected])++packages:++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}++ '@oxc-project/[email protected]':+ resolution: {integrity: sha512-IJ3s6ltHLp45S0bh7phkX+gJO7A1Wuz2EaqpAhb8WjqDwbzMiWKHhyyT42tskaWjEYXtHtVCPpnBJVT9+dcRLg==}++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [android]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-lkWU8ZJaRk9q3CIEY1Tc7vIFALp3Xw5NfGJo2hQg5oIqNgxWi1zI+IiDEK3r70BF5Dzol1tcXsnzsRc8NLhG+Q==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [android]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-dgR56NYnvAszm7Ob1B2/Vn0e8bUQYZH2UjVaMMtMVOCKFSfjhfLmuA/9+O+F+ajUdG6B/bSssrKW6JJYASa8jA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [darwin]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-vpVxFvUCFioJqug7OTvqptkc4yb8UX0AwfDmJpaR/0sWz+BUmqSVAf7c8JkUgnN8YLspb4a/N6NhTyMAmdyQ7Q==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [darwin]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-h1wG6Y6K3JlRswxsI64qQJqBAy4vrLuHgRbc8CZMGSWTOFRY6ghMApM1NKzB2I0n5xV1fjkE18SuVl2QpLeNpA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [freebsd]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-tbCiqub0q2MVWJKgF5PoAlNWCtQydiOYSLIkd8sByqK/6MMYLJRcSXSYodqYtd0O+Fw7QaVmKKlS4oL94YRZ0w==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm]+ os: [linux]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-oxK9+baEBPhZG5HB4URY+uU04zJWeZlH6Tb9rB5DK4DF9XR1uXNLXt5Q5ZsugTKayNCNLhkcwz/ye74hRI98dg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [openharmony]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-y5NTmmasMS455JlOCO4ZM9krIchv3Mvm1crL1iUPGOPgEzSkves9n0SdC5Sjz6+qWDFhd8/JpfWMH8NSWNHe+A==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [arm64]+ os: [win32]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-np8iZSLfXlAD4kWhiyq/u0Yt8oZDtRQ8lGhQaCXo2rl37KNjeU0GjJuwr4P3oeZ++ROfofsKNBqR5LTO8aXyWQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ cpu: [x64]+ os: [win32]++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true++ '@vitest/[email protected]':+ resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}++ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}++ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}++ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [android]++ resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [darwin]++ resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [darwin]++ resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [freebsd]++ resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm]+ os: [linux]++ resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [win32]++ resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}++ resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==}+ engines: {node: '>=12.20.0'}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-vMM4q3aixf46GiF1Kok8jDPFsEpXgFWGjUHXNkNHNm+Y2adXAG2dbX91jkti3i0ZRsOlcmbuzAz1poObSHCmUA==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true++ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}++ resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}++ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}++ resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ '@vitejs/devtools': ^0.4.0 || ^0.5.0+ esbuild: ^0.27.0 || ^0.28.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ '@vitejs/devtools':+ optional: true+ esbuild:+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==}+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@opentelemetry/api': ^1.9.0+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0+ '@vitest/browser-playwright': 4.1.11+ '@vitest/browser-preview': 4.1.11+ '@vitest/browser-webdriverio': 4.1.11+ '@vitest/coverage-istanbul': 4.1.11+ '@vitest/coverage-v8': 4.1.11+ '@vitest/ui': 4.1.11+ happy-dom: '*'+ jsdom: '*'+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@opentelemetry/api':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser-playwright':+ optional: true+ '@vitest/browser-preview':+ optional: true+ '@vitest/browser-webdriverio':+ optional: true+ '@vitest/coverage-istanbul':+ optional: true+ '@vitest/coverage-v8':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true++ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}+ engines: {node: '>=8'}+ hasBin: true++snapshots:++ '@jridgewell/[email protected]': {}++ '@oxc-project/[email protected]': {}++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]':+ optional: true++ '@rolldown/[email protected]': {}++ '@standard-schema/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/deep-eql': 4.0.2+ assertion-error: 2.0.1++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@vitest/[email protected]':+ dependencies:+ '@standard-schema/spec': 1.1.0+ '@types/chai': 5.2.3+ '@vitest/spy': 4.1.11+ '@vitest/utils': 4.1.11+ chai: 6.2.2+ tinyrainbow: 3.1.1++ '@vitest/[email protected]([email protected])':+ dependencies:+ '@vitest/spy': 4.1.11+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+ vite: 8.2.2++ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 3.1.1++ '@vitest/[email protected]':+ dependencies:+ '@vitest/utils': 4.1.11+ pathe: 2.0.3++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 4.1.11+ '@vitest/utils': 4.1.11+ magic-string: 0.30.21+ pathe: 2.0.3++ '@vitest/[email protected]': {}++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 4.1.11+ convert-source-map: 2.0.0+ tinyrainbow: 3.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9++ [email protected]: {}++ optionalDependencies:+ picomatch: 4.0.7++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ dependencies:+ detect-libc: 2.1.2+ optionalDependencies:+ lightningcss-android-arm64: 1.33.0+ lightningcss-darwin-arm64: 1.33.0+ lightningcss-darwin-x64: 1.33.0+ lightningcss-freebsd-x64: 1.33.0+ lightningcss-linux-arm-gnueabihf: 1.33.0+ lightningcss-linux-arm64-gnu: 1.33.0+ lightningcss-linux-arm64-musl: 1.33.0+ lightningcss-linux-x64-gnu: 1.33.0+ lightningcss-linux-x64-musl: 1.33.0+ lightningcss-win32-arm64-msvc: 1.33.0+ lightningcss-win32-x64-msvc: 1.33.0++ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ nanoid: 3.3.18+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ '@oxc-project/types': 0.147.0+ '@rolldown/pluginutils': 1.0.1+ optionalDependencies:+ '@rolldown/binding-android-arm-eabi': 1.2.6+ '@rolldown/binding-android-arm64': 1.2.6+ '@rolldown/binding-darwin-arm64': 1.2.6+ '@rolldown/binding-darwin-x64': 1.2.6+ '@rolldown/binding-freebsd-x64': 1.2.6+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.6+ '@rolldown/binding-linux-arm64-gnu': 1.2.6+ '@rolldown/binding-linux-arm64-musl': 1.2.6+ '@rolldown/binding-linux-ppc64-gnu': 1.2.6+ '@rolldown/binding-linux-s390x-gnu': 1.2.6+ '@rolldown/binding-linux-x64-gnu': 1.2.6+ '@rolldown/binding-linux-x64-musl': 1.2.6+ '@rolldown/binding-openharmony-arm64': 1.2.6+ '@rolldown/binding-win32-arm64-msvc': 1.2.6+ '@rolldown/binding-win32-x64-msvc': 1.2.6++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7++ [email protected]: {}++ dependencies:+ lightningcss: 1.33.0+ picomatch: 4.0.7+ postcss: 8.5.26+ rolldown: 1.2.6+ tinyglobby: 0.2.17+ optionalDependencies:+ fsevents: 2.3.3++ dependencies:+ '@vitest/expect': 4.1.11+ '@vitest/mocker': 4.1.11([email protected])+ '@vitest/pretty-format': 4.1.11+ '@vitest/runner': 4.1.11+ '@vitest/snapshot': 4.1.11+ '@vitest/spy': 4.1.11+ '@vitest/utils': 4.1.11+ es-module-lexer: 2.3.2+ expect-type: 1.4.0+ magic-string: 0.30.21+ obug: 2.1.4+ pathe: 2.0.3+ picomatch: 4.0.7+ std-env: 4.2.0+ tinybench: 2.9.0+ tinyexec: 1.3.0+ tinyglobby: 0.2.17+ tinyrainbow: 3.1.1+ vite: 8.2.2+ why-is-node-running: 2.3.0+ transitivePeerDependencies:+ - msw++ dependencies:+ siginfo: 2.0.0+ stackback: 0.0.2diff --git a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.jsindex d81f225c..60d46994 100644--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js+++ b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js@@ -3,7 +3,7 @@ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { it } from 'vitest'-import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from '../lib/core/git-snapshot.js'+import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from '../lib/core/git-snapshot.js'import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../lib/core/ledger.js'it('captures and restores modified, added, and deleted files', async () => {@@ -129,6 +129,66 @@ it('does not treat CRLF conversion as a file conflict', async () => {}})+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 writeFile(join(workspace, 'modified.txt'), 'one\ntwo\n')+ await writeFile(join(workspace, 'deleted.txt'), 'gone\n')++ const store = createSnapshotStore(join(root, 'data'), workspace)+ const before = captureSnapshot(store, 'refs/turnrewind/diff-before', 'before')+ await writeFile(join(workspace, 'modified.txt'), 'one\nTWO\n')+ await rm(join(workspace, 'deleted.txt'))+ await writeFile(join(workspace, 'created.txt'), 'fresh\n')+ const after = captureSnapshot(store, 'refs/turnrewind/diff-after', 'after', before.commit)++ assert.equal(classifyPathChange(store, before.commit, after.commit, 'modified.txt'), 'modified')+ assert.equal(classifyPathChange(store, before.commit, after.commit, 'created.txt'), 'created')+ assert.equal(classifyPathChange(store, before.commit, after.commit, 'deleted.txt'), 'deleted')++ // The undo diff is the reverse of the turn's change.+ const undoDiff = snapshotFileDiff(store, after.commit, before.commit, 'modified.txt')+ assert.match(undoDiff, /-TWO/u)+ assert.match(undoDiff, /\+two/u)++ // Disk still matches the snapshot: no human changes to report.+ assert.equal(diffAgainstDisk(store, after.commit, 'modified.txt'), '')+ // A human edit after the turn shows up as what an undo would overwrite.+ await writeFile(join(workspace, 'modified.txt'), 'one\nHUMAN\n')+ const conflictDiff = diffAgainstDisk(store, after.commit, 'modified.txt')+ assert.match(conflictDiff, /-TWO/u)+ assert.match(conflictDiff, /\+HUMAN/u)+ // A file deleted after the turn diffs against the empty blob.+ await rm(join(workspace, 'modified.txt'))+ assert.match(diffAgainstDisk(store, after.commit, 'modified.txt'), /-one/u)+ }+ finally {+ await rm(root, { recursive: true, force: true })+ }+})++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 writeFile(join(workspace, 'big.txt'), 'old\n')+ const store = createSnapshotStore(join(root, 'data'), workspace)+ const before = captureSnapshot(store, 'refs/turnrewind/truncate-before', 'before')+ const lines = Array.from({ length: 500 }, (_, index) => `line-${index}`).join('\n')+ await writeFile(join(workspace, 'big.txt'), `${lines}\n`)+ const after = captureSnapshot(store, 'refs/turnrewind/truncate-after', 'after', before.commit)+ const diff = snapshotFileDiff(store, before.commit, after.commit, 'big.txt', 50)+ assert.ok(diff.split('\n').length <= 52)+ assert.match(diff, /truncated/u)+ }+ finally {+ await rm(root, { recursive: true, force: true })+ }+})+it('rejects paths outside the workspace', async () => {const root = await mkdtemp(join(tmpdir(), 'turnrewind-path-test-'))const workspace = join(root, 'workspace')@@ -140,3 +200,46 @@ it('rejects paths outside the workspace', async () => {await rm(root, { recursive: true, force: true })}})++it('probes a small workspace as trackable and refuses oversized / deep ones', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-probe-'))+ const workspace = join(root, 'ws')+ 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')+ }+ finally {+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/plugins/dsh-tauri-turnrewind/test/ledger.test.js b/plugins/dsh-tauri-turnrewind/test/ledger.test.jsindex 8eda46ce..e4e7bf76 100644--- a/plugins/dsh-tauri-turnrewind/test/ledger.test.js+++ b/plugins/dsh-tauri-turnrewind/test/ledger.test.js@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { it } from 'vitest'-import { claimRewindNotices, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleInterruptedTurn, settleNoopTurn, settleTurn } from '../lib/core/ledger.js'+import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../lib/core/ledger.js'it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))@@ -216,6 +216,66 @@ it('selects an interrupted turn after a later turn is undone', async () => {}})+it('redoes an applied undo and queues a redo notice atomically', async () => {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-redo-test-'))+ const db = openLedger(root)+ try {+ insertTurn(db, {+ turnId: 'session:1',+ sessionId: 'session',+ workspaceKey: 'workspace',+ startedAt: '2026-01-01T00:00:00.000Z',+ beforeRef: 'refs/turnrewind/turn-1-before',+ })+ settleTurn(db, 'session:1', 'refs/turnrewind/turn-1-after')+ createOperation(db, {+ operationId: 'op-undo',+ kind: 'undo',+ targetTurnId: 'session:1',+ requestedAt: '2026-01-01T00:01:00.000Z',+ beforeRef: 'refs/turnrewind/operation-op-undo',+ })+ settleOperation(db, 'op-undo', 'applied')+ completeUndoWithNotice(db, 'session:1', {+ noticeId: 'notice-undo',+ sessionId: 'session',+ workspaceKey: 'workspace',+ targetTurnId: 'session:1',+ paths: ['a.ts'],+ createdAt: '2026-01-01T00:01:01.000Z',+ })+ assert.equal(getTurn(db, 'session:1').status, 'undone')+ assert.equal(getLatestAppliedUndo(db, 'session', 'workspace').operation_id, 'op-undo')++ // The undo notice is delivered first.+ const undoNotices = claimRewindNotices(db, 'session', 'workspace')+ assert.equal(undoNotices.length, 1)+ assert.equal(undoNotices[0].kind, 'undo')++ completeRedoWithNotice(db, 'op-undo', 'session:1', {+ noticeId: 'notice-redo',+ sessionId: 'session',+ workspaceKey: 'workspace',+ targetTurnId: 'session:1',+ paths: ['a.ts'],+ createdAt: '2026-01-01T00:02:00.000Z',+ })+ assert.equal(getTurn(db, 'session:1').status, 'settled')+ assert.equal(getTurn(db, 'session:1').reversible, 1)+ // A redone operation is no longer a redo candidate.+ assert.equal(getLatestAppliedUndo(db, 'session', 'workspace'), undefined)++ const redoNotices = claimRewindNotices(db, 'session', 'workspace')+ assert.equal(redoNotices.length, 1)+ assert.equal(redoNotices[0].kind, 'redo')+ assert.deepEqual(redoNotices[0].paths, ['a.ts'])+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})+it('marks an interrupted active turn abandoned on reopen', async () => {const root = await mkdtemp(join(tmpdir(), 'turnrewind-recovery-test-'))const first = openLedger(root)diff --git a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.jsnew file mode 100644index 00000000..213100b8--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js@@ -0,0 +1,160 @@+import assert from 'node:assert/strict'+import { mkdir, 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 { applyUndo } from '../lib/index.js'+import { captureSnapshot, createSnapshotStore } from '../lib/core/git-snapshot.js'+import { getTurn, insertTurn, openLedger, settleTurn } from '../lib/core/ledger.js'++async function setupTurn() {+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-lifecycle-test-'))+ const workspace = join(root, 'workspace')+ await mkdir(workspace, { recursive: true })+ await writeFile(join(workspace, 'a.txt'), 'v1\n')+ const db = openLedger(join(root, 'ledger'))+ const store = createSnapshotStore(join(root, 'data'), workspace)+ const before = captureSnapshot(store, 'refs/turnrewind/t1-before', 'before')+ await writeFile(join(workspace, 'a.txt'), 'v2\n')+ await writeFile(join(workspace, 'c.txt'), 'new\n')+ const after = captureSnapshot(store, 'refs/turnrewind/t1-after', 'after', before.commit)+ insertTurn(db, {+ turnId: 'session:1',+ sessionId: 'session',+ workspaceKey: resolve(workspace).toLowerCase(),+ startedAt: '2026-01-01T00:00:00.000Z',+ beforeRef: 'refs/turnrewind/t1-before',+ })+ settleTurn(db, 'session:1', 'refs/turnrewind/t1-after')+ const runtime = {+ db,+ store,+ workspaceKey: resolve(workspace).toLowerCase(),+ parentRef: 'refs/turnrewind/t1-after',+ undoing: false,+ }+ const invocation = (rawInput = '') => ({+ rawInput,+ agent: { session: { id: 'session', header: { cwd: workspace } } },+ })+ return { root, workspace, db, runtime, active: new Map(), invocation }+}++it('plans, previews, and applies conflict policies', async () => {+ const { root, workspace, db, runtime, active, invocation } = await setupTurn()+ try {+ // Dry run classifies every path without writing.+ const dryRun = await applyUndo(runtime, active, invocation('--dry-run'))+ assert.equal(dryRun.kind, 'success')+ assert.match(dryRun.text, /modified 1, created 1, deleted 0/u)+ assert.match(dryRun.text, /modified\s+a\.txt/u)+ assert.match(dryRun.text, /created\s+c\.txt/u)+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')++ // Preview shows the diff the undo would apply.+ const preview = await applyUndo(runtime, active, invocation('--preview'))+ assert.equal(preview.kind, 'success')+ assert.match(preview.text, /Undo will apply/u)+ assert.match(preview.text, /-v2/u)+ assert.match(preview.text, /\+v1/u)++ // A human edit after the turn blocks the undo and shows what would be overwritten.+ await writeFile(join(workspace, 'a.txt'), 'HUMAN\n')+ const blocked = await applyUndo(runtime, active, invocation())+ assert.equal(blocked.kind, 'error')+ assert.match(blocked.text, /1 conflict/u)+ assert.match(blocked.text, /\+HUMAN/u)+ assert.match(blocked.text, /--skip-conflicts/u)+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'HUMAN\n')++ // --skip-conflicts restores only the clean file and reports the skip.+ const skipped = await applyUndo(runtime, active, invocation('--skip-conflicts'))+ assert.equal(skipped.kind, 'success')+ assert.match(skipped.text, /Skipped 1 conflicted file\(s\): a\.txt/u)+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'HUMAN\n')+ await assert.rejects(stat(join(workspace, 'c.txt')))+ assert.equal(getTurn(db, 'session:1').status, 'undone')+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})++it('forces a restore over a conflicted file', async () => {+ const { root, workspace, db, runtime, active, invocation } = await setupTurn()+ try {+ await writeFile(join(workspace, 'a.txt'), 'HUMAN\n')+ const forced = await applyUndo(runtime, active, invocation('--force'))+ assert.equal(forced.kind, 'success')+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')+ await assert.rejects(stat(join(workspace, 'c.txt')))+ assert.equal(getTurn(db, 'session:1').status, 'undone')+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})++it('round-trips undo and redo', async () => {+ const { root, workspace, db, runtime, active, invocation } = await setupTurn()+ try {+ const undo = await applyUndo(runtime, active, invocation())+ assert.equal(undo.kind, 'success')+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')+ await assert.rejects(stat(join(workspace, 'c.txt')))++ const redo = await applyUndo(runtime, active, invocation('--redo'))+ assert.equal(redo.kind, 'success')+ assert.match(redo.text, /re-applied 2 file\(s\)/u)+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')+ assert.equal(await readFile(join(workspace, 'c.txt'), 'utf8'), 'new\n')+ assert.equal(getTurn(db, 'session:1').status, 'settled')++ // The turn is reversible again after the redo.+ const undoAgain = await applyUndo(runtime, active, invocation())+ assert.equal(undoAgain.kind, 'success')+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')++ // A second redo targets the new undo operation.+ const redoAgain = await applyUndo(runtime, active, invocation('--redo'))+ assert.equal(redoAgain.kind, 'success')+ assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})++it('blocks redo when the disk changed after the undo', async () => {+ const { root, workspace, db, runtime, active, invocation } = await setupTurn()+ try {+ const undo = await applyUndo(runtime, active, invocation())+ assert.equal(undo.kind, 'success')+ await writeFile(join(workspace, 'a.txt'), 'edited-after-undo\n')+ const redo = await applyUndo(runtime, active, invocation('--redo'))+ assert.equal(redo.kind, 'error')+ assert.match(redo.text, /Redo is blocked/u)+ assert.match(redo.text, /\+edited-after-undo/u)+ assert.equal(getTurn(db, 'session:1').status, 'undone')+ }+ 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 {+ assert.match((await applyUndo(runtime, active, invocation('--force --skip-conflicts'))).text, /mutually exclusive/u)+ assert.match((await applyUndo(runtime, active, invocation('--redo session:1'))).text, /--redo cannot be combined/u)+ assert.match((await applyUndo(runtime, active, invocation('--subtree session:1'))).text, /not available/u)+ }+ finally {+ db.close()+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/plugins/dsh-tauri-turnrewind/vitest.config.js b/plugins/dsh-tauri-turnrewind/vitest.config.jsnew file mode 100644index 00000000..f615125f--- /dev/null+++ b/plugins/dsh-tauri-turnrewind/vitest.config.js@@ -0,0 +1,10 @@+import { defineConfig } from 'vitest/config'++// The plugin is not a member of the repo's pnpm workspace; keep its test config+// local so vitest does not climb up and load the desktop shell's vite.config.ts.+export default defineConfig({+ test: {+ include: ['test/**/*.test.js'],+ testTimeout: 30000,+ },+})