Skip to content

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

Merge remote-tracking branch 'origin/feature/turn-rewind' into feature/turn-rewind

miaooo0000OOOO64a4e858ce1b
diff --cc plugins/dsh-tauri-turnrewind/README.md
index ddc73b7f,0d36e7b1..270481a7
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@@ -9,17 -9,19 +9,22 @@@
这是 Host MVP 原型,当前实现:
- 为已领取的 Agent turn 建立私有 Git 快照;
- - 将快照映射记录到 `$DSH_HOME/turnrewind/ledger.sqlite`;
+ - 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
+ - **git 全程异步执行**:快照、diff、恢复都不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行,不同会话并行;
+ - **git 可用性探测**:系统没有 git 时,turn 显式记为 `skipped`(原因 `TURNREWIND_GIT_UNAVAILABLE`),而不是静默失败;
+ - **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;被清空前留下来的旧 turn 会在 `/undo` 选目标时自动识别为死快照并标记跳过(`snapshot ref missing`),不会甩出 git 原始报错;
+ - **工作区资格守卫**:家目录、家目录的祖先、盘根目录,以及超过快照预算(文件数 / 总大小 / 单文件大小)的目录不做快照,turn 记为 `skipped` 并向 `/undo` 说明原因(见「工作区资格与快照预算」);
+ - **不可用弹窗**:客户端半(`lib/client.js`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、每个浏览器只弹一次);
- 注册人类命令 `/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 或提交历史。
## 使用方法
@@@ -62,8 -60,37 +67,37 @@@
/undo --subtree
```
-父对话递归撤销、redo、消息旁 Undo 按钮和设置页模式切换尚未实现。
+父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。
+ ## 工作区资格与快照预算
+
+ 快照的第一版实现会对任意工作区做全量基线,曾有用户在 QQ 机器人会话(默认工作目录是家目录、约 250 GB 内容)上触发 `git add --all` 级别的灾难。现在 turn 开始前会先做资格检查,不合格的工作区**不建快照、不产生可撤销 turn**,并在账本中记为 `skipped`(`/undo` 会显示原因)。两层检查:
+
+ 1. **系统目录直接拒绝**:家目录本身、家目录的祖先目录(如 `C:\Users`、`C:\`)、以及任何盘符根目录。这类目录无论多小都不做快照。
+ 2. **预算预扫描**(带元数据的快速遍历,超限立即中止):
+ - 文件数上限:默认 50,000(环境变量 `TURNREWIND_MAX_FILES`);
+ - 总大小上限:默认 1 GiB(环境变量 `TURNREWIND_MAX_BYTES`);
+ - 单文件上限:64 MB(与恢复读取上限一致,超限文件永远无法恢复,因此整个工作区拒绝快照);
+ - `.git`、`node_modules`、`dist`、`build`、`coverage`、`.turnrewind` 目录不计入预算。
+
+ 被拒绝的 turn 仍正常执行,只是不提供 undo。同时该会话会收到一条一次性提示(`[Turn rewind unavailable]`),说明工作区被拒绝的原因;每个会话只提示一次,后续 turn 不再重复打扰。提示会以两种形态呈现:
+
+ 1. **会话内消息**:插件来源的上下文注入消息,模型和用户都可见、可审计;
+ 2. **Web UI 弹窗**:宿主端 `turnrewind` 会话投影(`lib/core/dialog-projection.js`)把提示折叠进会话列表快照,客户端半(`lib/client.js`)从 `sessions.list` 的 `projectionValues.turnrewind` 读到后弹出模态对话框,按提示 id 在 `localStorage` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。
+
+ 若确有合法的大工作区需要 undo,可通过环境变量放宽预算,自行承担快照耗时与磁盘占用。
+
+ ### 清理已膨胀的快照数据
+
+ 如果某个工作区在旧版本下已经生成过巨大快照,先停止 DSH Host 进程,再执行:
+
+ ```powershell
+ node plugins\dsh-tauri-turnrewind\lib\purge-workspace.js "C:\Users\<user>" # release 数据目录 ~/.dsh
+ node plugins\dsh-tauri-turnrewind\lib\purge-workspace.js "C:\Users\<user>" --home "$env:USERPROFILE\.dsh.dev" # debug
+ ```
+
+ 该命令删除该工作区对应的私有快照仓库(`$DSH_HOME/snapshots/<hash>.git`)及其全部账本记录(turns / operations / notices / workspaces),其他工作区的数据不受影响。
+
## Undo 的工作区范围
Undo 的范围是:
diff --cc plugins/dsh-tauri-turnrewind/lib/client.js
index 129ddfc8,58898675..263c04d1
--- a/plugins/dsh-tauri-turnrewind/lib/client.js
+++ b/plugins/dsh-tauri-turnrewind/lib/client.js
@@@ -1,163 -1,185 +1,348 @@@
+// 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;
+ }
+});
+ // Client half of dsh-tauri-turnrewind: raises an in-app dialog when the
+ // current session carries an unsupported-workspace heads-up from the host.
+ // Hand-wrapped in the dsh client ModuleLoader format (no build step): the web
+ // app evaluates this file and registers the module under the plugin name.
+ if (globalThis.__ModuleLoader__) {
+ globalThis.__ModuleLoader__.load({ id: 'dsh-tauri-turnrewind', factory: () => {
+ const module = { exports: {} }
+ const exports = module.exports
+
+ const inject = ['sessions', 'locale']
+
+ const NS = 'dsh-tauri-turnrewind'
+ const SEEN_KEY = 'turnrewind.seenUnsupportedNotices'
+ const MAX_SEEN = 100
+
+ const dictionaries = {
+ zh: {
+ title: '撤销功能在此工作区不可用',
+ intro: '当前会话的工作区不支持文件撤销。对话照常运行,但本工作区内的文件改动无法用 /undo 撤销。',
+ reason: '原因',
+ ok: '知道了',
+ },
+ en: {
+ title: 'Undo is unavailable in this workspace',
+ intro: 'File undo is disabled for this session\'s workspace. Turns still run normally, but changes in this workspace cannot be reverted with /undo.',
+ reason: 'Reason',
+ ok: 'Got it',
+ },
+ }
+
+ function readSeen() {
+ try {
+ const raw = globalThis.localStorage.getItem(SEEN_KEY)
+ const list = raw ? JSON.parse(raw) : []
+ return Array.isArray(list) ? list : []
+ }
+ catch {
+ return []
+ }
+ }
+
+ function markSeen(id) {
+ try {
+ const seen = readSeen().filter(entry => entry !== id)
+ seen.push(id)
+ globalThis.localStorage.setItem(SEEN_KEY, JSON.stringify(seen.slice(-MAX_SEEN)))
+ }
+ catch {
+ // Storage may be unavailable; the dialog just re-shows next reload.
+ }
+ }
+
+ let dialog
+
+ function palette() {
+ const dark = globalThis.matchMedia?.('(prefers-color-scheme: dark)')?.matches ?? false
+ return dark
+ ? { card: '#1f2937', text: '#f9fafb', muted: '#9ca3af', box: '#111827', boxBorder: '#374151', backdrop: 'rgba(2, 6, 23, 0.6)', button: '#6366f1', buttonText: '#ffffff' }
+ : { card: '#ffffff', text: '#111827', muted: '#6b7280', box: '#f3f4f6', boxBorder: '#e5e7eb', backdrop: 'rgba(15, 23, 42, 0.45)', button: '#4f46e5', buttonText: '#ffffff' }
+ }
+
+ function ensureDialog() {
+ if (dialog)
+ return dialog
+ const colors = palette()
+ const backdrop = document.createElement('div')
+ backdrop.setAttribute('role', 'presentation')
+ Object.assign(backdrop.style, {
+ display: 'none',
+ position: 'fixed',
+ inset: '0',
+ zIndex: '2147483000',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: colors.backdrop,
+ })
+
+ const card = document.createElement('div')
+ card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
+ Object.assign(card.style, {
+ maxWidth: '440px',
+ width: 'calc(100vw - 48px)',
+ boxSizing: 'border-box',
+ background: colors.card,
+ color: colors.text,
+ borderRadius: '12px',
+ padding: '20px 22px',
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ lineHeight: '1.6',
+ boxShadow: '0 20px 50px rgba(0, 0, 0, 0.3)',
+ })
+
+ const title = document.createElement('div')
+ Object.assign(title.style, { fontSize: '15px', fontWeight: '600', marginBottom: '10px' })
+
+ const intro = document.createElement('div')
+
+ const reasonLabel = document.createElement('div')
+ Object.assign(reasonLabel.style, { marginTop: '12px', color: colors.muted, fontSize: '12px' })
+
+ const reasonBox = document.createElement('div')
+ Object.assign(reasonBox.style, {
+ marginTop: '6px',
+ padding: '8px 10px',
+ borderRadius: '8px',
+ background: colors.box,
+ border: `1px solid ${colors.boxBorder}`,
+ wordBreak: 'break-all',
+ whiteSpace: 'pre-wrap',
+ maxHeight: '160px',
+ overflowY: 'auto',
+ })
+
+ const actions = document.createElement('div')
+ Object.assign(actions.style, { marginTop: '16px', textAlign: 'right' })
+ const button = document.createElement('button')
+ button.type = 'button'
+ Object.assign(button.style, {
+ background: colors.button,
+ color: colors.buttonText,
+ border: 'none',
+ borderRadius: '8px',
+ padding: '6px 18px',
+ fontSize: '13px',
+ cursor: 'pointer',
+ })
+ actions.appendChild(button)
+
+ card.append(title, intro, reasonLabel, reasonBox, actions)
+ backdrop.appendChild(card)
+ document.body.appendChild(backdrop)
+
+ function hide() {
+ backdrop.style.display = 'none'
+ }
+ button.addEventListener('click', hide)
+ backdrop.addEventListener('click', (event) => {
+ if (event.target === backdrop)
+ hide()
+ })
+
+ dialog = { backdrop, title, intro, reasonLabel, reasonBox, button }
+ return dialog
+ }
+
+ function showDialog(t, notices) {
+ const el = ensureDialog()
+ el.title.textContent = t('title')
+ el.intro.textContent = t('intro')
+ el.reasonLabel.textContent = t('reason')
+ el.reasonBox.textContent = notices.map(notice => notice.reason || notice.id).join('\n')
+ el.button.textContent = t('ok')
+ el.backdrop.style.display = 'flex'
+ }
+
+ function apply(ctx) {
+ ctx.effect(() => ctx.locale.register(NS, dictionaries), 'turnrewind locale')
+ const t = ctx.locale.bind(NS)
+ // Read through the service store, not the ctx.sessions property proxy:
+ // the host session service merges a different member under the same name.
+ const sessions = ctx.get('sessions')
+ ctx.effect(() => {
+ const unsubscribe = sessions.list.subscribe(() => {
+ const state = sessions.list.getSnapshot()
+ const summary = state.current !== undefined ? state.byId[state.current] : undefined
+ const value = summary?.projectionValues?.turnrewind
+ const notices = Array.isArray(value?.notices) ? value.notices : []
+ const fresh = notices.filter(notice => notice && typeof notice.id === 'string' && !readSeen().includes(notice.id))
+ if (fresh.length === 0)
+ return
+ for (const notice of fresh) markSeen(notice.id)
+ showDialog(t, fresh)
+ })
+ return () => {
+ unsubscribe()
+ }
+ }, 'turnrewind dialog runner')
+ }
+
+ Object.assign(exports, { apply, inject })
+ return module.exports
+ } })
+ }
diff --cc plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
index 9c39264c,4fbefd41..2b4acac1
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
@@@ -1,7 -1,8 +1,8 @@@
- import { spawnSync } from 'node:child_process'
+ import { Buffer } from 'node:buffer'
+ import { spawn } 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'
@@@ -104,104 -175,20 +175,114 @@@ export function createSnapshotStore(roo
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*
++ // Files excluded by EXCLUDE_PATHS: .env, .env.*, *.pem, *.key, id_rsa*,
++ // credentials.*, secrets.*
+ 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))
++ if (/^id_rsa/.test(base) || /^credentials\./.test(base) || /^secrets\./.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) {
+ /**
+ * Capture a complete allowed-path tree, incrementally reusing the parent tree.
+ * A missing parent (wiped snapshot directory, moved DSH_HOME) degrades to a
+ * fresh baseline instead of failing every future turn.
+ */
+ export async function captureSnapshot(store, refName, message, parentRef) {
const { repoDir, workspaceDir } = store
- ensureRepository(repoDir, workspaceDir)
+ await ensureRepository(repoDir, workspaceDir)
+ let parent
+ if (parentRef) {
+ parent = await gitRef(repoDir, workspaceDir, parentRef)
+ if (!parent)
+ console.warn(`turnrewind: snapshot parent ${parentRef} is gone; building a fresh baseline for ${workspaceDir}`)
+ }
const indexPath = join(repoDir, `turnrewind-index-${randomUUID()}`)
try {
const env = { GIT_INDEX_FILE: indexPath }
@@@ -227,116 -214,21 +308,119 @@@
}
}
- export function snapshotDiff(store, beforeCommit, afterCommit) {
- const output = runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '--no-renames', beforeCommit, afterCommit])
- return [...new Set(output.split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
+ export async function snapshotDiff(store, beforeCommit, afterCommit) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '--no-renames', beforeCommit, afterCommit])
+ return [...new Set(output.toString('utf8').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)`
+}
+
++/** Run one git command with data piped to stdin (e.g. hash-object -w --stdin). */
++function runGitStdin(repoDir, workspaceDir, args, input) {
++ return new Promise((resolvePromise, rejectPromise) => {
++ const child = spawn('git', ['-c', 'core.quotepath=false', '--git-dir', repoDir, '--work-tree', workspaceDir, ...args], {
++ cwd: workspaceDir,
++ env: { ...process.env },
++ })
++ const chunks = []
++ const errors = []
++ child.stdout.on('data', chunk => chunks.push(chunk))
++ child.stderr.on('data', chunk => errors.push(chunk))
++ child.on('error', error => rejectPromise(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
++ child.on('close', (code) => {
++ if (code !== 0) {
++ rejectPromise(new Error(`TURNREWIND_GIT_FAILED: ${Buffer.concat(errors).toString('utf8').trim() || `exit ${code}`}`))
++ return
++ }
++ resolvePromise(Buffer.concat(chunks))
++ })
++ // Ignore EPIPE if git exits before consuming all input.
++ child.stdin.on('error', () => {})
++ child.stdin.end(input)
++ })
++}
++
+/** 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)
++export async function classifyPathChange(store, beforeCommit, afterCommit, path) {
++ const before = await stateAt(store, beforeCommit, path)
++ const after = await 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)
++export async function snapshotFileDiff(store, fromCommit, toCommit, path, maxLines) {
++ const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--no-renames', fromCommit, toCommit, '--', path])
++ return truncateDiff(output.toString('utf8'), 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) {
++async 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()
++ const output = await runGitStdin(store.repoDir, store.workspaceDir, ['hash-object', '-w', '--stdin'], '')
++ store.emptyBlob = output.toString('utf8').trim()
+ }
+ return store.emptyBlob
+}
+
- function blobFor(store, commit, path) {
- if (!commitEntry(store, commit, path))
++async function blobFor(store, commit, path) {
++ if (!await commitEntry(store, commit, path))
+ return ensureEmptyBlob(store)
- return runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`]).trim()
++ const output = await runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`])
++ return output.toString('utf8').trim()
+}
+
- function hashDiskFile(store, workspaceDir, path) {
++async 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()
++ const output = await runGitStdin(store.repoDir, store.workspaceDir, ['hash-object', '-w', '--stdin'], readFileSync(target))
++ return output.toString('utf8').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)
++export async function diffAgainstDisk(store, commit, path, maxLines) {
++ const from = await blobFor(store, commit, path)
++ const to = await 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, [
++ const output = await runGit(store.repoDir, store.workspaceDir, [
+ 'diff', '--no-renames', '--src-prefix=snapshot/', '--dst-prefix=disk/', from, to,
+ ])
- return truncateDiff(output, maxLines)
++ return truncateDiff(output.toString('utf8'), 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)
+ async function commitEntry(store, commit, path) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', commit, '--', path])
+ return output.toString('utf8').split(/\r?\n/).includes(path)
}
- function commitBytes(store, commit, path) {
- const result = spawnSync('git', ['--git-dir', store.repoDir, 'show', `${commit}:${path}`], {
- cwd: store.workspaceDir,
- encoding: null,
- maxBuffer: MAX_FILE_BYTES,
- })
- if (result.error)
- throw new Error(`TURNREWIND_GIT_READ: ${path}: ${result.error.message}`)
- if (result.status !== 0)
- throw new Error(`TURNREWIND_GIT_READ: ${path}`)
- if (result.stdout.length > MAX_FILE_BYTES)
+ async function commitBytes(store, commit, path) {
+ const output = await runGit(store.repoDir, store.workspaceDir, ['show', `${commit}:${path}`], {}, MAX_FILE_BYTES + 1)
+ if (output.length > MAX_FILE_BYTES)
throw new Error(`TURNREWIND_FILE_TOO_LARGE: ${path}`)
- return result.stdout
+ return output
}
function digest(bytes) {
@@@ -351,13 -243,10 +435,12 @@@
return createHash('sha256').update(comparable).digest('hex')
}
- 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))
+ export async function stateAt(store, commit, path) {
++ // stateAt only inspects the private snapshot repo (commit:path revisions),
++ // never the filesystem, so a symlinked or odd path simply reads as absent.
+ if (!await commitEntry(store, commit, path))
return { kind: 'absent', digest: null }
- const bytes = commitBytes(store, commit, path)
+ const bytes = await commitBytes(store, commit, path)
return { kind: 'file', digest: digest(bytes) }
}
diff --cc plugins/dsh-tauri-turnrewind/lib/index.js
index 5a9e9c8b,1ba56a98..84a905fa
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@@ -2,8 -2,10 +2,10 @@@ import { randomUUID } from 'node:crypto
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import process from 'node:process'
- 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 { createDialogProjection } from './core/dialog-projection.js'
-import { captureSnapshot, createSnapshotStore, currentState, gitAvailable, gitRef, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'
++import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from './core/git-snapshot.js'
+ import { assessWorkspace } from './core/guard.js'
-import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurnSummary, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
++import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
@@@ -89,78 -67,10 +96,78 @@@ function assertSessionOwner(target, age
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) {
++async function safeDiffAgainstDisk(store, ref, path) {
+ try {
- return diffAgainstDisk(store, ref, path)
++ return await 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) {
++async function diskMatchesSnapshot(runtime, workspaceDir, ref, path) {
+ try {
- return classifyUndo(currentState(workspaceDir, path), stateAt(runtime.store, ref, path)) !== 'conflict'
++ return classifyUndo(currentState(workspaceDir, path), await 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 => ({
++async function buildPlanEntries(runtime, workspaceDir, target, paths) {
++ return Promise.all(paths.map(async path => ({
+ path,
- change: classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),
- conflict: !diskMatchesSnapshot(runtime, workspaceDir, target.after_ref, path),
- }))
++ change: await classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),
++ conflict: !await 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) {
++async 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)
++ 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 (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)
++ const diff = await 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) {
@@@ -224,65 -154,15 +253,77 @@@ async function settleSessionTurns(ledge
}
}
+/** 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 (!await turnRefsExist(runtime.store, turn)) {
++ return { kind: 'error', text: 'The snapshot data for the undone turn no longer exists (the snapshot repository was previously wiped).' }
++ }
++ const paths = await 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 expected = await 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)
++ const diff = await 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)
++ await captureSnapshot(runtime.store, beforeRef, `turnrewind redo ${turn.turn_id}`, runtime.parentRef)
+ for (const path of paths)
- restorePath(runtime.store, turn.after_ref, path)
++ await 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 turnRefsExist(store, turn) {
+ if (!turn.before_ref || !turn.after_ref)
+ return false
+ return Boolean(
+ await gitRef(store.repoDir, store.workspaceDir, turn.before_ref)
+ && await gitRef(store.repoDir, store.workspaceDir, turn.after_ref),
+ )
+ }
+
async function applyUndo(runtime, active, invocation) {
const parsed = parseUndoInput(invocation.rawInput)
if (parsed.error)
@@@ -298,12 -178,27 +339,30 @@@
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)
+ let target
+ if (parsed.turnId) {
+ target = getTurn(runtime.db, parsed.turnId)
+ if (target && !await turnRefsExist(runtime.store, target)) {
+ return {
+ kind: 'error',
+ text: `The snapshot data for turn ${parsed.turnId} no longer exists (the snapshot repository was previously wiped); its changes can no longer be undone.`,
+ }
+ }
+ }
+ else {
+ // Walk newest-first and skip turns whose snapshot refs died with a wiped
+ // snapshot repository, marking them so later /undo runs never re-check.
+ for (const candidate of listReversibleTurns(runtime.db, invocation.agent.session.id, workspaceKey)) {
+ if (await turnRefsExist(runtime.store, candidate)) {
+ target = candidate
+ break
+ }
+ markTurnSnapshotMissing(runtime.db, candidate.turn_id)
+ }
+ }
if (!target) {
const latest = getLatestTurnSummary(runtime.db, invocation.agent.session.id)
const detail = latest
@@@ -326,16 -221,19 +385,16 @@@
if (paths.length === 0)
return { kind: 'success', text: 'No file changes were recorded for this turn.' }
- const entries = buildPlanEntries(runtime, workspaceDir, target, paths)
- const conflicts = []
- for (const path of paths) {
- const expected = await 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 = await 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) }
++ return { kind: 'success', text: await 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) }
++ return { kind: 'error', text: await formatPlan(runtime, target, entries, parsed) }
const operationId = randomUUID()
const beforeRef = `refs/turnrewind/operation-${operationId}`
@@@ -349,11 -247,7 +408,11 @@@
})
try {
- for (const path of paths) await 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)
++ await 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,
@@@ -406,11 -283,22 +465,26 @@@ function apply(ctx, config = {})
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.commands
+ // Client-visible projection: lets the web UI raise the unavailable-dialog
+ // from the session list it already receives, no conversation API needed.
+ ctx.effect(() => ctx.sessionProjections.register(createDialogProjection()), 'turnrewind projection')
+
+ // Per-session FIFO chain: baseline capture, settle and undo bookkeeping for
+ // one session never interleave. Git now runs asynchronously, so ordering is
+ // enforced here instead of by the event loop blocking.
+ const sessionChains = new Map()
+
+ function enqueueTurnTask(sessionId, task) {
+ const previous = sessionChains.get(sessionId) ?? Promise.resolve()
+ const next = previous.then(task)
+ sessionChains.set(sessionId, next.catch(() => {}))
+ return next
+ }
function ensureRuntime(agent) {
const workspaceDir = workspaceForAgent(agent)
diff --cc plugins/dsh-tauri-turnrewind/package.json
index 7d541964,a5468955..43edbece
--- a/plugins/dsh-tauri-turnrewind/package.json
+++ b/plugins/dsh-tauri-turnrewind/package.json
@@@ -1,10 -1,8 +1,10 @@@
{
"name": "dsh-tauri-turnrewind",
"type": "module",
- "version": "0.1.0-dev.1",
+ "version": "0.1.0-dev.4",
"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",
@@@ -17,11 -16,11 +17,12 @@@
"patch": "./cordis.patch.yml"
},
"client": {
+ "platform": "web",
"inject": [
"@deepseek-ai/dsh-client-runtime",
- "@deepseek-ai/dsh-client-ui-conversation"
- ],
- "platform": "web"
++ "@deepseek-ai/dsh-client-ui-conversation",
+ "@deepseek-ai/dsh-client-locale"
+ ]
}
},
"engines": {
diff --cc plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
index 60d46994,36d752ed..709b470f
--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
@@@ -3,7 -3,7 +3,7 @@@ import { mkdir, mkdtemp, readFile, rm,
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
- import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from '../lib/core/git-snapshot.js'
-import { captureSnapshot, createSnapshotStore, currentState, gitAvailable, restorePath, snapshotDiff, stateAt } from '../lib/core/git-snapshot.js'
++import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from '../lib/core/git-snapshot.js'
import { completeUndoWithNotice, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../lib/core/ledger.js'
it('captures and restores modified, added, and deleted files', async () => {
@@@ -129,66 -129,6 +129,66 @@@ it('does not treat CRLF conversion as
}
})
+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')
++ const before = await 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)
++ const after = await 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')
++ assert.equal(await classifyPathChange(store, before.commit, after.commit, 'modified.txt'), 'modified')
++ assert.equal(await classifyPathChange(store, before.commit, after.commit, 'created.txt'), 'created')
++ assert.equal(await 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')
++ const undoDiff = await 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'), '')
++ assert.equal(await 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')
++ const conflictDiff = await 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)
++ assert.match(await 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 before = await 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)
++ const after = await captureSnapshot(store, 'refs/turnrewind/truncate-after', 'after', before.commit)
++ const diff = await 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')
@@@ -201,45 -141,37 +201,80 @@@
}
})
+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 })
+ }
+})
++
+ it('rebuilds a fresh baseline when the parent snapshot is gone', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-orphan-test-'))
+ const workspace = join(root, 'workspace')
+ try {
+ await mkdir(workspace, { recursive: true })
+ await writeFile(join(workspace, 'a.txt'), 'one')
+ const store = createSnapshotStore(join(root, 'data'), workspace)
+ const first = await captureSnapshot(store, 'refs/turnrewind/orphan-first', 'first')
+
+ // Simulate the snapshot repository being wiped out from under the ledger:
+ // without the fallback, every later capture would fail on read-tree.
+ // The parent is passed by ref name, exactly like the ledger stores it.
+ await rm(store.repoDir, { recursive: true, force: true })
+ await writeFile(join(workspace, 'a.txt'), 'two')
+ const rebuilt = await captureSnapshot(store, 'refs/turnrewind/orphan-second', 'second', 'refs/turnrewind/orphan-first')
+ assert.notEqual(rebuilt.commit, first.commit)
+ assert.equal((await stateAt(store, rebuilt.commit, 'a.txt')).kind, 'file')
+
+ // The next turn keeps building on the recovered chain.
+ await writeFile(join(workspace, 'b.txt'), 'new')
+ const third = await captureSnapshot(store, 'refs/turnrewind/orphan-third', 'third', rebuilt.commit)
+ assert.deepEqual(await snapshotDiff(store, rebuilt.commit, third.commit), ['b.txt'])
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('probes git availability once per process', async () => {
+ const first = await gitAvailable()
+ const second = await gitAvailable()
+ assert.equal(first, second)
+ assert.equal(typeof first, 'boolean')
+ })
diff --cc plugins/dsh-tauri-turnrewind/test/ledger.test.js
index e4e7bf76,02e4c0e2..8bac0d13
--- a/plugins/dsh-tauri-turnrewind/test/ledger.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
@@@ -3,7 -3,7 +3,7 @@@ import { mkdtemp, rm } from 'node:fs/pr
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
- import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../lib/core/ledger.js'
-import { claimRewindNotices, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, queueRewindNotice, recordSkippedTurn, settleInterruptedTurn, settleNoopTurn, settleTurn } from '../lib/core/ledger.js'
++import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, queueRewindNotice, recordSkippedTurn, 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,66 -243,45 +243,105 @@@ it('selects an interrupted turn after
}
})
+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('lists reversible turns newest-first and marks dead snapshots skipped', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-deadref-test-'))
+ const db = openLedger(root)
+ try {
+ for (const [turnId, time] of [
+ ['session:1', '2026-01-01T00:00:00.000Z'],
+ ['session:2', '2026-01-01T00:01:00.000Z'],
+ ['session:3', '2026-01-01T00:02:00.000Z'],
+ ]) {
+ insertTurn(db, {
+ turnId,
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ startedAt: time,
+ beforeRef: `refs/turnrewind/turn-${turnId}-before`,
+ })
+ settleTurn(db, turnId, `refs/turnrewind/turn-${turnId}-after`)
+ }
+ completeUndoWithNotice(db, 'session:3', {
+ noticeId: 'notice-3',
+ sessionId: 'session',
+ workspaceKey: 'workspace',
+ targetTurnId: 'session:3',
+ paths: ['a.txt'],
+ createdAt: '2026-01-01T00:03:00.000Z',
+ })
+ const candidates = listReversibleTurns(db, 'session', 'workspace')
+ assert.deepEqual(candidates.map(turn => turn.turn_id), ['session:2', 'session:1'])
+ markTurnSnapshotMissing(db, 'session:2')
+ assert.equal(getTurn(db, 'session:2').reversible, 0)
+ assert.match(getTurn(db, 'session:2').error, /snapshot repository was wiped/)
+ assert.deepEqual(listReversibleTurns(db, 'session', 'workspace').map(turn => turn.turn_id), ['session:1'])
+ }
+ 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 --cc plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
index 213100b8,00000000..4733b2ba
mode 100644,000000..100644
--- a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
@@@ -1,160 -1,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')
++ const before = await 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)
++ const after = await 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 })
+ }
+})