Skip to content

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

feat(turnrewind): full client UI, keep settled plans traceable, drop legacy JS

yingtianland263dae2c6b3
diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md
index 2aae4122..afd80bee 100644
--- a/docs/PROJECT_STATUS.md
+++ b/docs/PROJECT_STATUS.md
@@ -1,75 +1,62 @@
# 项目进展与交接备忘
-> 更新于 2026-08-31。用途:换设备/换会话时快速接续 turn-rewind 插件开发。
-> 详细设计见 `docs/TURN_REWIND.md`,用户文档见 `plugins/dsh-tauri-turnrewind/README.md`。
+> 更新于 2026-09-03。用途:换设备/换会话时快速接续 turn-rewind 插件开发。
+> 详细设计见 `docs/TURN_REWIND.md`,用户文档见 `packages/dsh-tauri-turnrewind-ts/README.md`。
## 一句话状态
-turn-rewind 插件 **v0.1.0 已发布**(独立仓库,CI 绿);完整 undo 闭环(预览红绿 diff → 卡内 ✓/✗ 确认 → 执行 → 结果卡内展示)已在真机验证通过。
+turn-rewind 已完成 **TypeScript 重写**(`packages/dsh-tauri-turnrewind-ts`,v0.2.0-beta.1),并切换为 **Git 目录模式**:工作区必须是 Git worktree,非 Git 目录禁用(`TURNREWIND_GIT_REQUIRED`);17 个测试文件、82 个测试全绿;完整 undo 闭环(预览红绿 diff → 卡内 ✓/✗ 确认 → 执行 → 结果永久可查)已在真机验证通过。旧 JS 版(`plugins/dsh-tauri-turnrewind`)已删除。
## 仓库拓扑
| 仓库 | 位置/远程 | 用途 | 当前位置 |
| --- | --- | --- | --- |
-| 桌面开发仓库 | 本机 `Desktop/dsh` ↔ `origin`(dsh-tauri-desk 官方) + `undo`(我的 fork) | 插件开发 + 真机验证 | `feature/turn-rewind` @ `63ad6a8`;工作树有未提交的 P0-1 barrier 修复 |
-| 桌面仓库 fork | github.com/yingtianlan/deepseek-harness-desktop-undo | fork(备份/PR) | feature/turn-rewind @ `63ad6a8`;当前开发仓库已同步该远程引用 |
-| 插件发布仓库 | 本机 `Desktop/dsh-tauri-turnrewind` ↔ github.com/yingtianlan/dsh-tauri-turnrewind | 独立发布(v0.1.0 tag,CI 绿) | main @ `6bc62ae` |
-| 官方插件参考源码 | 本机 `Desktop/dsh/source/dsh-tauri-plugins` | 只读参考(webServer 路由/client 模式都抄的它) | 本地 clone |
+| 桌面开发仓库(TS 分支) | 本机 `Desktop/dsh-git-rewind-ts` ↔ `origin`(我的 fork) | 插件开发 + 真机验证 | `dsh/turnrewind-ts` @ `dace50b`+ |
+| 桌面仓库 fork | github.com/yingtianlan/deepseek-harness-desktop-undo | 备份/PR | `dsh/turnrewind-ts` 已推送远程 |
+| 官方插件参考源码 | 本机 `Desktop/dsh/source/dsh-tauri-plugins` | 只读参考(packages 插件规范) | 本地 clone |
+| 旧 JS 实验分支 | 同 fork `dsh/turnrewind-git-dir-undo` | 历史存档(JS 版 Git 模式原型) | 不再演进 |
-## 本轮已完成(全部真机验证)
+## 当前形态(Git 目录模式 + TS)
-- **两阶段 `/undo`**:预览卡(红绿 diff + `+x -y` 徽标 + 文件清单)→ 卡内 ✓/✗ 按钮 →
- ✓ 走同源 HTTP 路由 `/api/turnrewind/confirm` 执行(**不要用 sessions.prompt RPC,实测不通**)→
- 结果写回 plan 行,卡片轮询 `/api/turnrewind/status` 就地显示绿字结果
-- pending plan 持久化:5 分钟过期、新预览替换旧计划、状态(pending/applied/cancelled)+
- 结果文本落账本;**卡片状态一律以账本为准**(刷新/时序都不丢)
-- 取消/过期 → 卡片塌缩为无边框细行 `▸ undo · 已取消`(按钮不复活,路由二次校验兜底)
-- 工作区守卫三层:家目录/祖先/盘根硬拒 + 预算探测(限额与守卫同源,`TURNREWIND_MAX_FILES`/
- `TURNREWIND_MAX_BYTES`)+ claim 时记录;`skipped` turn + 一次性提示(会话内消息 + 主题化弹窗)
-- git 全异步(不冻结 Host)、baseline barrier、git 探测、快照链自愈、死引用跳过、排除规则收窄(去掉 `*token*` 误伤)
-- P0-1 已完成本地修复:连续 turn、重复 claimed、先到 turn/end、dispose/HMR waiter/队列清理均有保护;详见 `TURN_REWIND_PRODUCTION_AUDIT.md`
-- 独立发布仓库剥离:`scripts/sync.mjs` 同步流、CI(Node 22/24 矩阵)、lockfile 钉版本
+- **TS 重写**:包位于 `packages/dsh-tauri-turnrewind-ts`,遵循 `packages/*` 插件规范(tsdown 构建、exports 指向 `dist/`、workspace catalog 依赖);host half(`src/host/`)/ client half(`src/client/`)/ shared 常量三层目录。
+- **Git-only**:会话 cwd 必须位于 Git worktree(子目录归并到根);非 Git 目录 turn 记 `skipped`(`TURNREWIND_GIT_REQUIRED`),`/undo` 明确提示。系统目录(家目录/祖先/盘根)硬拒。
+- **快照模型(OpenCode 式)**:每个 worktree 一个私有 snapshot repo(`$DSH_HOME/snapshots/<hash>.git`),经 alternates 借用源对象(gc/prune 自愈);ignore 语义委托源仓库(`.gitignore`/`.git/info/exclude`/global excludes/`.gitattributes`);自定义敏感文件名单已全部移除。
+- **原子恢复**:bak-swap(target→bak→temp→target→删 bak),崩溃窗口由启动清扫复活;绝不触碰用户 HEAD/branch/index/stash(git-state.test 钉死)。
+- **客户端**:React 组件(command-view)渲染两阶段 undo 卡片 + 不可用弹窗;plan 提交按钮点击即禁用+「执行中…」,结果永久保留在账本(settled 行不清理,可追溯)。
-## ⚠️ 未推送提醒
+## 本轮已完成
-桌面仓库 `feature/turn-rewind` 当前与本地远程引用 `undo/feature/turn-rewind` 同为 `63ad6a8`;
-但 baseline barrier 及后续回归修复目前仍在工作树,尚未提交或推送。完成审查并确认稳定后,再提交并推送。
+- TS 重写全量落地:host(apply/ledger/git-snapshot/git-workspace/guard/planner/undo/routes/dialog-projection/maintenance)+ client(command-view/dialog/register/utils/locales)
+- 17 个测试文件、82 个测试全绿:git-state 零污染、atomic-restore、git-gc 自愈、git-worktree 隔离、git-ignore 委托、oversize 单文件报告、barrier 时序、ledger 生命周期、client 纯函数
+- JS 版目录删除,文档同步为 Git-only + TS 描述
+- plan 结果行永久保留(可追溯);提交按钮 spinner + 防重复点击
+- keyed slot 修复(`conversation.chat.commandview` 需要 `key`);`dsh.client.inject` 补 `dsh-tauri` 依赖
## 换设备环境搭建
-1. clone 桌面仓库 + 检出 `feature/turn-rewind`;
+1. clone fork + 检出 `dsh/turnrewind-ts`;
2. `pnpm install`;
-3. 插件 link 安装(命令见插件 README「从源码开发」节);
-4. 测试:`pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=120000 --maxWorkers=1`(当前 9 个文件、49 个测试全绿);
-5. dev 数据目录 `~/.dsh.dev`(自动),Host 崩溃时看 `~/.dsh.dev` 旁 `dsh-web.dev.log`。
+3. `pnpm --filter dsh-tauri-turnrewind build`(产出 `dist/`,Host 导入必需);
+4. 测试:`pnpm --filter dsh-tauri-turnrewind test`;
+5. debug 桌面端启动时自动以 `link:` 安装全部内部插件(含本插件);dev 数据目录 `~/.dsh.dev`,日志在 `%APPDATA%\io.github.hairyf.deepseek-harness-desktop\logs\dsh-web.dev.log`。
## 下一步待办(优先级序)
-1. **干净安装冒烟**:`dsh plugin add github:yingtianlan/dsh-tauri-turnrewind`——非 link 安装下
- client manifest 是否被正确发现,是唯一未实测的发布路径;
-2. 新发布仓库补 `pnpm-lock.yaml`(当时网络断没生成):`pnpm install` 后提交,并把 CI 的
- `--no-frozen-lockfile` 改回 `--frozen-lockfile`、恢复 `cache: pnpm`(ci.yml 有 TODO 注释);
-3. P1 风险清单(详见会话讨论,未落文档的部分):快照容量 GC、`core.longpaths` 未设
- (Windows 深路径恢复会炸)、崩溃中断 undo 无启动对账、`$DSH_HOME` 在 OneDrive 下的
- SQLite/git 锁风险;
-4. 二期遗留:消息旁 `+x -y` 徽标(`conversation.chat.node` 是按键替换渲染,有维护风险,缓行)、
- 设置页回退模式切换、子树 undo;
-5. 向上游 `dsh-tauri-desk` 提两个 PR:`dsh-src-` 预发布 tag 识别修复(已在本分支)+
- turnrewind 插件本体(可等独立仓库稳定后)。
+1. 真实 DSH lifecycle 集成测试(agent-loop claim → baseline → tool write 时序);
+2. redo 执行段接入 operation 记录与失败回滚(当前冻结,见 README「已知缺陷:redo」);
+3. 快照容量治理(turn 数/容量/保留期 GC);
+4. 消息旁 Undo 按钮、子树 undo;
+5. 干净安装冒烟(非 link 安装下 client manifest 发现)。
## 踩坑备忘(血泪浓缩)
- **client 模块 id 必须归一化为包名**:模块系统剥 `/client` 后缀;启动清单只 import 包名。
- 注册第二个顶层模块 = apply 永远不执行(无报错、无日志,极难排查)。
+- **keyed slot 必须带 `key`**:`conversation.chat.commandview` 注册时漏 `key` 会直接 fail apply(报 `requires options.key`)。
+- **`dsh.client.inject` 必须列出 `dsh-tauri`**:client bundle 里 `require('dsh-tauri/client')` 依赖 ModuleLoader 注入该模块,漏了报 `missed the module table`;同时 `dsh.client.external` 也要声明 `dsh-tauri/client`。
+- **client bundle 是浏览器脚本**:`dist/client.cjs` 第一行就引用 `window`;Node 单测要通过 vitest alias 指到 TS 源码(见 `vitest.config.ts`)。
+- **包名 ≠ 目录名**:包名 `dsh-tauri-turnrewind`,目录 `packages/dsh-tauri-turnrewind-ts`;`pnpm --filter` 按包名。
+- **Host 导入零容忍**:改导出/接口后必跑 `node --input-type=module -e "await import('.../dist/index.js')"` 冒烟;改后必 `pnpm --filter dsh-tauri-turnrewind build`。
+- **pnpm store 版本冲突**:debug profile 的 `node_modules` 若由不同大版本 pnpm 安装,重装会报 `ERR_PNPM_UNEXPECTED_STORE`——删 profile 的 `node_modules` 重来即可。
- **`git rev-parse --verify <裸sha>` 不检查对象存在性**:快照链校验必须用 ref 名比较。
-- **新仓库被上级 pnpm workspace 吞掉**(装到 `C:\Users\<user>` 去了):加自己的
- `pnpm-workspace.yaml`(键序照抄桌面仓库,有 yaml 排序 lint)。
-- **CI `setup-node` 的 `cache: pnpm` 在无 lockfile 仓库会直接 fail**;无 lockfile 期用
- `--no-frozen-lockfile`。
-- **dsh Host 对插件 import 失败零容忍**:整个进程退出。改导出/接口后必跑
- `node --input-type=module -e "await import('./lib/index.js')"` 冒烟。
-- **eslint 大整理后先 `--fix` 再手工**;jsonc/yaml 的键序规则会用 `--fix` 对齐。
-- **push 网络抽风**:`git -c http.proxy= -c https.proxy= push ...` 直连重试;本机 7890 代理
- 时好时坏;连不上就等,别硬推。
-- 桌面仓库的 vitest 跑不在 root 下的测试文件会被项目 include 过滤掉——验证独立仓库用
- `--root` 或桌面工具链二进制直接指路径。
+- **dsh Host 对插件 import 失败零容忍**:整个进程退出。
+- **push 网络抽风**:`git -c http.proxy= -c https.proxy= push ...` 直连重试。
diff --git a/docs/TURN_REWIND.md b/docs/TURN_REWIND.md
index ffe7ca6e..9d870bf2 100644
--- a/docs/TURN_REWIND.md
+++ b/docs/TURN_REWIND.md
@@ -482,20 +482,31 @@ SQLite 账本负责:
## 11. 组件与接口
```text
-plugins/dsh-tauri-turnrewind/
-├─ package.json
+packages/dsh-tauri-turnrewind-ts/
+├─ package.json # 包名 dsh-tauri-turnrewind;exports 指向 dist/
├─ cordis.patch.yml
-├─ lib/
-│ ├─ index.js # 当前 Host composition 原型
-│ └─ core/
-│ ├─ git-snapshot.js # 私有 Git 快照与受限恢复
-│ ├─ ledger.js # SQLite turn/operation 账本
-│ └─ planner.js # 计划与冲突分类纯函数
-├─ test/
-│ ├─ planner.test.js # 已有:子树顺序、路径聚合、冲突分类
-│ ├─ git-snapshot.test.js # 已有:Git 快照、增删改恢复、路径逃逸
-│ ├─ ledger.test.js # 已有:账本持久化与 active 恢复
-│ └─ lifecycle.test.js # 待补:真实 DSH 事件与命令集成
+├─ tsdown.config.ts # tsdown 构建(host ESM + client CJS bundle)
+├─ src/
+│ ├─ index.ts # public barrel(Host 导出面)
+│ ├─ shared/constants.ts # 跨 half 协议常量(插件名 / API 前缀 / storage 基名)
+│ ├─ host/
+│ │ ├─ apply.ts # Host composition(turn 生命周期 / 路由 / 命令 / 投影)
+│ │ ├─ routes/ # 同源 HTTP 路由(POST-only、loopback、body 上限)
+│ │ └─ service/
+│ │ ├─ git-snapshot.ts # 私有 Git 快照与受限恢复(bak-swap 原子替换)
+│ │ ├─ git-workspace.ts # Git worktree 元数据解析(Git-only 资格)
+│ │ ├─ guard.ts # 系统目录拒绝(家目录/祖先/盘根)
+│ │ ├─ ledger.ts # SQLite turn/operation/plan 账本
+│ │ ├─ planner.ts # 计划与冲突分类纯函数
+│ │ ├─ undo.ts # undo/redo 执行核心
+│ │ ├─ maintenance.ts # purge 工作区数据
+│ │ └─ dialog-projection.ts
+│ └─ client/
+│ ├─ index.ts # client bundle 入口(apply / inject)
+│ ├─ components/ # undo 命令卡片(React)
+│ ├─ register/ # slot 注册 + 不可用弹窗
+│ ├─ utils/ locales/ constants/ types/
+├─ test/ # 17 个测试文件 / 82 个测试
└─ README.md
```
diff --git a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
index 21a3f3a3..ba8a58b9 100644
--- a/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
+++ b/docs/TURN_REWIND_GIT_DIR_PROGRESS.md
@@ -150,25 +150,18 @@ Failed: 0
## 5. 验证命令
-在本分支根目录执行:
+在本分支根目录执行(TS 包,Git 目录模式已是 `dsh/turnrewind-ts` 的当前形态):
```powershell
pnpm install
-pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=120000 --maxWorkers=1
-pnpm exec eslint plugins/dsh-tauri-turnrewind
-node --input-type=module -e "await import('./plugins/dsh-tauri-turnrewind/lib/index.js')"
+pnpm --filter dsh-tauri-turnrewind build
+pnpm --filter dsh-tauri-turnrewind test
+pnpm --filter dsh-tauri-turnrewind typecheck
+node --input-type=module -e "await import('./packages/dsh-tauri-turnrewind-ts/dist/index.js')"
```
-完整回归达到全绿前,不能把本分支描述为生产就绪。
+当前 17 个测试文件、82 个测试全绿。
## 6. 分支说明
-本实验位于独立桌面项目目录,使用独立 Git worktree 分支:
-
-```text
-branch: dsh/turnrewind-git-dir-undo
-base: 6808c65
-status: WIP
-```
-
-本分支用于把 Git 目录模式实验和主 `feature/turn-rewind` 隔离,后续可以单独评审、继续修复或整体丢弃。
+Git 目录模式已完成 TS 重写并合入 `dsh/turnrewind-ts`(旧 JS 版目录 `plugins/dsh-tauri-turnrewind` 已删除)。历史实验分支 `dsh/turnrewind-git-dir-undo` 保留为存档。
diff --git a/docs/TURN_REWIND_PRODUCTION_AUDIT.md b/docs/TURN_REWIND_PRODUCTION_AUDIT.md
index 417c4f89..6c418237 100644
--- a/docs/TURN_REWIND_PRODUCTION_AUDIT.md
+++ b/docs/TURN_REWIND_PRODUCTION_AUDIT.md
@@ -1,12 +1,12 @@
# dsh-tauri-turnrewind 生产环境审查报告
-> 审查对象:`dsh-tauri-turnrewind` 当前 `feature/turn-rewind` 分支代码
+> 审查对象:`dsh-tauri-turnrewind` 主功能分支 `feature/turn-rewind` 的 **JS 版历史代码**(`plugins/dsh-tauri-turnrewind`,已删除)
>
> 审查基线:远端个人 fork 最新提交 `82e84bbe99802c5e3df9b9292ca9e8cbca18f500`
>
> 审查性质:生产安全与稳定性审查及修复后复审;报告区分已修复、部分缓解和仍未解决的问题。
>
-> **范围说明**:本报告针对主功能分支。实验分支 `dsh/turnrewind-git-dir-undo`(Git 目录快照模式)删除了预算预扫描与自定义敏感文件名单、把 ignore 语义委托给源仓库、并新增 alternates 失效自愈——本报告中涉及 `guard.js` 预算扫描与排除规则的部分**不适用于该实验分支**;其余安全边界(路径检查、冲突二次校验、barrier/FIFO、needs-recovery、pending plan 原子 claim)在该分支同样保留并有测试钉住。实验分支的专项状态见 `TURN_REWIND_GIT_DIR_PROGRESS.md`。
+> **范围说明(2026-09-03 更新)**:本报告是针对 **JS 版**的历史审查存档。当前活跃实现是 `packages/dsh-tauri-turnrewind-ts`(**TypeScript 重写**),快照模型为 **Git 目录模式**(工作区必须是 Git worktree,非 Git 目录禁用;ignore 语义委托源仓库;无预算预扫描与自定义敏感文件名单)——本报告中涉及 `guard.js` 预算扫描与排除规则的部分**不适用于当前实现**。其余安全边界(路径检查、冲突二次校验、原子 bak-swap 恢复、barrier/FIFO、needs-recovery、pending plan 原子 claim)在 TS 版同样保留并有测试钉住。TS 版的专项状态见 `TURN_REWIND_GIT_DIR_PROGRESS.md`,审查对照记录见 `TURN_REWIND_REVIEW_2026-09-03.md`。
## 1. 执行摘要
diff --git a/docs/TURN_REWIND_REVIEW_2026-09-03.md b/docs/TURN_REWIND_REVIEW_2026-09-03.md
new file mode 100644
index 00000000..3b4fa73d
--- /dev/null
+++ b/docs/TURN_REWIND_REVIEW_2026-09-03.md
@@ -0,0 +1,422 @@
+# dsh-tauri-turnrewind 审查报告
+
+> 审查日期:2026-09-03
+> 审查对象:`packages/dsh-tauri-turnrewind-ts`(当前 TypeScript rewrite),审查时以 `plugins/dsh-tauri-turnrewind`(legacy JavaScript 实现,**现已删除**)作为对照
+> 相关设计:`docs/TURN_REWIND.md`
+> 相关用户文档:`packages/dsh-tauri-turnrewind-ts/README.md`
+
+## 1. 执行摘要
+
+当前 TypeScript 版本已经实现了一个可运行的单回合 turn rewind MVP:Git worktree 资格检查、私有 snapshot repo、baseline barrier、预览/确认/取消、冲突检测、单回合 Undo、基础 Redo、notice 注入、快照自愈以及大文件提示均已有代码和测试。
+
+但它仍不应作为生产级文件恢复功能启用。主要原因是恢复操作仍有数据安全和账本一致性风险:
+
+1. `--force` 在特定路径类型变化下可能递归删除整个目录;
+2. `interrupted` turn Undo 后可能没有正确变为 `undone`;
+3. 文件恢复、operation、turn 状态和 notice 不是一个完整的数据库事务;
+4. Redo 尚未具备与 Undo 对等的失败回滚和 `needs-recovery` 机制;
+5. 恢复仍直接使用 Node/Git,尚未接入受控 sandbox/Tauri bridge;
+6. 只有进程内互斥,没有跨进程持久化 workspace lock。
+
+因此当前适合继续在可丢弃的测试工作区验证,不建议在真实用户工作区中启用。
+
+## 2. 审查范围
+
+### 2.1 源码
+
+- `packages/dsh-tauri-turnrewind-ts/src/host/apply.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/guard.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/host/routes/index.ts`
+- `packages/dsh-tauri-turnrewind-ts/src/client/**`
+- `packages/dsh-tauri-turnrewind-ts/package.json`
+- `packages/dsh-tauri-turnrewind-ts/cordis.patch.yml`
+
+### 2.2 文档
+
+- `docs/TURN_REWIND.md`
+- `packages/dsh-tauri-turnrewind-ts/README.md`
+- `plugins/dsh-tauri-turnrewind/README.md`
+- `docs/PROJECT_STATUS.md`
+- `docs/AGENTS.plugins.md`
+
+### 2.3 对照实现
+
+- `plugins/dsh-tauri-turnrewind/lib/index.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/ledger.js`
+- `plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js`
+- `plugins/dsh-tauri-turnrewind/lib/client.js`
+
+## 3. 完成度矩阵
+
+| 能力 | 状态 | 说明 |
+| --- | --- | --- |
+| Git worktree 资格检查 | 已实现 | 非 Git workspace、系统目录会被拒绝;子目录归并到 worktree 根 |
+| 私有 Git snapshot repo | 已实现 | 位于 `$DSH_HOME/snapshots/<hash>.git` |
+| 不修改用户 Git 状态 | 已实现 | 已有测试覆盖 HEAD、branch、index、stash、refs 和 status |
+| Git ignore / alternates | 已实现 | 有 ignore、`.git/info/exclude`、global excludes 和 GC 自愈测试 |
+| baseline barrier | 已实现 | `agent/pre-step` 等待 before snapshot 完成 |
+| 单回合 Undo | 基本实现 | 修改/创建/删除文件的基础路径可恢复 |
+| 预览 / 确认 / 取消 | 基本实现 | pending plan 存 SQLite,默认 5 分钟过期 |
+| 冲突检测 | 已实现 | 当前磁盘状态与 turn after snapshot 比较 |
+| `--skip-conflicts` | 已实现 | 跳过冲突文件并报告 |
+| `--force` | 已实现但有风险 | 非普通文件路径类型变化可能触发破坏性递归删除 |
+| 基础 Redo | 已实现但不安全 | 失败时没有完整回滚和恢复围栏 |
+| interrupted turn Undo | 部分实现 | 入口接受 interrupted,但账本完成条件只接受 settled |
+| rewind notice | 已实现 | 下一次模型 step 消费一次,可多条 notice 排序注入 |
+| 不可用 workspace 弹窗 | 已实现但集成不足 | 有投影和纯函数测试,缺真实 Web UI 测试 |
+| 快照损坏/alternates 自愈 | 已实现 | 能重建 self-contained snapshot store |
+| 父子 turn 关系 | 未接入 | planner 有纯函数,但实际 insert 没有 parentTurnId |
+| `--subtree` | 未实现 | 当前明确返回 MVP 不支持 |
+| 消息旁 Undo 按钮 | 未实现 | 当前只有 command view 卡片 |
+| 设置页模式切换 | 未实现 | 三种会话回退模式尚未接入 |
+| 非 Git workspace | 当前不支持 | Git directory 实验模式明确要求 Git worktree;与主设计文档旧描述冲突 |
+| 受控 sandbox/Tauri bridge | 未实现 | 当前直接使用 Node filesystem/Git |
+| workspace 持久化锁 | 未实现 | 只有 Host 进程内 Map/Promise 互斥 |
+| snapshot 容量治理 | 未实现 | 没有按容量、turn 数、保留期进行 GC |
+| mode / symlink / special file | 未完整实现 | symlink 可能被当作普通文件;权限位未恢复 |
+| 真实 DSH lifecycle integration test | 未实现 | 当前主要为 fake context 和文件系统测试 |
+
+## 4. Findings
+
+### P0-1:`--force` 可能递归删除整个目录
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts:638-647`
+
+当 before snapshot 中路径不存在,而当前磁盘中的同名路径变成目录时,`restorePath()` 会执行:
+
+```ts
+rmSync(target, { recursive: info.isDirectory(), force: true })
+```
+
+这个行为已经在临时目录中用构建后的 dist 产物实证:turn 新建 `foo`,之后用户将 `foo` 替换为包含其他文件的目录,调用 `restorePath(before, 'foo')` 会返回 removed,并递归删除整个 `foo/` 子树。生产调用链中的路径目前来自 `git diff --name-only`,因此路径为 `.`/空路径、直接删除 workspace 根目录的情形当前不可由正常 diff 触达;但目录子树删除在显式 `--force` 下真实可发生。默认 Undo/confirm 会把目录类型变化标为 conflict 并拦截,`--skip-conflicts` 会跳过,只有 `--force` 绕过该保护。
+
+另外,`assertSafePath()` 当前允许 `target === root`。虽然正常生产路径不会产生此类 path,但直接调用 `restorePath(..., '.')` 已实证会递归删除整个 workspace,因此这是需要补上的防御纵深。
+
+**影响:** 破坏“只恢复 turn 触及路径”的边界,可能造成无关文件数据损失;被源仓库 ignore 的文件不在插件快照中,删除后无法从 turnrewind 快照找回。
+
+**建议:**
+
+- `assertSafePath()` 拒绝 `target === root`;
+- 目标不是普通文件时默认拒绝;
+- 即使 `--force` 也不要递归删除非空目录;
+- 可将冲突目录移入 quarantine,或只允许删除空目录;
+- 预览和 `--force` 确认文案明确提示“目标已变为目录,操作不会递归删除无关文件”;
+- 增加“文件被替换成非空目录后执行 `--force`”以及根路径防御测试。
+
+### P0-2:`interrupted` turn Undo 后账本状态可能错误
+
+**位置:**
+
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:572`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:402-410`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts:513-530`
+
+Undo 入口允许目标状态为 `settled` 或 `interrupted`,但 `completeUndoWithNotice()` 使用:
+
+```sql
+UPDATE turns SET status = 'undone'
+WHERE turn_id = ? AND status = 'settled'
+```
+
+因此 interrupted turn 的文件可能已被恢复,但 turn 仍为 `interrupted`,继续出现在可撤销列表中。该情况已用真实 `executeUndoRestore` 复核:调用返回成功,但 turn 仍是 `interrupted + reversible=1`,后续可再次被 `/undo` 选中。随后 Redo 的:
+
+```sql
+UPDATE turns SET status = 'settled'
+WHERE turn_id = ? AND status = 'undone'
+```
+
+也会更新 0 行,但仍可能写入 Redo operation 和 notice。
+
+**影响:** 文件状态、turn 状态和 operation 状态不一致,可能重复 Undo 或产生错误 Redo 记录。
+
+**建议:**
+
+- Undo 状态更新支持 `settled` 和 `interrupted`;
+- 检查 SQL `changes === 1`,否则事务失败;
+- Redo 同样校验 operation 和 turn 的状态变更行数;
+- 补充 interrupted → undo → redo 的集成测试。
+
+### P0-3:文件恢复与账本提交不是一个完整的可恢复事务
+
+**位置:**
+
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:372-381`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:402-410`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts:513-535`
+
+当前 Undo 大致按以下顺序执行:
+
+1. 捕获 operation before snapshot;
+2. 创建 operation;
+3. 恢复文件;
+4. `completeUndoWithNotice()` 提交 turn 和 notice;
+5. 单独调用 `settleOperation()`。
+
+第 4、5 步不在同一个 SQLite 事务中。该崩溃窗口已用临时目录和构建产物复核:如果 `completeUndoWithNotice()` 已提交而进程在 `settleOperation()` 前退出,重启账本会把 operation 从 `applying` 改成 `needs-recovery`,但 turn 已经是 `undone`、notice 已经 pending。此时 workspace 会被恢复围栏拦截,错误提示“上一次 Undo/Redo 被中断”,而 Redo 也因只查 `outcome = 'applied'` 的 operation 而不可用。
+
+**影响:** 磁盘、turn、operation、notice 互相矛盾;重启后的诊断和 Redo 选择可能错误。
+
+**建议:**
+
+新增一个完整的 ledger transaction API,在同一事务中完成:
+
+- 校验目标 turn 当前状态;
+- operation → `applied`;
+- turn → `undone`;
+- 插入 notice;
+- 保存恢复结果和未恢复路径。
+
+SQLite 与文件系统无法构成真正跨系统事务,但当账本提交失败时,至少应将 operation 标记为 `needs-recovery` 并阻止继续操作。
+
+### P0-4:Redo 没有与 Undo 对等的失败恢复机制
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:58-112`
+
+README 已明确记录 Redo 的已知缺陷:Redo 不创建 applying operation、不保存可用于失败回滚的 operation 记录,也没有 `needs-recovery` 围栏。
+
+如果 Redo 恢复多个文件时中途失败,可能出现部分文件已重做、turn 仍为 undone、旧 operation 仍可重做的状态。重启后也不会自动阻止该 workspace。
+
+**建议:**
+
+在修复前:
+
+- 默认禁用 `/undo --redo`,或限制为已证明安全的普通文件集合;
+- 不要把 Redo 作为 README 中的正常可用能力宣传。
+
+正式实现时复用 Undo 框架:创建 applying operation、保存 before snapshot、失败回滚、失败时写入 needs-recovery、最后以一个事务提交状态和 notice。
+
+### P0-5:单路径恢复失败没有持久化为 partial outcome
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:383-417`
+
+`executeUndoRestore()` 会有意吞掉单个路径的恢复异常,把失败放入内存中的 `failedPaths`,继续恢复其他文件,最后仍然无条件执行 `completeUndoWithNotice()` 和 `settleOperation(..., 'applied')`。当前测试也把这种行为作为预期:大文件失败时整体返回 success,turn 标记为 `undone`。
+
+这本身可以是“尽力恢复”的产品选择,但失败事实没有完整进入账本:
+
+- `operations.error` 保持为空;
+- notice 只记录 `restoredPaths`,不包含失败路径;
+- 直接命令执行的失败明细只有返回文本;
+- 账本没有 `partial` / `partial_failure` outcome 或失败路径明细。
+
+**影响:** 重启、审计或后续 Redo 无法可靠知道哪些文件实际没有恢复。用户看到的是部分结果,但持久状态可能看起来像完整 applied。
+
+**建议:**
+
+- 增加 `partial` 或 `partial_failure` operation outcome;
+- 单独持久化 operation paths、每路径 resolution/result/error;
+- notice 同时包含未恢复路径和原因;
+- 明确部分 Undo 是否允许 Redo,以及 Redo 的目标路径集合;
+- 在 operation 状态确定后再允许 turn 进入对应的 `undone`/`partial` 状态。
+
+## 5. P1 风险
+
+### P1-1:只有进程内互斥,没有 workspace 持久锁
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/apply.ts:191-204`、`packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:460-474`
+
+当前通过 `runtime.undoing`、`active Map` 和 per-session Promise chain 防止单进程内并发。它无法覆盖多个 Host 进程、多个 profile、Host 重启交界或外部维护脚本同时操作的情况。
+
+**建议:** 使用 SQLite lease 或带 PID/时间戳的 lock 文件,覆盖 capture、settle、Undo、Redo、GC 和 snapshot rebuild,并设计崩溃接管规则。
+
+### P1-2:pending plan 没有完整绑定预览时的 snapshot/digest
+
+**位置:**
+
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts:288-314`
+- `packages/dsh-tauri-turnrewind-ts/src/host/apply.ts:440-463`
+- `packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts:521-534`
+
+文档中的 `planVersion` 应绑定 workspace、target turn、快照版本和当前摘要。当前 pending plan 主要保存 plan ID、session、workspace、turn 和 paths;确认时会重新计算路径和冲突,但 `row.paths` 没有作为严格版本校验使用。
+
+**建议:** 保存并校验 before/after ref、paths digest、workspace digest 和 turn 状态,确认时拒绝任何计划版本漂移。
+
+### P1-3:symlink 被静默当成普通文件
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts:579-600`、`:638-655`
+
+Git snapshot 中的 symlink 目前可能通过 `git show` 读出 link target 文本,随后 `stateAt()` 返回 `kind: file`,恢复时写成普通文件,而不是恢复 symlink。
+
+**影响:** 恢复后的文件类型错误,且不是明确的 unsupported/failure。
+
+**建议:** 首版应明确拒绝并标记 symlink 为 unsupported,或完整保存 `linkTarget` 并实现安全恢复。增加 symlink capture、diff、undo round-trip 测试。
+
+### P1-4:文件 mode/权限位未恢复
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts:31-35`、`packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts:655-658`
+
+`PathState` 没有 mode,恢复通过临时文件和 rename 写回,可能丢失 executable、read-only 等权限信息。只改权限不改内容的 turn 也不会进入 snapshot diff。
+
+**建议:** 读取并持久化 Git mode,mode 变化参与 diff,恢复后调用 chmod;Windows 下明确处理只读属性和不支持的特殊文件。
+
+### P1-5:路径校验存在 TOCTOU 窗口
+
+**位置:** `packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts:301-324`、`:638-698`
+
+`assertSafePath()` 校验完成后,到 `mkdirSync`、`renameSync`、删除备份之间仍可能被外部进程替换父目录为 symlink/junction。
+
+**建议:** 优先接入受控 sandbox/Tauri bridge;否则每个关键操作前重新验证 realpath,并增加 Windows reparse point 检测,避免对验证后发生变化的路径继续写入。
+
+## 6. P2 问题与工程改进
+
+### P2-1:子树 Undo 的 planner 没有接入实际 turn 数据
+
+`planner.ts` 已有 `collectDescendantTurns()` 和 `aggregatePathPlan()`,但实际插入 turn 时没有提供 `parentTurnId`。因此 parent/child 关系为空,`--subtree` 仍然只能返回不支持。
+
+建议在确认 DSH 真实 turn tree 契约后,保存 parentTurnId,并实现同一 workspace 内后序遍历、路径聚合和重叠路径目标选择。
+
+### P2-2:主设计文档、实验模式文档和状态文档存在冲突
+
+当前 README 使用 Git directory experiment 语义:非 Git workspace 不支持;而 `docs/TURN_REWIND.md` 的非 Git 章节和验收矩阵仍要求普通目录可恢复。`docs/PROJECT_STATUS.md` 还保留预算预扫描、JS 版本和旧测试数量描述。
+
+建议把以下内容拆开并标注唯一真相源:
+
+- 主线架构目标;
+- Git directory 实验模式;
+- 当前 TypeScript rewrite 实际行为。
+
+### P2-3:legacy JS 包和 TypeScript 包同名
+
+以下两个 package 的 `name` 都是 `dsh-tauri-turnrewind`:
+
+- `plugins/dsh-tauri-turnrewind/package.json`
+- `packages/dsh-tauri-turnrewind-ts/package.json`
+
+版本、入口和依赖不同,可能导致本地安装、发布 manifest 和 `pnpm` filter 选择错误实现。
+
+建议确定一个 canonical package,删除或明确标记另一个 legacy 包,并同步 README、CI、manifest 和发布流程。
+
+### P2-4:快照容量治理未实现
+
+当前有 notice 清理和手工 workspace purge,但没有按总容量、turn 数、保留天数和 operation/redo 引用进行 snapshot/ref/object GC。大仓库长期运行会持续增加 `$DSH_HOME` 占用。
+
+建议实现可配置配额、保留策略、引用检查、低磁盘提前失败和可观测清理结果。
+
+### P2-5:Git worktree 解析仍使用同步子进程
+
+`git-workspace.ts:35-48` 和 `:55-68` 使用 `spawnSync` 执行多次 `rev-parse`。在网络盘、OneDrive、杀毒软件锁定或 Git 异常时仍可能阻塞 Host。
+
+建议缓存稳定的 workspace 元数据,并将探测迁移为带超时的异步执行;至少不要在每次 turn 领取时重复多次同步探测。
+
+### P2-6:status route 没有严格限制 GET
+
+`jsonRoute()` 只对 `mutate: true` 路由检查 POST,而 status route 注册时没有显式方法约束:
+
+```ts
+jsonRoute('/api/turnrewind/status', statusRoute)
+```
+
+建议给 route helper 增加显式 `method`/`methods` 选项,status 只接受 GET,confirm/cancel 只接受 POST。
+
+### P2-7:客户端样式不符合插件规范
+
+`packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts` 和 `src/client/register/dialog.ts` 大量使用 React inline style 和 DOM `element.style`。`docs/AGENTS.plugins.md` 要求自定义样式统一使用 css-render,并由 `apply()` effect 管理挂载/卸载。
+
+建议将 command card 和 dialog 的样式迁移到 css-render 对象树,集中管理 style ID、class name 和 disposer。
+
+## 7. 测试与验证结果
+
+本次验证执行于当前 checkout:
+
+```powershell
+pnpm --filter dsh-tauri-turnrewind typecheck
+```
+
+结果:通过。
+
+```powershell
+pnpm --filter dsh-tauri-turnrewind test -- --run
+```
+
+结果:通过:
+
+- 17 个测试文件;
+- 82 个测试;
+- 全部通过。
+
+覆盖范围包括 Git snapshot、增删改恢复、中文路径、CRLF、路径逃逸、symlink 路径拒绝、ignore 规则、alternates GC 自愈、账本生命周期、baseline barrier、pending plan、Undo/Redo 基础流程和 unsupported notice。
+
+```powershell
+pnpm exec eslint packages/dsh-tauri-turnrewind-ts
+```
+
+结果:0 errors、1 warning:
+
+```text
+packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts:175
+react/set-state-in-effect
+```
+
+```powershell
+pnpm --filter dsh-tauri-turnrewind build
+```
+
+结果:通过,`publint` 通过。
+
+此外,构建后的 Host import smoke test 通过:
+
+```powershell
+node --input-type=module -e "await import('./packages/dsh-tauri-turnrewind-ts/dist/index.js'); console.log('host import ok')"
+```
+
+### 测试不足
+
+当前测试仍不足以证明生产安全性,特别缺少:
+
+- 非空目录替换文件后的 `--force` 测试;
+- interrupted turn Undo/Redo 的账本状态测试;
+- Undo/Redo 中途失败后的文件和 ledger 一致性测试;
+- 跨进程 workspace lock 测试;
+- symlink 快照恢复类型测试;
+- mode/权限位变化测试;
+- Windows junction/reparse point 测试;
+- 真实 DSH Host lifecycle 集成测试;
+- 真实 Web ModuleLoader 和 commandview slot 集成测试;
+- clean install / 发布包发现测试。
+
+## 8. 建议修复顺序
+
+### 第一阶段:先处理数据安全
+
+1. 修复 `restorePath()` 对目录的递归删除;
+2. 修复 interrupted turn 的 Undo/Redo 状态更新;
+3. 统一 operation、turn、notice 的账本事务;
+4. 在 Redo 完成恢复机制前暂时关闭或限制 Redo;
+5. 增加失败恢复和 `needs-recovery` 测试。
+
+### 第二阶段:补齐恢复边界
+
+6. 实现 workspace 持久锁;
+7. 为 pending plan 增加 snapshot/digest 绑定;
+8. 明确 symlink、mode、目录和 special file 策略;
+9. 处理 TOCTOU、junction 和 reparse point;
+10. 接入受控 sandbox/Tauri bridge。
+
+### 第三阶段:补产品和发布能力
+
+11. 接入 parentTurnId 和 subtree Undo;
+12. 实现消息旁 Undo;
+13. 实现设置页回退模式;
+14. 实现 snapshot 容量治理和 GC;
+15. 增加真实 DSH/Web/clean-install 集成测试;
+16. 消除 legacy JS 与 TypeScript 包同名歧义;
+17. 同步架构文档、README、项目状态和发布 manifest。
+
+## 9. 最终结论
+
+当前版本的核心单回合 Undo 链路已经具备继续迭代的基础,测试也证明了正常路径较完整。但在修复 P0 问题前,它不满足文档定义的安全、可恢复和生产级文件回滚标准。
+
+**发布阻断条件:**
+
+- 修复目录递归删除风险;
+- 修复 interrupted turn 的账本状态错误;
+- 为 Undo/Redo 建立可恢复的 operation 状态机;
+- 接入受控 filesystem/sandbox bridge,或明确限制插件运行边界;
+- 补齐真实 DSH lifecycle 和 Web UI 集成测试。
+
+本报告只记录审查结果,本次没有修改插件实现代码。
diff --git a/packages/dsh-tauri-turnrewind-ts/README.md b/packages/dsh-tauri-turnrewind-ts/README.md
index 56b010c2..1c0e1614 100644
--- a/packages/dsh-tauri-turnrewind-ts/README.md
+++ b/packages/dsh-tauri-turnrewind-ts/README.md
@@ -1,10 +1,10 @@
# dsh-tauri-turnrewind
-本地开发中的 DSH turn 回滚插件。
+本地开发中的 DSH turn 回滚插件(**TypeScript 重写版**,位于 `packages/`,遵循 workspace 插件规范;旧 JS 版已移除)。
> 当前 `cordis.patch.yml` 已为本地 debug profile 的实验启用而挂载插件。它仍是原型:恢复路径直接使用 Node/Git,尚未接入受控的宿主 sandbox/Tauri bridge;仅可在可丢弃的测试工作区中启用,不能作为生产功能使用。
>
-> **Git 目录模式(实验分支)**:本分支把快照模型切换为「工作区必须是 Git worktree」(OpenCode 风格):非 Git 目录显式记为不可追踪(`TURNREWIND_GIT_REQUIRED`);ignore 规则(`.gitignore` / `.git/info/exclude` / global excludes / `.gitattributes`)委托给源仓库;私有 snapshot repo 通过 alternates 借用源对象。设计与进度见 `docs/TURN_REWIND_GIT_DIR_PROGRESS.md`——该文档明确本模式是独立实验分支,尚未合并回主功能分支。
+> **Git 目录模式(当前形态)**:工作区**必须**位于 Git worktree(OpenCode 风格)。非 Git 目录显式禁用——turn 记为 `skipped`(`TURNREWIND_GIT_REQUIRED`),`/undo` 说明原因,不再为普通目录建快照。ignore 规则(`.gitignore` / `.git/info/exclude` / global excludes / `.gitattributes`)委托给源仓库;私有 snapshot repo 通过 alternates 借用源对象。设计与进度见 `docs/TURN_REWIND_GIT_DIR_PROGRESS.md`。
## 当前状态
@@ -17,7 +17,7 @@
- **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;被清空前留下来的旧 turn 会在 `/undo` 选目标时自动识别为死快照并标记跳过(`snapshot ref missing`),不会甩出 git 原始报错;
- **alternates 失效自愈**:私有 repo 通过 alternates 借用源仓库对象,而源仓库 `git gc --prune=now`(amend/rebase 的日常残留)可能删掉被借用且不可达的对象;每次 capture 后做连通性检查(`git rev-list --objects --missing=print`),发现缺对象即降级为自包含存储(不再借用、不再复制源 index)并重建基线,旧 turn 走死快照跳过路径;
- **工作区资格守卫(Git 目录模式)**:会话 cwd 必须位于 Git worktree(子目录自动归并到 worktree 根,共享同一快照域);家目录、家目录祖先、盘根等系统目录直接拒绝;非 Git 目录记为 `TURNREWIND_GIT_REQUIRED`,不再做全目录预算扫描(见「工作区资格」);
-- **不可用弹窗**:客户端半(`lib/client.js`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、跟随应用主题、每个浏览器只弹一次);
+- **不可用弹窗**:客户端半(`src/client/`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、跟随应用主题、每个浏览器只弹一次);
- **两阶段 `/undo`**:先出预览卡(红绿 diff + `+x -y` 徽标 + 文件清单),卡内 ✓/✗ 按钮确认执行或取消——不看预览就不会误执行;计划 5 分钟过期,确认时二次校验磁盘;
- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖,并给出「turn 产物 → 当前磁盘」的冲突 diff;
- 冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)直接执行;
@@ -25,7 +25,7 @@
- 注册人类命令 `/undo`;
- `/undo` 默认处理当前会话最新的单个可恢复 turn,也可指定完整 turn ID;
- 同一 workspace 的活动 turn 或 undo 操作互斥;
-- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;**redo 路径尚未接入该机制**(已知缺陷,功能冻结中,见「已知缺陷:redo」);当前只能先人工检查 workspace,再停止 Host 并使用 `purge-workspace.js` 清理该 workspace 的 turnrewind 数据后恢复使用;
+- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;**redo 路径尚未接入该机制**(已知缺陷,功能冻结中,见「已知缺陷:redo」);当前只能先人工检查 workspace,再停止 Host 并使用 purge 工具(见下文「清理已膨胀的快照数据」)清理该 workspace 的 turnrewind 数据后恢复使用;
- 每次 Undo/Redo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;
- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。
@@ -72,9 +72,9 @@
父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。
-## 工作区资格(Git 目录模式)
+## 工作区资格(Git-only)
-快照的第一版实现会对任意工作区做全量基线,曾有用户在 QQ 机器人会话(默认工作目录是家目录、约 250 GB 内容)上触发 `git add --all` 级别的灾难。本分支(Git 目录模式)改为以**源仓库的 Git worktree 为快照边界**,不再做全目录预算扫描。turn 开始前的资格检查:
+曾有用户在 QQ 机器人会话(默认工作目录是家目录、约 250 GB 内容)上触发 `git add --all` 级别的灾难,早期版本因此引入了全目录预算扫描。当前实现以**源仓库的 Git worktree 为快照边界**:**非 Git 目录禁用**(不再做预算扫描,也不再为普通目录建快照)。turn 开始前的资格检查:
1. **系统目录直接拒绝**:家目录本身、家目录的祖先目录(如 `C:\Users`、`C:\`)、以及任何盘符根目录。这类目录无论多小都不做快照。
2. **必须是 Git worktree**:会话 cwd 不在 Git worktree 内的 turn 记为 `skipped`(原因 `TURNREWIND_GIT_REQUIRED`)。子目录会话自动归并到 worktree 根(`git rev-parse --show-toplevel`),共享同一快照域;同一仓库的 linked worktree 各自成域。
@@ -83,7 +83,7 @@
被拒绝的 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` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。
+2. **Web UI 弹窗**:宿主端 `turnrewind` 会话投影(`src/host/service/dialog-projection.ts`)把提示折叠进会话列表快照,客户端半(`src/client/register/dialog.ts`)从 `sessions.list` 的 `projectionValues.turnrewind` 读到后弹出模态对话框,按提示 id 在 `localStorage` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。
大工作区的取舍:不再做预算预扫描,快照耗时与磁盘占用随仓库规模增长(Git ignore 能排除 `node_modules` 等,但容量/性能风险仍由使用者自行承担);单文件快照/恢复上限为 64 MB——超限文件仍会被捕获进快照,`/undo` 预览会以 `[too large]` 标注并在执行后单文件报告为「未恢复」,**不会**导致整次 undo 失败,其余文件照常恢复。若项目里有此类大文件且不希望被追踪,请把它们加进源仓库的 ignore 规则。
@@ -92,10 +92,12 @@
如果某个工作区在旧版本下已经生成过巨大快照,先停止 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
+node packages\dsh-tauri-turnrewind-ts\dist\purge-workspace.js "C:\Users\<user>" # release 数据目录 ~/.dsh
+node packages\dsh-tauri-turnrewind-ts\dist\purge-workspace.js "C:\Users\<user>" --home "$env:USERPROFILE\.dsh.dev" # debug
```
+(需先 `pnpm --filter dsh-tauri-turnrewind build` 产出 `dist/`。)
+
该命令删除该工作区对应的私有快照仓库(`$DSH_HOME/snapshots/<hash>.git`)及其全部账本记录(turns / operations / notices / workspaces),其他工作区的数据不受影响。
## Undo 的工作区范围
@@ -322,26 +324,27 @@ commit history
## Debug 安装
-在当前 checkout 中执行:
+TS 版插件位于 `packages/dsh-tauri-turnrewind-ts`,构建产物在 `dist/`。在当前 checkout 中执行:
```powershell
-pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
-$env:DSH_HOME = "$env:USERPROFILE\.dsh.dev"
-node "$env:APPDATA\io.github.hairyf.deepseek-harness-desktop\dependencies\dsh\node_modules\@deepseek-ai\dsh\lib\bin.js" plugin --profile web add "$(Resolve-Path plugins/dsh-tauri-turnrewind)"
+pnpm install
+pnpm --filter dsh-tauri-turnrewind build
+pnpm --filter dsh-tauri-turnrewind test
```
-插件包必须先通过 `pnpm add` / `dsh plugin add` 安装,不能仅把源码目录放在项目里就期待 DSH 加载。修改 Host 代码后需要重启对应的 DSH debug Host 进程。
+插件通过 `pnpm add` / `dsh plugin add` 安装(debug 桌面端启动时会自动以 `link:` 方式安装全部内部插件)。修改 Host 代码后需要重新 `pnpm --filter dsh-tauri-turnrewind build` 并重启 DSH debug Host 进程;修改 Client 代码后同理(client bundle 在 Host 启动时发现)。
## 测试
-运行插件测试:
+运行插件 lint 与测试:
```powershell
-pnpm exec eslint plugins/dsh-tauri-turnrewind
-pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
+pnpm --filter dsh-tauri-turnrewind exec eslint src
+pnpm --filter dsh-tauri-turnrewind typecheck
+pnpm --filter dsh-tauri-turnrewind test
```
-当前测试覆盖 Git 快照、增删改恢复、中文路径、CRLF、路径逃逸、符号链接、敏感文件排除、账本生命周期、interrupted turn 和多次 notice。
+当前 17 个测试文件、82 个测试,覆盖:Git 快照(增删改恢复、中文路径、CRLF、路径逃逸、符号链接、ignore 委托、alternates 复用与自愈)、原子 bak-swap 恢复与崩溃清扫、Git 状态零污染(HEAD/branch/index/status/refs/stash 不变)、linked worktree 隔离、oversized blob 单文件报告、账本生命周期、pending plan 原子 claim、interrupted turn、barrier 时序、undo/redo 往返、client 纯函数(输出解析/plan 状态判定/会话归属)。
## 当前限制
@@ -350,8 +353,8 @@ pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
- 接入受控的宿主 sandbox/Tauri bridge;
- 完成真实 DSH lifecycle integration tests;
- 快照容量治理:按 turn 数/容量/保留期清理旧 snapshot ref(当前只做断链自愈,不清理历史);
-- 完善 Git 仓库工作区的增量基线(参考 OpenCode:共享用户对象库 + 仅 stage 变更路径);
- 完善多 workspace 并发锁;
- 实现父对话递归 undo;
- 实现消息旁 Undo 按钮;
-- 明确二进制、重命名、权限位和特殊文件策略。
+- 明确二进制、重命名、权限位和特殊文件策略;
+- redo 执行段接入 operation 记录与失败回滚(见「已知缺陷:redo」)。
diff --git a/packages/dsh-tauri-turnrewind-ts/package.json b/packages/dsh-tauri-turnrewind-ts/package.json
index b213811d..4e8aade1 100644
--- a/packages/dsh-tauri-turnrewind-ts/package.json
+++ b/packages/dsh-tauri-turnrewind-ts/package.json
@@ -43,7 +43,11 @@
"platform": "web",
"inject": [
"@deepseek-ai/dsh-client-runtime",
- "@deepseek-ai/dsh-client-locale"
+ "@deepseek-ai/dsh-client-locale",
+ "dsh-tauri"
+ ],
+ "external": [
+ "dsh-tauri/client"
]
}
},
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts b/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
new file mode 100644
index 00000000..983314fa
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
@@ -0,0 +1,420 @@
+/**
+ * client/components/command-view.ts — /undo 命令卡片 React 组件。
+ *
+ * 渲染两阶段 undo 的预览卡:徽标(+x -y)、文件清单、点击展开红绿 diff、
+ * 确认/取消按钮与 plan 状态轮询。卡片状态以账本为唯一事实来源——刷新页面后
+ * 从 persisted plan status 重建,而不是内存态。
+ */
+
+import type { ParsedUndoFile, ParsedUndoOutput } from '../types'
+import React, { useEffect, useRef, useState } from 'react'
+import { TURNREWIND_HTTP_BASE, TURNREWIND_POLL_INTERVAL_MS } from '../constants'
+import { parseUndoOutput, resolvePlanStatus } from '../utils/parse'
+import { resolveOwnerSessionId } from '../utils/session'
+
+// ------------------------------------------------------------------
+// 颜色:全部引用应用主题 token(带硬编码 fallback),随主题切换实时变化。
+// ------------------------------------------------------------------
+const DIFF_COLORS = {
+ delBg: 'rgba(248, 81, 73, 0.26)',
+ addBg: 'rgba(63, 185, 80, 0.38)',
+ del: 'var(--dsw-alias-state-error-primary, #f85149)',
+ add: 'var(--dsw-alias-state-success-primary, #3fb950)',
+ delText: 'var(--dsw-alias-state-error-primary, #ffb3ab)',
+ addText: 'var(--dsw-alias-state-success-primary, #8ff0a4)',
+ hunk: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
+ meta: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
+ text: 'var(--dsw-alias-label-secondary, #cccccc)',
+ bg: 'var(--dsw-alias-bg-layer-2, #161b22)',
+ border: 'var(--dsw-alias-border-l2, #30363d)',
+} as const
+
+/** 连续轮询失败上限(404/gone 不计——它们直接 settle plan)。 */
+const MAX_POLL_FAILURES = 5
+
+function isFileSeparator(raw: string): boolean {
+ return /^--- (?!a\/)(?!b\/)\S/.test(raw)
+}
+
+type LineKind = 'del' | 'add' | 'hunk' | 'meta' | 'ctx'
+
+function classifyLine(raw: string): { kind: LineKind, text: string } {
+ const line = raw
+ if (/^\s*(?:diff --git |index )/.test(line))
+ return { kind: 'meta', text: line.trim() }
+ if (/^\s*--- a\//.test(line) || /^\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 diffLineStyle(kind: LineKind): React.CSSProperties {
+ switch (kind) {
+ case 'del': return { background: DIFF_COLORS.delBg, color: DIFF_COLORS.delText }
+ case 'add': return { background: DIFF_COLORS.addBg, color: DIFF_COLORS.addText }
+ case 'hunk': return { color: DIFF_COLORS.hunk }
+ case 'meta': return { color: DIFF_COLORS.meta }
+ default: return { color: DIFF_COLORS.text }
+ }
+}
+
+function diffSign(kind: LineKind): string {
+ if (kind === 'del')
+ return '-'
+ if (kind === 'add')
+ return '+'
+ return ' '
+}
+
+interface DiffLineEntry {
+ kind: LineKind
+ text: string
+}
+
+function DiffLine({ entry }: { entry: DiffLineEntry }): React.ReactElement {
+ return React.createElement('div', {
+ style: {
+ display: 'flex',
+ fontFamily: 'var(--ds-font-family-code, monospace)',
+ fontSize: '12px',
+ lineHeight: '19px',
+ paddingLeft: 8,
+ paddingRight: 8,
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-all',
+ ...diffLineStyle(entry.kind),
+ },
+ }, React.createElement('span', {
+ style: {
+ width: 14,
+ flex: 'none',
+ color: entry.kind === 'del' ? DIFF_COLORS.del : entry.kind === 'add' ? DIFF_COLORS.add : 'transparent',
+ userSelect: 'none',
+ },
+ }, diffSign(entry.kind)), React.createElement('span', { style: { flex: 1 } }, entry.text))
+}
+
+function NumBadge({ additions, deletions }: { additions: number, deletions: number }): React.ReactElement | null {
+ if (additions === 0 && deletions === 0)
+ return null
+ return React.createElement('span', {
+ style: { display: 'inline-flex', gap: 6, flex: 'none', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11 },
+ }, React.createElement('span', { style: { color: 'var(--dsw-alias-state-success-primary, #3fb950)' } }, `+${additions}`), React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' } }, `-${deletions}`))
+}
+
+function DiffBlock({ file }: { file: ParsedUndoFile }): React.ReactElement {
+ const rows: React.ReactElement[] = []
+ for (const line of file.diff) {
+ if (isFileSeparator(line))
+ continue
+ const trimmed = line.trim()
+ if (trimmed.startsWith('diff --git ') || trimmed.startsWith('index ') || trimmed.startsWith('--- a/') || trimmed.startsWith('+++ b/') || trimmed.startsWith('\\'))
+ continue
+ rows.push(React.createElement(DiffLine, { key: `${file.path}:${rows.length}`, entry: classifyLine(line) }))
+ }
+ return React.createElement('div', {
+ style: { marginTop: 8, border: `1px solid ${DIFF_COLORS.border}`, borderRadius: 8, overflow: 'hidden' },
+ }, React.createElement('div', {
+ style: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ padding: '5px 10px',
+ fontFamily: 'var(--ds-font-family-code, monospace)',
+ fontSize: '11.5',
+ color: 'var(--dsw-alias-label-secondary, #cccccc)',
+ borderBottom: `1px solid ${DIFF_COLORS.border}`,
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
+ },
+ }, React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' } }, file.change), React.createElement('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, file.path), React.createElement(NumBadge, { additions: file.additions, deletions: file.deletions })), React.createElement('div', { style: { maxHeight: 260, overflowY: 'auto', padding: '3px 0' } }, rows))
+}
+
+// ------------------------------------------------------------------
+// 提交通道:由 apply() 注入,插件 stop 时置空(effect 生命周期拥有)。
+// ------------------------------------------------------------------
+type SubmitLine = (line: string, ownerSessionId: string | null) => Promise<string | null>
+let submitLine: SubmitLine | null = null
+
+/** 供 apply() 安装/卸载提交通道。 */
+export function setSubmitLine(next: SubmitLine | null): void {
+ submitLine = next
+}
+
+// ------------------------------------------------------------------
+// 命令卡片组件。
+// ------------------------------------------------------------------
+export interface CommandViewProps {
+ node?: { id?: string, name?: string, sessionId?: string, outcome?: { kind?: string, text?: string } }
+ sessionId?: string
+}
+
+export function UndoCommandView(props: CommandViewProps): React.ReactElement {
+ const node = props.node ?? {}
+ const ownerSessionId = resolveOwnerSessionId(props)
+ const outcome = node.outcome
+ const text = typeof outcome?.text === 'string' ? outcome.text : ''
+ const state = outcome == null ? 'running' : outcome.kind === 'error' ? 'error' : 'ok'
+ const parsed: ParsedUndoOutput = parseUndoOutput(text)
+ const withDiff = parsed.files.filter(file => file.diff.length > 0)
+ const totals = parsed.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 })
+ const hasDiff = withDiff.length > 0
+ const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')
+
+ // 展开状态按命令持久化:用户折叠后刷新不重新展开。
+ const expandKey = `turnrewind.expanded.${node.id ?? parsed.planId ?? parsed.summary}`
+ const [expanded, setExpanded] = useState(hasDiff)
+ useEffect(() => {
+ try {
+ const stored = globalThis.localStorage.getItem(expandKey)
+ if (stored === '0' || stored === '1')
+ setExpanded(stored === '1')
+ }
+ catch {}
+ }, [expandKey])
+
+ function toggleExpanded(): void {
+ setExpanded((v) => {
+ const next = !v
+ try {
+ globalThis.localStorage.setItem(expandKey, next ? '1' : '0')
+ }
+ catch {}
+ return next
+ })
+ }
+
+ // plan 状态(账本为唯一事实来源;重建后从 persisted state 恢复)。
+ const [submitted, setSubmitted] = useState<'confirm' | 'cancel' | null>(null)
+ // 提交中状态:点击后立即置位,按钮禁用并显示 spinner,防止重复点击。
+ // 注意与 submittingRef 并存:ref 挡同步双击,state 驱动 UI(禁用 + spinner)。
+ const [submitting, setSubmitting] = useState(false)
+ const [submitError, setSubmitError] = useState<string | null>(null)
+ const [resultText, setResultText] = useState<string | null>(null)
+ const [planStatus, setPlanStatus] = useState<string | null>(null)
+
+ // 轮询 plan 状态:mount 立即查一次(刷新后从 persisted state 重建卡片),直到 settle。
+ useEffect(() => {
+ if (state !== 'ok' || !parsed.planId)
+ return
+ let stop = false
+ let timer: ReturnType<typeof setInterval> | null = null
+ let failures = 0
+ const controller = new AbortController()
+ function haltPolling(): void {
+ stop = true
+ if (timer !== null) {
+ clearInterval(timer)
+ timer = null
+ }
+ }
+ async function check(): Promise<void> {
+ if (stop)
+ return
+ try {
+ const res = await fetch(`${TURNREWIND_HTTP_BASE}/status?planId=${encodeURIComponent(parsed.planId!)}&sessionId=${encodeURIComponent(ownerSessionId ?? '')}`, { signal: controller.signal })
+ const payload = await res.json().catch(() => ({}) as Record<string, unknown>)
+ if (stop)
+ return
+ const next = resolvePlanStatus({ ok: res.ok, status: res.status }, payload as { status?: string, resultText?: string | null })
+ if (next.status !== null && next.status !== 'pending')
+ setPlanStatus(next.status)
+ else if (next.status === 'pending')
+ setPlanStatus('pending')
+ if (next.status === 'applied')
+ setResultText(next.resultText ?? '已执行')
+ if (next.stop) {
+ haltPolling()
+ return
+ }
+ failures = next.status === 'pending' ? 0 : failures + 1
+ if (failures >= MAX_POLL_FAILURES)
+ haltPolling()
+ }
+ catch {
+ if (stop)
+ return
+ failures += 1
+ if (failures >= MAX_POLL_FAILURES)
+ haltPolling()
+ }
+ }
+ void check()
+ timer = setInterval(check, TURNREWIND_POLL_INTERVAL_MS)
+ return () => {
+ controller.abort()
+ haltPolling()
+ }
+ }, [state, parsed.planId, ownerSessionId])
+
+ const titleColor = state === 'error' ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-primary, #cccccc)'
+ const collapsed = planStatus === 'cancelled' || planStatus === 'gone'
+ const showBody = expanded && !collapsed && (hasDiff || parsed.files.length > 0)
+ const actionable = parsed.planId !== undefined && state === 'ok' && !collapsed && (planStatus === null || planStatus === 'pending')
+ // ref 防抖:React 状态更新慢一拍,双击会绕过 state-only 检查发两次请求。
+ const submittingRef = useRef(false)
+
+ async function submit(kind: 'confirm' | 'cancel'): Promise<void> {
+ if (submittingRef.current || submitting || submitted || !parsed.planId)
+ return
+ submittingRef.current = true
+ setSubmitting(true)
+ setSubmitError(null)
+ try {
+ const line = kind === 'confirm'
+ ? `/undo --confirm ${parsed.planId}`
+ : `/undo --cancel ${parsed.planId}`
+ const failure = submitLine ? await submitLine(line, ownerSessionId) : 'submit channel unavailable'
+ if (failure) {
+ // 保持可重试:plan 仍 pending。
+ setSubmitError(failure)
+ submittingRef.current = false
+ setSubmitting(false)
+ return
+ }
+ // POST 本身已完成:撤掉 spinner,按钮进入「已提交」态;
+ // 最终结果(applied/cancelled)由轮询从账本确认。
+ submittingRef.current = false
+ setSubmitting(false)
+ setSubmitted(kind)
+ }
+ catch (error) {
+ submittingRef.current = false
+ setSubmitting(false)
+ setSubmitError(String((error as Error)?.message ?? error))
+ }
+ }
+
+ const confirmLabel = submitting
+ ? '执行中…'
+ : submitted === 'confirm' ? '已提交执行确认' : '✓ 执行'
+ const cancelLabel = submitting
+ ? '取消中…'
+ : submitted === 'cancel' ? '已取消' : '✕ 取消'
+ // plan 提交即置 applying:提示行不等轮询返回就切到等待态。
+ const pendingWait = submitting || submitted === 'confirm' || planStatus === 'applying'
+ const hint = submitError
+ ? `执行确认失败:${submitError}`
+ : resultText || (planStatus === 'applied' || pendingWait
+ ? '已提交,等待执行结果…'
+ : planStatus === 'cancelled' || submitted === 'cancel' ? '已取消' : planStatus === 'gone' ? '该计划已过期,重新执行 /undo 可生成新预览' : '执行将恢复下方文件到本轮改动前')
+ const hintColor = submitError
+ ? 'var(--dsw-alias-state-error-primary, #f85149)'
+ : resultText || planStatus === 'applied'
+ ? 'var(--dsw-alias-state-success-primary, #3fb950)'
+ : 'var(--dsw-alias-label-secondary, #333333)'
+ const showFooter = actionable || submitting || resultText !== null || submitError !== null || submitted !== null || planStatus === 'applied'
+
+ // 取消/过期折叠为无边框细行。
+ if (collapsed) {
+ return React.createElement('div', {
+ style: { display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px 2px 4px', margin: '2px 0 2px 4px', fontSize: 13 },
+ }, React.createElement('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' } }, '▸'), React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)' } }, node.name || 'undo'), React.createElement('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' } }, '·'), React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' } }, hint))
+ }
+
+ return React.createElement('div', {
+ style: {
+ border: `1px solid ${DIFF_COLORS.border}`,
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
+ borderRadius: 12,
+ margin: '4px 0 4px 4px',
+ overflow: 'hidden',
+ maxWidth: '100%',
+ },
+ },
+ // 可折叠标题行。
+ React.createElement('button', {
+ type: 'button',
+ onClick: toggleExpanded,
+ style: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ width: '100%',
+ textAlign: 'left',
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '8px 12px',
+ color: titleColor,
+ fontSize: 13,
+ },
+ }, React.createElement('span', {
+ style: {
+ transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)',
+ transition: 'transform .12s',
+ display: 'inline-block',
+ color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
+ },
+ }, '▸'), React.createElement('span', { style: { fontWeight: 500 } }, node.name || 'undo'), React.createElement(NumBadge, { additions: totals.additions, deletions: totals.deletions }), React.createElement('span', {
+ style: {
+ color: 'var(--dsw-alias-label-secondary, #cccccc)',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ flex: 1,
+ minWidth: 0,
+ },
+ }, summary)),
+ // 文件清单 / diff 内容。
+ showBody
+ ? React.createElement('div', {
+ style: { borderTop: `1px solid ${DIFF_COLORS.border}`, padding: hasDiff ? '6px 10px 10px' : '6px 12px 10px' },
+ }, hasDiff
+ ? withDiff.map(file => React.createElement(DiffBlock, { key: file.path, file }))
+ : parsed.files.map(file => React.createElement('div', {
+ key: file.path,
+ style: { display: 'flex', gap: 8, padding: '2px 0', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 12 },
+ }, React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', width: 64, flex: 'none' } }, file.change), React.createElement('span', null, file.path))))
+ : null,
+ // 操作 footer。
+ showFooter
+ ? React.createElement('div', {
+ style: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 10,
+ borderTop: `1px solid ${DIFF_COLORS.border}`,
+ padding: '8px 12px',
+ },
+ }, actionable || submitting
+ ? React.createElement('button', {
+ type: 'button',
+ onClick: () => { void submit('confirm') },
+ disabled: submitting || submitted !== null,
+ style: {
+ background: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
+ color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
+ border: 'none',
+ borderRadius: 8,
+ padding: '5px 16px',
+ fontSize: '12.5px',
+ cursor: submitting ? 'wait' : 'pointer',
+ opacity: submitting ? 0.75 : 1,
+ },
+ }, confirmLabel)
+ : null, actionable || submitting
+ ? React.createElement('button', {
+ type: 'button',
+ onClick: () => { void submit('cancel') },
+ disabled: submitting || submitted !== null,
+ style: {
+ background: 'transparent',
+ color: submitted === 'cancel' ? 'var(--dsw-alias-label-tertiary, #8b8b8b)' : 'var(--dsw-alias-state-error-primary, #f85149)',
+ border: '1px solid var(--dsw-alias-border-l2, #30363d)',
+ borderRadius: 8,
+ padding: '5px 16px',
+ fontSize: '12.5px',
+ cursor: submitting ? 'wait' : 'pointer',
+ opacity: submitting ? 0.75 : 1,
+ },
+ }, cancelLabel)
+ : null, React.createElement('span', { style: { flex: 1 } }), React.createElement('span', {
+ style: { color: hintColor, fontSize: '11.5px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
+ }, hint))
+ : null)
+}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/constants/index.ts b/packages/dsh-tauri-turnrewind-ts/src/client/constants/index.ts
index 74181bb0..ff5fff07 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/constants/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/constants/index.ts
@@ -13,3 +13,27 @@ export const TURNREWIND_STYLE_ID = 'dsh-tauri-turnrewind-dialog'
/** 卡片/弹窗 CSS class 前缀。 */
export const TURNREWIND_CLASS_PREFIX = 'dsh-turnrewind'
+
+/** /undo 命令卡片槽位(DSH 会话命令视图标准槽)。 */
+export const COMMAND_VIEW_SLOT = 'conversation.chat.commandview'
+
+/** 命令卡片在槽内的注册 id。 */
+export const COMMAND_VIEW_ID = 'turnrewind-undo-card'
+
+/** keyed slot 的 key(同一 slot 的多个组件按 key 区分)。 */
+export const COMMAND_VIEW_KEY = 'undo'
+
+/** effect 标签(诊断/日志)。 */
+export const COMMAND_VIEW_EFFECT = 'turnrewind command view'
+
+/** locale 命名空间(不可用弹窗双语)。 */
+export const TURNREWIND_LOCALE_NS = 'dsh-tauri-turnrewind'
+
+/** 弹窗已读去重的 localStorage key。 */
+export const SEEN_NOTICES_KEY = 'turnrewind.seenUnsupportedNotices'
+
+/** 弹窗去重列表长度上限。 */
+export const MAX_SEEN_NOTICES = 100
+
+/** 同源 HTTP 路由前缀(Host 注册的 /api/turnrewind/*)。 */
+export const TURNREWIND_HTTP_BASE = '/api/turnrewind'
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts b/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
index 6b7842a4..460f2ee1 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/index.ts
@@ -2,14 +2,18 @@
* dsh-tauri-turnrewind 客户端插件体(browser half):两阶段 undo 卡片与不可用弹窗。
*
* 目录规划:constants/ types/ utils/(纯函数)locales/(双语)register/
- * (卡片/弹窗注册);与 node half(host/)经 /api/turnrewind/* 通信。
+ * (卡片/弹窗注册)/ components/(React 组件);与 node half(host/)经
+ * /api/turnrewind/* 通信。
*/
import type { ClientContext } from 'dsh-tauri/client'
import type { LocaleKey } from './locales'
import { compat } from 'dsh-tauri/client'
-import { TURNREWIND_POLL_INTERVAL_MS, TURNREWIND_POLL_STOP_MS } from './constants'
+import { setSubmitLine } from './components/command-view'
+import { TURNREWIND_HTTP_BASE, TURNREWIND_LOCALE_NS } from './constants'
import { LOCALES } from './locales'
+import { registerCommandView } from './register/command-view'
+import { disposeDialog, pickFreshNotices, showDialog } from './register/dialog'
import { parseUndoOutput, resolvePlanStatus } from './utils/parse'
import { resolveOwnerSessionId } from './utils/session'
@@ -37,8 +41,84 @@ export function apply(ctx: ClientContext): void {
return dict[key]
}
- void t
- void TURNREWIND_POLL_INTERVAL_MS
- void TURNREWIND_POLL_STOP_MS
- void parseUndoOutput
+ // ————————————————— 命令卡片 slot 注册 —————————————————
+ ctx.effect(() => registerCommandView(ctx), 'turnrewind command view')
+
+ // ————————————————— locale 安装 —————————————————
+ ctx.effect(() => {
+ const disposer = locale.register(TURNREWIND_LOCALE_NS, 'zh', Object.fromEntries(Object.entries(LOCALES.zh)))
+ return disposer
+ }, 'turnrewind locale')
+ ctx.effect(() => {
+ const disposer = locale.register(TURNREWIND_LOCALE_NS, 'en', Object.fromEntries(Object.entries(LOCALES.en)))
+ return disposer
+ }, 'turnrewind locale en')
+
+ // ————————————————— ✓/✗ 提交通道 —————————————————
+ // 直接 POST 到插件的同源 HTTP 路由(宿主页面本身由同一 Host 服务,无需额外
+ // auth wiring)。返回错误字符串让卡片可以显示真实失败原因。
+ ctx.effect(() => {
+ setSubmitLine(async (line, ownerSessionId) => {
+ try {
+ if (typeof ownerSessionId !== 'string' || ownerSessionId.length === 0)
+ return '无法确定该卡片所属的会话,请刷新页面后重试'
+ const kind = line.includes('--confirm') ? 'confirm' : 'cancel'
+ const planId = line.split(' ').at(-1)!
+ const res = await fetch(`${TURNREWIND_HTTP_BASE}/${kind}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ planId, sessionId: ownerSessionId }),
+ })
+ const payload = await res.json().catch(() => ({}) as Record<string, unknown>)
+ if (!res.ok)
+ return (payload as { error?: string }).error ?? `HTTP ${res.status}`
+ return null
+ }
+ catch (error) {
+ console.error('[turnrewind] failed to submit undo confirmation:', error)
+ return String((error as Error)?.message ?? error)
+ }
+ })
+ return () => {
+ setSubmitLine(null)
+ }
+ }, 'turnrewind submit line')
+
+ // ————————————————— 不可用工作区弹窗 runner —————————————————
+ // 通过 sessions.list 的投影值读取 Host 注入的 unsupported 提示,
+ // 每条提示在 localStorage 去重——同一浏览器只弹一次。
+ const sessions = (ctx as unknown as { get?: (name: string) => unknown }).get?.('sessions') as
+ | { list: { getSnapshot: () => unknown, subscribe: (fn: () => void) => () => void } }
+ | undefined
+
+ function checkOnce(): void {
+ if (!sessions)
+ return
+ const state = sessions.list.getSnapshot() as {
+ current?: string
+ byId?: Record<string, { projectionValues?: { turnrewind?: unknown } }>
+ }
+ const summary = state.current !== undefined ? state.byId?.[state.current] : undefined
+ const value = summary?.projectionValues?.turnrewind
+ const fresh = pickFreshNotices(value)
+ if (fresh.length === 0)
+ return
+ console.warn(`[turnrewind] unsupported heads-up visible: ${fresh.map(notice => notice.id).join(', ')}`)
+ showDialog(t, fresh)
+ }
+
+ ctx.effect(() => {
+ if (!sessions)
+ return () => {}
+ const unsubscribe = sessions.list.subscribe(checkOnce)
+ // 页面加载时投影帧可能在订阅建立前到达;短暂轮询保证时序不会吞掉提示。
+ const poll = setInterval(checkOnce, 2000)
+ const stopPolling = setTimeout(clearInterval, 120000, poll)
+ return () => {
+ unsubscribe()
+ clearInterval(poll)
+ clearTimeout(stopPolling)
+ disposeDialog()
+ }
+ }, 'turnrewind dialog runner')
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts b/packages/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts
new file mode 100644
index 00000000..7dbdacc0
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts
@@ -0,0 +1,20 @@
+/**
+ * client/register/command-view.ts — /undo 命令卡片(红绿 diff + 徽标 + 确认/取消)的 slot 注册。
+ */
+
+import type { Context } from '@deepseek-ai/cordis'
+import { UndoCommandView } from '../components/command-view'
+import { COMMAND_VIEW_ID, COMMAND_VIEW_KEY, COMMAND_VIEW_SLOT } from '../constants'
+
+/** 注册 conversation.chat.commandview 槽位;effect 卸载时释放 inject 句柄。 */
+export function registerCommandView(ctx: Context): () => void {
+ return ctx.slots.inject(COMMAND_VIEW_SLOT as never, () =>
+ ctx.slots.register(
+ {
+ name: COMMAND_VIEW_SLOT,
+ id: COMMAND_VIEW_ID,
+ key: COMMAND_VIEW_KEY,
+ } as never,
+ UndoCommandView,
+ ))
+}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts b/packages/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts
new file mode 100644
index 00000000..7c329727
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts
@@ -0,0 +1,188 @@
+/**
+ * client/register/dialog.ts — 不可用工作区的模态弹窗(双语 + 主题 token + 去重)。
+ *
+ * DOM 直挂(非 React 组件):弹窗只在 apply 生命周期内存在,stop/HMR 时整个
+ * backdrop 子树移除(所有 listener 挂在子树节点上,不会泄漏)。
+ */
+
+import type { LocaleKey } from '../locales'
+import { MAX_SEEN_NOTICES, SEEN_NOTICES_KEY, TURNREWIND_CLASS_PREFIX, TURNREWIND_STYLE_ID } from '../constants'
+
+export interface UnsupportedNotice {
+ id: string
+ reason?: string
+}
+
+interface DialogElements {
+ backdrop: HTMLDivElement
+ title: HTMLDivElement
+ intro: HTMLDivElement
+ reasonLabel: HTMLDivElement
+ reasonBox: HTMLDivElement
+ button: HTMLButtonElement
+}
+
+let dialog: DialogElements | undefined
+
+// ------------------------------------------------------------------
+// localStorage 去重:同一浏览器每条提示只弹一次。
+// ------------------------------------------------------------------
+function readSeen(): string[] {
+ try {
+ const raw = globalThis.localStorage.getItem(SEEN_NOTICES_KEY)
+ const list = raw ? JSON.parse(raw) : []
+ return Array.isArray(list) ? list : []
+ }
+ catch {
+ return []
+ }
+}
+
+function markSeen(id: string): void {
+ try {
+ const seen = readSeen().filter(entry => entry !== id)
+ seen.push(id)
+ globalThis.localStorage.setItem(SEEN_NOTICES_KEY, JSON.stringify(seen.slice(-MAX_SEEN_NOTICES)))
+ }
+ catch {
+ // Storage 不可用时下次重弹即可。
+ }
+}
+
+// ------------------------------------------------------------------
+// 弹窗 DOM:所有颜色走 CSS variable(随主题实时切换),fallback 到硬编码值。
+// ------------------------------------------------------------------
+function ensureDialog(): DialogElements {
+ if (dialog)
+ return dialog
+ const backdrop = document.createElement('div')
+ backdrop.setAttribute('role', 'presentation')
+ backdrop.className = `${TURNREWIND_CLASS_PREFIX}-backdrop`
+ Object.assign(backdrop.style, {
+ display: 'none',
+ position: 'fixed',
+ inset: '0',
+ zIndex: '2147483000',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: 'var(--dsw-alias-bg-mask-1, rgba(0, 0, 0, 0.45))',
+ })
+
+ const card = document.createElement('div')
+ card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
+ card.className = `${TURNREWIND_CLASS_PREFIX}-card`
+ Object.assign(card.style, {
+ maxWidth: '440px',
+ width: 'calc(100vw - 48px)',
+ boxSizing: 'border-box',
+ background: 'var(--dsw-alias-bg-layer-1, #ffffff)',
+ color: 'var(--dsw-alias-label-primary, #111111)',
+ border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
+ borderRadius: '12px',
+ padding: '20px 22px',
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ lineHeight: '1.6',
+ boxShadow: '0 20px 50px rgba(0, 0, 0, 0.25)',
+ })
+
+ const title = document.createElement('div')
+ Object.assign(title.style, {
+ fontSize: '15px',
+ fontWeight: '600',
+ marginBottom: '10px',
+ color: 'var(--dsw-alias-state-error-primary, #d03050)',
+ })
+
+ const intro = document.createElement('div')
+ Object.assign(intro.style, { color: 'var(--dsw-alias-label-secondary, #333333)' })
+
+ const reasonLabel = document.createElement('div')
+ Object.assign(reasonLabel.style, { marginTop: '12px', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: '12px' })
+
+ const reasonBox = document.createElement('div')
+ Object.assign(reasonBox.style, {
+ marginTop: '6px',
+ padding: '8px 10px',
+ borderRadius: '8px',
+ background: 'var(--dsw-alias-bg-layer-2, #f5f5f5)',
+ border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
+ 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: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
+ color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
+ border: 'none',
+ borderRadius: '8px',
+ padding: '6px 18px',
+ fontSize: '13px',
+ cursor: 'pointer',
+ })
+ button.addEventListener('mouseover', () => {
+ button.style.background = 'var(--dsw-alias-button-primary-hover, #4338ca)'
+ })
+ button.addEventListener('mouseout', () => {
+ button.style.background = 'var(--dsw-alias-button-primary-fill, #4f46e5)'
+ })
+ actions.appendChild(button)
+
+ card.append(title, intro, reasonLabel, reasonBox, actions)
+ backdrop.appendChild(card)
+ document.body.appendChild(backdrop)
+
+ function hide(): void {
+ 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
+}
+
+/** 插件 stop/HMR 时整个 backdrop 子树移除——listener 全部随之释放。 */
+export function disposeDialog(): void {
+ if (!dialog)
+ return
+ dialog.backdrop.remove()
+ dialog = undefined
+}
+
+/** 用当前活跃语言填充并显示弹窗。 */
+export function showDialog(t: (key: LocaleKey) => string, notices: UnsupportedNotice[]): void {
+ const el = ensureDialog()
+ el.title.textContent = t('dialogTitle')
+ el.intro.textContent = t('dialogIntro')
+ el.reasonLabel.textContent = t('dialogReason')
+ el.reasonBox.textContent = notices.map(notice => notice.reason || notice.id).join('\n')
+ el.button.textContent = t('dialogConfirm')
+ el.backdrop.style.display = 'flex'
+}
+
+/** 从会话投影中筛选未见过的提示并标记已读。 */
+export function pickFreshNotices(value: unknown): UnsupportedNotice[] {
+ const notices = Array.isArray((value as { notices?: unknown[] })?.notices)
+ ? (value as { notices: unknown[] }).notices
+ : []
+ const fresh = notices.filter((notice): notice is UnsupportedNotice =>
+ notice != null && typeof (notice as UnsupportedNotice).id === 'string' && !readSeen().includes((notice as UnsupportedNotice).id))
+ if (fresh.length > 0) {
+ for (const notice of fresh) markSeen(notice.id)
+ }
+ return fresh
+}
+
+/** style id 导出(供测试断言/未来的 css-render 迁移使用)。 */
+export { TURNREWIND_STYLE_ID }
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/types/index.ts b/packages/dsh-tauri-turnrewind-ts/src/client/types/index.ts
index 8869a4ca..dd3102b4 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/types/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/types/index.ts
@@ -24,7 +24,7 @@ export interface ParsedUndoOutput {
/** plan 状态轮询结果。 */
export interface PlanStatusResolution {
- status: 'pending' | 'applied' | 'gone' | 'error'
+ status: 'pending' | 'applied' | 'cancelled' | 'gone' | 'error' | null
stop: boolean
resultText: string | null
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts b/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
index e9ba1628..38aa9ff6 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
@@ -67,14 +67,16 @@ export function parseUndoOutput(raw: string | undefined): ParsedUndoOutput {
return result
}
-/** plan 状态轮询的结局判定(gone 即停;applied/error 带 resultText)。 */
-export function resolvePlanStatus(res: { ok: boolean, status: number }, payload: { status?: string, resultText?: string | null } | null): { status: 'pending' | 'applied' | 'gone' | 'error', stop: boolean, resultText: string | null } {
+/** plan 状态轮询的结局判定(gone 即停;applied/cancelled/error 带 resultText)。 */
+export function resolvePlanStatus(res: { ok: boolean, status: number }, payload: { status?: string, resultText?: string | null } | null): { status: 'pending' | 'applied' | 'cancelled' | 'gone' | 'error' | null, stop: boolean, resultText: string | null } {
+ // Non-404 failures must not settle the card: the plan may still land on a
+ // later poll, so keep polling without flipping to a terminal state.
if (!res.ok)
- return { status: res.status === 404 ? 'gone' : 'error', stop: res.status === 404, resultText: null }
+ return { status: res.status === 404 ? 'gone' : 'pending', stop: res.status === 404, resultText: null }
const status = payload?.status
if (status === 'gone')
return { status: 'gone', stop: true, resultText: null }
if (status === 'applied' || status === 'cancelled' || status === 'error')
- return { status: status === 'error' ? 'error' : 'applied', stop: true, resultText: payload?.resultText ?? null }
+ return { status, stop: true, resultText: payload?.resultText ?? null }
return { status: 'pending', stop: false, resultText: null }
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
index e30581b9..7226b49e 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
@@ -36,12 +36,9 @@ export const SNAPSHOT_PATHSPECS: string[] = [
':(exclude,glob)**/*.turnrewind-restore.bak',
]
-/** pending plan 存活时长。 */
+/** pending plan 存活时长(只影响未执行的预览;settled 结果行永久保留可追溯)。 */
export const PENDING_PLAN_TTL_MS = 5 * 60 * 1000
-/** pending plan 结果行的保留时长。 */
-export const PENDING_PLAN_RESULT_TTL_MS = 24 * 60 * 60 * 1000
-
/** endedTurns 内存上界。 */
export const MAX_ENDED_TURNS = 500
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
index 8be5ec80..aa2754bb 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
@@ -9,7 +9,7 @@ import { randomUUID } from 'node:crypto'
import { mkdirSync } from 'node:fs'
import { DatabaseSync } from 'node:sqlite'
import { dirname, join } from 'pathe'
-import { PENDING_PLAN_RESULT_TTL_MS, PENDING_PLAN_TTL_MS } from '../constants'
+import { PENDING_PLAN_TTL_MS } from '../constants'
const SCHEMA = `
PRAGMA journal_mode = WAL;
@@ -157,12 +157,16 @@ export function openLedger(rootDir: string): Ledger {
return db
}
-/** 失效 plan 清扫:过期 pending 删除;已结束结果行超过保留期删除。 */
+/**
+ * 失效 plan 清扫:只删过期的 pending 行。
+ *
+ * settled 行(applied/cancelled)**永远保留**:undo 的执行结果必须可追溯
+ * (刷新页面、跨天查看、审计),结果行就是持久记录——删了它卡片就变成
+ * "gone",用户看不到已经执行了什么。
+ */
export function prunePendingPlans(db: Ledger): void {
- const now = new Date().toISOString()
- db.prepare('DELETE FROM pending_plans WHERE status = \'pending\' AND expires_at < ?').run(now)
- db.prepare('DELETE FROM pending_plans WHERE status <> \'pending\' AND created_at < ?')
- .run(new Date(Date.now() - PENDING_PLAN_RESULT_TTL_MS).toISOString())
+ db.prepare('DELETE FROM pending_plans WHERE status = \'pending\' AND expires_at < ?')
+ .run(new Date().toISOString())
}
export function registerWorkspace(db: Ledger, workspaceKey: string, workspacePath: string, snapshotRepo: string): void {
diff --git a/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js b/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
index 36566f7d..683ae994 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/client-view.test.js
@@ -1,83 +1,62 @@
import assert from 'node:assert/strict'
import { it } from 'vitest'
-import '../src/client/index'
-
-/**
- * Load the client bundle the way the tests need it: the DSH module loader is
- * absent under Node, so client.js exposes its factory on globalThis and the
- * pure helpers can be exercised with a stub `require` (nothing dereferences
- * React/jsx-runtime at load time — only inside component bodies).
- */
-function loadBundle() {
- const factory = globalThis.__turnrewindClientFactory
- assert.equal(typeof factory, 'function', 'client.js must expose its factory when __ModuleLoader__ is absent')
- const stubRequire = () => ({ jsx: () => null, jsxs: () => null })
- return factory(stubRequire)
-}
+import * as client from '../src/client/index'
it('exposes the cordis plugin face and pure helpers', () => {
- const bundle = loadBundle()
- assert.equal(typeof bundle.apply, 'function')
- assert.deepEqual(bundle.inject, ['slots', 'sessions', 'locale'])
- assert.equal(typeof bundle.parseUndoOutput, 'function')
- assert.equal(typeof bundle.resolvePlanStatus, 'function')
- assert.equal(typeof bundle.resolveOwnerSessionId, 'function')
+ assert.equal(typeof client.apply, 'function')
+ assert.deepEqual(client.inject, ['slots', 'sessions', 'locale'])
+ assert.equal(typeof client.parseUndoOutput, 'function')
+ assert.equal(typeof client.resolvePlanStatus, 'function')
+ assert.equal(typeof client.resolveOwnerSessionId, 'function')
})
it('resolvePlanStatus settles an expired plan as gone and stops polling', () => {
- const bundle = loadBundle()
// The host route answers 404 once the pending plan expired or was purged.
- const expired = bundle.resolvePlanStatus({ ok: false, status: 404 }, {})
+ const expired = client.resolvePlanStatus({ ok: false, status: 404 }, {})
assert.deepEqual(expired, { status: 'gone', stop: true, resultText: null })
// A host that ever reports gone explicitly settles the same way.
- const explicit = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'gone' })
+ const explicit = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'gone' })
assert.deepEqual(explicit, { status: 'gone', stop: true, resultText: null })
})
it('resolvePlanStatus stops polling once the plan settles', () => {
- const bundle = loadBundle()
- const applied = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied', resultText: 'Undid turn x' })
+ const applied = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied', resultText: 'Undid turn x' })
assert.deepEqual(applied, { status: 'applied', stop: true, resultText: 'Undid turn x' })
// Missing resultText stays null so the card can substitute its own label.
- const appliedBare = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied' })
+ const appliedBare = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied' })
assert.deepEqual(appliedBare, { status: 'applied', stop: true, resultText: null })
- const cancelled = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'cancelled' })
+ const cancelled = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'cancelled' })
assert.deepEqual(cancelled, { status: 'cancelled', stop: true, resultText: null })
})
it('resolvePlanStatus keeps polling pending plans', () => {
- const bundle = loadBundle()
- const pending = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'pending' })
+ const pending = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'pending' })
assert.deepEqual(pending, { status: 'pending', stop: false, resultText: null })
})
-it('resolvePlanStatus keeps polling on non-404 failures without touching state', () => {
- const bundle = loadBundle()
+it('resolvePlanStatus keeps polling on non-404 failures without settling the plan', () => {
for (const res of [{ ok: false, status: 500 }, { ok: false, status: 503 }, { ok: true, status: 200 }]) {
- const next = bundle.resolvePlanStatus(res, res.ok ? {} : { error: 'boom' })
- assert.deepEqual(next, { status: null, stop: false, resultText: null })
+ const next = client.resolvePlanStatus(res, res.ok ? {} : { error: 'boom' })
+ assert.deepEqual(next, { status: 'pending', stop: false, resultText: null })
}
})
it('resolveOwnerSessionId prefers the session-scoped prop over the node', () => {
- const bundle = loadBundle()
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: 'session-b' } }), 'session-a')
+ assert.equal(client.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: 'session-b' } }), 'session-a')
// Node field is the fallback for hosts that attach it to the command node.
- assert.equal(bundle.resolveOwnerSessionId({ node: { sessionId: 'session-b' } }), 'session-b')
+ assert.equal(client.resolveOwnerSessionId({ node: { sessionId: 'session-b' } }), 'session-b')
})
it('resolveOwnerSessionId never guesses from missing or invalid ids', () => {
- const bundle = loadBundle()
- assert.equal(bundle.resolveOwnerSessionId({}), null)
- assert.equal(bundle.resolveOwnerSessionId(undefined), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: '' }), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 42 }), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: '' } }), 'session-a')
+ assert.equal(client.resolveOwnerSessionId({}), null)
+ assert.equal(client.resolveOwnerSessionId(undefined), null)
+ assert.equal(client.resolveOwnerSessionId({ sessionId: '' }), null)
+ assert.equal(client.resolveOwnerSessionId({ sessionId: 42 }), null)
+ assert.equal(client.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: '' } }), 'session-a')
})
it('parseUndoOutput still extracts the pending plan id', () => {
- const bundle = loadBundle()
- const parsed = bundle.parseUndoOutput([
+ const parsed = client.parseUndoOutput([
'Undo preflight: turn s:1; 1 file(s); 0 conflicts.',
' modified a.txt',
'',
@@ -94,8 +73,7 @@ it('parseUndoOutput still extracts the pending plan id', () => {
})
it('parseUndoOutput keeps paths with spaces and plan flags out of the conflict fallback', () => {
- const bundle = loadBundle()
- const parsed = bundle.parseUndoOutput([
+ const parsed = client.parseUndoOutput([
'Undo preflight: turn s:1; 3 file(s) (modified 2, created 1, deleted 0); 1 conflict(s).',
' modified my notes.txt',
' created reports/q3 summary.md',
diff --git a/packages/dsh-tauri-turnrewind-ts/vitest.config.ts b/packages/dsh-tauri-turnrewind-ts/vitest.config.ts
index 06c74aff..ab33fb46 100644
--- a/packages/dsh-tauri-turnrewind-ts/vitest.config.ts
+++ b/packages/dsh-tauri-turnrewind-ts/vitest.config.ts
@@ -1,8 +1,19 @@
+import { resolve } from 'node:path'
import { defineConfig } from 'vitest/config'
// Tests import from src/ (TS) directly; keep the config local so vitest does
// not climb up and load the desktop shell's vite.config.ts.
+//
+// `dsh-tauri/client` must alias to its TS source: the built dist/client.cjs
+// begins with `window.__ModuleLoader__.load(...)`, which is a browser-only
+// classic script — importing it under Node (the vitest default environment)
+// throws `window is not defined` before any test runs.
export default defineConfig({
+ resolve: {
+ alias: {
+ 'dsh-tauri/client': resolve(import.meta.dirname, '../dsh-tauri/src/client/index.ts'),
+ },
+ },
test: {
include: ['test/**/*.test.js'],
testTimeout: 120000,
diff --git a/plugins/dsh-tauri-turnrewind/.gitignore b/plugins/dsh-tauri-turnrewind/.gitignore
deleted file mode 100644
index eee69496..00000000
--- a/plugins/dsh-tauri-turnrewind/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-node_modules/
-dist/
-coverage/
-*.sqlite
-*.sqlite-*
-.turnrewind/
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
deleted file mode 100644
index 56b010c2..00000000
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ /dev/null
@@ -1,357 +0,0 @@
-# dsh-tauri-turnrewind
-
-本地开发中的 DSH turn 回滚插件。
-
-> 当前 `cordis.patch.yml` 已为本地 debug profile 的实验启用而挂载插件。它仍是原型:恢复路径直接使用 Node/Git,尚未接入受控的宿主 sandbox/Tauri bridge;仅可在可丢弃的测试工作区中启用,不能作为生产功能使用。
->
-> **Git 目录模式(实验分支)**:本分支把快照模型切换为「工作区必须是 Git worktree」(OpenCode 风格):非 Git 目录显式记为不可追踪(`TURNREWIND_GIT_REQUIRED`);ignore 规则(`.gitignore` / `.git/info/exclude` / global excludes / `.gitattributes`)委托给源仓库;私有 snapshot repo 通过 alternates 借用源对象。设计与进度见 `docs/TURN_REWIND_GIT_DIR_PROGRESS.md`——该文档明确本模式是独立实验分支,尚未合并回主功能分支。
-
-## 当前状态
-
-这是 Host MVP 原型,当前实现:
-
-- 为已领取的 Agent turn 建立私有 Git 快照;
-- 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
-- **git 子进程模型**:快照、diff、恢复走异步 spawn,不阻塞 Host 事件循环;同一会话的捕获/结算按 FIFO 串行;收到 turn 输入后,before snapshot 通过 `agent/pre-step` barrier 完成后才允许模型和工具执行;同一 workspace 被其他 session 占用时,新 turn 会正常运行但记为 `skipped`,避免共享 snapshot 链互相污染。**仍有两处同步路径**:工作区解析(git-workspace.js 的 rev-parse spawnSync,每次 turn 领取触发数次,单次 <100ms)与冲突检测的磁盘读取(currentState 同步读单个文件,上限 64MB)——超重工作区上可能短暂卡顿,异步化在待办中;
-- **git 可用性探测**:系统没有 git 时,turn 显式记为 `skipped`(原因 `TURNREWIND_GIT_UNAVAILABLE`),而不是静默失败;
-- **快照链自愈**:私有快照仓库被删/损坏后,下一次捕获自动降级重建基线(日志有一条 warning),后续 turn 照常可撤销;被清空前留下来的旧 turn 会在 `/undo` 选目标时自动识别为死快照并标记跳过(`snapshot ref missing`),不会甩出 git 原始报错;
-- **alternates 失效自愈**:私有 repo 通过 alternates 借用源仓库对象,而源仓库 `git gc --prune=now`(amend/rebase 的日常残留)可能删掉被借用且不可达的对象;每次 capture 后做连通性检查(`git rev-list --objects --missing=print`),发现缺对象即降级为自包含存储(不再借用、不再复制源 index)并重建基线,旧 turn 走死快照跳过路径;
-- **工作区资格守卫(Git 目录模式)**:会话 cwd 必须位于 Git worktree(子目录自动归并到 worktree 根,共享同一快照域);家目录、家目录祖先、盘根等系统目录直接拒绝;非 Git 目录记为 `TURNREWIND_GIT_REQUIRED`,不再做全目录预算扫描(见「工作区资格」);
-- **不可用弹窗**:客户端半(`lib/client.js`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、跟随应用主题、每个浏览器只弹一次);
-- **两阶段 `/undo`**:先出预览卡(红绿 diff + `+x -y` 徽标 + 文件清单),卡内 ✓/✗ 按钮确认执行或取消——不看预览就不会误执行;计划 5 分钟过期,确认时二次校验磁盘;
-- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖,并给出「turn 产物 → 当前磁盘」的冲突 diff;
-- 冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)直接执行;
-- `/undo --redo` 重做最近一次已应用的 undo(磁盘在 undo 后被改动则拒绝);
-- 注册人类命令 `/undo`;
-- `/undo` 默认处理当前会话最新的单个可恢复 turn,也可指定完整 turn ID;
-- 同一 workspace 的活动 turn 或 undo 操作互斥;
-- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖;**redo 路径尚未接入该机制**(已知缺陷,功能冻结中,见「已知缺陷:redo」);当前只能先人工检查 workspace,再停止 Host 并使用 `purge-workspace.js` 清理该 workspace 的 turnrewind 数据后恢复使用;
-- 每次 Undo/Redo 的回退提示独立持久化;下一次模型 step 一次性注入全部 pending notice;
-- 不修改用户项目的 HEAD、分支、index、stash 或提交历史。
-
-## 使用方法
-
-在已加载本插件的 DSH 会话中:
-
-```text
-/undo
-```
-
-默认进入**两阶段流程**:先输出预览卡(每个文件的红绿 diff 与 `+x -y` 徽标),
-卡内附两个按钮——**✓ 执行撤销** 与 **✕ 取消**。点 ✓ 才会真正恢复文件;
-不点击的话计划 5 分钟后自动过期,不会误执行。确认时还会二次校验磁盘,
-预览之后文件又被改动过(冲突)会拒绝执行并提示重新预览。
-
-也可以指定完整 turn ID、或只看计划不动手:
-
-```text
-/undo <session-id>:<turn-number>
-/undo --dry-run # 仅输出文件清单与分类,不含 diff
-/undo --preview # 输出内容与 /undo 的预览卡一致
-```
-
-磁盘在预览后又被改动(冲突)时,可以选择处理策略:
-
-```text
-/undo --skip-conflicts # 只恢复无冲突文件,跳过的文件会列出
-/undo --force # 强制覆盖冲突文件(执行前仍有回滚点保护)
-```
-
-其他:
-
-```text
-/undo --redo # 重做最近一次已应用的 undo
-/undo --cancel <plan-id> # 取消一个待确认的预览计划
-```
-
-当前不支持:
-
-```text
-/undo --subtree
-```
-
-父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。
-
-## 工作区资格(Git 目录模式)
-
-快照的第一版实现会对任意工作区做全量基线,曾有用户在 QQ 机器人会话(默认工作目录是家目录、约 250 GB 内容)上触发 `git add --all` 级别的灾难。本分支(Git 目录模式)改为以**源仓库的 Git worktree 为快照边界**,不再做全目录预算扫描。turn 开始前的资格检查:
-
-1. **系统目录直接拒绝**:家目录本身、家目录的祖先目录(如 `C:\Users`、`C:\`)、以及任何盘符根目录。这类目录无论多小都不做快照。
-2. **必须是 Git worktree**:会话 cwd 不在 Git worktree 内的 turn 记为 `skipped`(原因 `TURNREWIND_GIT_REQUIRED`)。子目录会话自动归并到 worktree 根(`git rev-parse --show-toplevel`),共享同一快照域;同一仓库的 linked worktree 各自成域。
-3. **快照范围委托给源仓库 ignore 规则**:`.gitignore`、`.git/info/exclude`(每次 capture 重同步)、global excludes 与 `.gitattributes` 语义与源仓库一致;插件自身只额外排除 `.git` 元数据与 turnrewind 临时文件。**不再有自定义敏感文件名单**——未写进 ignore 的文件(含 `.env`、密钥类文件)会被快照;这是有意的取舍:`token.ts`、`credentials.module.ts` 等合法源码曾被旧规则静默排除,导致 undo 永远无法恢复它们。若不希望某些文件进入快照,请把它们加进源仓库的 ignore 规则。
-
-被拒绝的 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` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。
-
-大工作区的取舍:不再做预算预扫描,快照耗时与磁盘占用随仓库规模增长(Git ignore 能排除 `node_modules` 等,但容量/性能风险仍由使用者自行承担);单文件快照/恢复上限为 64 MB——超限文件仍会被捕获进快照,`/undo` 预览会以 `[too large]` 标注并在执行后单文件报告为「未恢复」,**不会**导致整次 undo 失败,其余文件照常恢复。若项目里有此类大文件且不希望被追踪,请把它们加进源仓库的 ignore 规则。
-
-### 清理已膨胀的快照数据
-
-如果某个工作区在旧版本下已经生成过巨大快照,先停止 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 的范围是:
-
-```text
-当前 session 绑定的 workspace(session header 的 cwd)
-```
-
-例如当前 session 的工作区是:
-
-```text
-C:\Users\<user>\Desktop\test
-```
-
-插件只会比较和恢复该目录以内、且被快照规则允许的文件。它不是“恢复整台电脑”,也不是“恢复所有 Agent 访问过的路径”。
-
-一次 turn 的文件范围是:
-
-```text
-turn 开始时的 workspace 快照
- ↓
-Agent 执行
- ↓
-turn 结束时的 workspace 快照
- ↓
-两次快照之间发生变化的文件
-```
-
-Undo 只恢复两次快照之间发生变化的文件:
-
-- Agent 修改的文件:恢复到 turn 开始前;
-- Agent 新建的文件:Undo 时删除;
-- Agent 删除的文件:Undo 时恢复;
-- 未发生变化的文件:不处理。
-
-## Workspace 外的文件
-
-如果 Agent 访问或修改了 workspace 外的文件,当前版本**不会捕获,也不会 Undo**。
-
-例如当前 workspace 是:
-
-```text
-C:\Users\<user>\Desktop\test
-```
-
-Agent 修改了:
-
-```text
-C:\Users\<user>\Desktop\test\a.txt
-C:\Users\<user>\Desktop\other\b.txt
-```
-
-执行 `/undo` 时:
-
-```text
-test\a.txt → 可能被恢复
-test 之外的 b.txt → 不会被处理
-```
-
-workspace 外的修改不会:
-
-- 写入 turn 的 before/after snapshot;
-- 出现在 `/undo --dry-run` 文件列表;
-- 被 `/undo` 恢复;
-- 出现在 rewind notice 的文件列表中。
-
-在 `workspace-write` 权限模式下,宿主 sandbox 通常会阻止 Agent 写出 workspace;但如果使用 `danger-full-access` 或其他方式允许外部写入,**Agent 能写成功不代表 turnrewind 能回退这些文件**。
-
-插件自己的恢复操作会拒绝以下路径:
-
-```text
-../outside.txt
-C:\OtherProject\file.txt
-workspace 内指向外部的符号链接路径
-```
-
-如果确实需要管理多个项目,应将它们作为独立 workspace 分别运行,不要把多个项目目录混成一个恢复域。
-
-## 不同修改方式的捕获规则
-
-当前插件按 workspace 在 turn 前后的实际差异捕获,不按工具名称判断来源。因此以下 Agent 修改方式通常都会被纳入当前 turn:
-
-- Agent `write`;
-- Agent `edit`;
-- Agent 使用 Git Bash/bash;
-- Agent 使用 PowerShell/pwsh;
-- Agent 运行格式化工具;
-- Agent 运行生成脚本;
-- Agent 通过 Git 命令间接修改文件;
-- Agent 执行其他会改写 workspace 文件的程序。
-
-准确语义是:
-
-```text
-该 workspace 在本 turn 期间发生的允许范围内变化
-```
-
-不是:
-
-```text
-百分之百证明该变化由 AI 直接写入
-```
-
-如果用户或其他程序在 Agent turn 执行期间同时修改同一个 workspace,当前 MVP 可能无法区分来源,也可能把这些变化一起记录到该 turn。建议等待 Agent 完成或打断后,再手动编辑同一 workspace。
-
-如果用户是在 turn 完成后修改文件,Undo 预检会将当前内容与 Agent turn 完成时的快照进行比较。内容不一致时会显示冲突,并默认拒绝覆盖。
-
-## 冲突是什么意思
-
-Undo 不是无条件覆盖。它会检查:
-
-```text
-当前文件状态 == Agent turn 完成时的文件状态?
-```
-
-如果相等,文件可以安全恢复到 turn 开始前。
-
-如果不相等,就会显示类似:
-
-```text
-Undo preflight: turn <turn-id>; 5 file(s); 5 conflict(s): 4.txt, 5.txt, 6.txt, 7.json, 8.md.
-```
-
-含义是:
-
-- 目标 turn 涉及 5 个文件;
-- 当前文件与该 turn 完成时的快照不一致;
-- 插件无法确认这些变化是否来自用户、其他 turn 或外部程序;
-- 默认不会覆盖,文件保持当前状态。
-
-Windows 的 `CRLF` 与 Unix 的 `LF` 换行差异会被文本状态比较规范化,不应单独造成冲突。二进制文件仍按原始字节比较。
-
-冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)处理;默认遇到冲突则拒绝并给出「人改了什么」的 diff。
-
-## 多次 Undo 与模型提示
-
-每次 Undo 都会产生一条独立的 pending rewind notice:
-
-```text
-Undo C → notice C
-Undo B → notice B
-Undo A → notice A
-```
-
-如果在发送下一条普通消息之前连续执行多次 Undo,下一次模型 step 会一次性收到全部 notice,顺序为:
-
-```text
-C、B、A
-```
-
-每条 notice 会列出:
-
-- 被撤销的 turn;
-- 该次 Undo 涉及的文件;
-- “当前磁盘文件是权威状态”;
-- “不要假设旧修改仍存在,请重新读取文件”。
-
-notice 只消费一次。下一次模型 step 后不会重复注入。
-
-## Git 与快照存储
-
-### 快照边界与对象借用(Git 目录模式)
-
-私有 snapshot repo 保存于 `$DSH_HOME/snapshots/<workspace-hash>.git`,与用户项目的 `.git` 完全隔离:capture 使用临时 `GIT_INDEX_FILE`(finally 中删除),snapshot refs 仅允许 `refs/turnrewind/` 前缀;不修改用户项目的 `HEAD`、branch、index、stash 或提交历史(有逐字节不变测试钉住)。初始化时通过 `objects/info/alternates` 借用源仓库对象以减少重复存储,并同步源仓库 `.git/info/exclude`;源仓库 `gc --prune=now` 删掉被借用对象时,下一次 capture 的连通性检查会检测到并降级为自包含存储(见「当前状态」中的 alternates 失效自愈)。
-
-家目录防护与 Git worktree 要求互为兜底:会话 cwd 为家目录/盘根等系统目录时直接拒绝;不在 Git worktree 内的目录记为 `TURNREWIND_GIT_REQUIRED`,不做全目录预算扫描,也没有可配置的 `guard` 预算项(旧版本的 `config.guard` / `TURNREWIND_MAX_*` 已随本模式移除)。
-
-快照存放在插件私有目录:
-
-```text
-$DSH_HOME/snapshots/<workspace-hash>.git
-```
-
-账本存放在:
-
-```text
-$DSH_HOME/ledger.sqlite
-```
-
-插件不会调用用户项目的:
-
-```bash
-git reset --hard
-git checkout .
-git clean -fd
-```
-
-也不会修改用户项目的:
-
-```text
-HEAD
-当前分支
-index
-stash
-commit history
-```
-
-## 快照范围与敏感文件(Git 目录模式)
-
-> ⚠️ **插件不提供敏感文件保护。** 旧版本的自定义排除清单(`.env`、`*.pem`、`credentials.*`、`*token*` 等)已随 Git 目录模式**全部移除**。当前快照范围完全委托给源仓库的 ignore 规则:**未写进 `.gitignore` / `.git/info/exclude` / global excludes 的文件——包括 `.env`、密钥、证书——都会被捕获进私有快照**,并可被 `/undo` 恢复。
-
-插件自身只额外排除(不属于项目内容的部分):
-
-```text
-.git/ # Git 元数据
-.turnrewind/ # 插件临时目录
-**/*.turnrewind-*.tmp # 恢复过程中的临时文件
-```
-
-`node_modules/`、`dist/`、`build/` 等不再由插件排除——由你仓库自己的 `.gitignore` 决定(普通项目都会忽略它们,快照语义因此与源仓库一致)。
-
-两点边界:
-
-- 被源仓库 ignore 的文件不会进入快照,也不会被 undo 恢复;ignore 规则每次 capture 重新读取(`.git/info/exclude` 还会同步进私有 repo);
-- 曾经使用的 `*token*`、`*secret*` 等子串规则已移除——它们会静默排除 `token.ts`、`tokenizer.py` 这类正当源码,且被排除路径不出现在 dry-run 列表中,导致 undo 静默漏恢复。
-
-**如果不希望秘密文件进入快照**:把它们加进源仓库的 ignore 规则(对 git 和本插件同时生效)。也可以在 `/undo --dry-run` 的文件清单里核对实际被追踪的范围。插件仍是实验原型,不应把它当作秘密信息保护工具。
-
-### 已知缺陷:redo(暂缓)
-
-`/undo --redo` 的执行段**尚未**接入 operation 记录与失败回滚:执行中任一文件恢复失败(超大文件、目标路径变为 symlink/目录、rename 失败)会留下「部分 redo」状态,无回滚、无 `needs-recovery` 标记,重启后围栏不会拦截该 workspace。该功能目前按计划冻结、后续启用时与 undo 路径对齐(`createOperation` → 失败回滚 → `needs-recovery`)后再开放;在此之前请勿在含 >64 MB 文件或路径状态复杂的 turn 上使用 redo。
-
-## Debug 安装
-
-在当前 checkout 中执行:
-
-```powershell
-pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
-$env:DSH_HOME = "$env:USERPROFILE\.dsh.dev"
-node "$env:APPDATA\io.github.hairyf.deepseek-harness-desktop\dependencies\dsh\node_modules\@deepseek-ai\dsh\lib\bin.js" plugin --profile web add "$(Resolve-Path plugins/dsh-tauri-turnrewind)"
-```
-
-插件包必须先通过 `pnpm add` / `dsh plugin add` 安装,不能仅把源码目录放在项目里就期待 DSH 加载。修改 Host 代码后需要重启对应的 DSH debug Host 进程。
-
-## 测试
-
-运行插件测试:
-
-```powershell
-pnpm exec eslint plugins/dsh-tauri-turnrewind
-pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
-```
-
-当前测试覆盖 Git 快照、增删改恢复、中文路径、CRLF、路径逃逸、符号链接、敏感文件排除、账本生命周期、interrupted turn 和多次 notice。
-
-## 当前限制
-
-这是实验性版本,正式启用前仍需要:
-
-- 接入受控的宿主 sandbox/Tauri bridge;
-- 完成真实 DSH lifecycle integration tests;
-- 快照容量治理:按 turn 数/容量/保留期清理旧 snapshot ref(当前只做断链自愈,不清理历史);
-- 完善 Git 仓库工作区的增量基线(参考 OpenCode:共享用户对象库 + 仅 stage 变更路径);
-- 完善多 workspace 并发锁;
-- 实现父对话递归 undo;
-- 实现消息旁 Undo 按钮;
-- 明确二进制、重命名、权限位和特殊文件策略。
diff --git a/plugins/dsh-tauri-turnrewind/cordis.patch.yml b/plugins/dsh-tauri-turnrewind/cordis.patch.yml
deleted file mode 100644
index 6ef649bb..00000000
--- a/plugins/dsh-tauri-turnrewind/cordis.patch.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-# Local development patch for dsh-tauri-turnrewind.
-# Add this row to a profile only after the Host MVP is reviewed.
-- insert:
- # Experimental local activation requested by the developer.
- # Use only with a disposable test workspace until the sandbox bridge lands.
- - id: turnrewind
- name: dsh-tauri-turnrewind
diff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.js
deleted file mode 100644
index e49e2a45..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/client.js
+++ /dev/null
@@ -1,752 +0,0 @@
-// dsh-tauri-turnrewind — client bundle (browser).
-//
-// One module, three jobs (the boot manifest imports the plugin under its
-// package name, so everything lives in this single factory):
-// 1. Renders the `/undo` command card in the `conversation.chat.commandview`
-// slot: +x -y badge, changed-file list, click-to-expand red/green diffs.
-// 2. Raises the in-app "undo unavailable" dialog when the current session
-// carries the unsupported-workspace heads-up injected by the host.
-//
-// 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`
-// (services the apply() context needs). The module system strips a trailing
-// `/client` from ids, so this id normalizes to the package name.
-
-/**
- * Build the client bundle. Extracted as a named factory so tests (Node/vitest,
- * where `__ModuleLoader__` is absent) can load it with a stub `require` and
- * exercise the pure helpers; the browser path below is unchanged.
- * @param require - CommonJS-style require provided by the DSH module loader.
- * @returns the module exports ({ apply, inject, pure helpers }).
- */
-function createTurnrewindClient(require) {
- const module = { exports: {} }
- const exports = module.exports
- const React = require('react')
- const jsxRuntime = require('react/jsx-runtime')
- const jsx = jsxRuntime.jsx
- const jsxs = jsxRuntime.jsxs
-
- const inject = ['slots', 'sessions', 'locale']
- // The ✓/✗ buttons post to the plugin's same-origin HTTP routes (the harness
- // page itself is served by the same host, so no auth wiring is needed);
- // assigned from apply() once the ctx is available. Owned by an effect so a
- // plugin stop clears the channel instead of leaving a stale closure.
- let submitLine = null
-
- // ------------------------------------------------------------------
- // /undo output parsing: the command prints a structured plain-text plan
- // (summary line, indented file list, per-file unified diff sections)
- // plus a trailing machine-readable `plan <id>` confirmation row.
- // ------------------------------------------------------------------
- function isFileSeparator(raw) {
- return /^--- (?!a\/)(?!b\/)\S/.test(raw)
- }
-
- function parseUndoOutput(raw) {
- const lines = (raw ?? '').split('\n')
- const result = { summary: lines[0] ?? '', files: [], dividers: [], planId: undefined }
- let current = null
- let inDiffs = false
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i]
- const planRow = /^plan ([0-9a-f-]+)$/.exec(line)
- if (planRow) {
- result.planId = planRow[1]
- continue
- }
- if (/^Send \/undo --(?:confirm|cancel)/.test(line))
- continue
- if (/^(?:Undo will apply|Conflicts \()/.test(line)) {
- inDiffs = true
- result.dividers.push(line)
- continue
- }
- // Paths may contain spaces ("my notes.txt"), and the plan also appends
- // " [conflict]" / " [too large]" flags. Match the whole remainder and
- // split the flags off so such files land in the file list with the right
- // classification instead of falling through to the diff-separator
- // branch (which would misclassify them as conflicts).
- const listed = /^ {2,}(modified|created|deleted) (.*\S)\s*$/.exec(line)
- if (listed && !inDiffs) {
- let path = listed[2]
- let conflict = false
- if (/\s{2,}\[conflict\]$/.test(path)) {
- conflict = true
- path = path.replace(/\s{2,}\[conflict\]$/, '')
- }
- if (/\s{2,}\[too large\]$/.test(path)) {
- path = path.replace(/\s{2,}\[too large\]$/, '')
- }
- result.files.push({ path, change: listed[1], additions: 0, deletions: 0, diff: [], conflict })
- continue
- }
- const separator = /^--- (?!a\/)(?!b\/)(.+)$/.exec(line)
- if (separator && inDiffs) {
- const path = separator[1].trim()
- current = result.files.find(file => file.path === path)
- if (!current) {
- current = { path, change: 'conflict', additions: 0, deletions: 0, diff: [] }
- result.files.push(current)
- }
- current.diff = []
- continue
- }
- if (current && line.trim() !== '' && inDiffs) {
- const trimmed = line.trim()
- if (/^\+/.test(trimmed) && !/^\+\+\+/.test(trimmed))
- current.additions += 1
- else if (trimmed.startsWith('-') && !trimmed.startsWith('---'))
- current.deletions += 1
- current.diff.push(line)
- }
- }
- return result
- }
-
- // ------------------------------------------------------------------
- // Pure decision for one plan-status poll response. Kept side-effect free
- // so the polling rules are unit-testable without a browser:
- // - 404 (expired/already applied on the host) or an explicit `gone`
- // payload collapses the card and stops polling;
- // - applied/cancelled stop polling;
- // - any other failure keeps polling, up to the caller's failure budget.
- // ------------------------------------------------------------------
- function resolvePlanStatus(res, payload) {
- const status = typeof payload?.status === 'string' ? payload.status : null
- if (res?.status === 404 || status === 'gone')
- return { status: 'gone', stop: true, resultText: null }
- if (res?.ok !== true || status === null)
- return { status: null, stop: false, resultText: null }
- return {
- status,
- stop: status === 'applied' || status === 'cancelled',
- resultText: typeof payload?.resultText === 'string' ? payload.resultText : null,
- }
- }
-
- /**
- * Resolve the session that owns a command card. Session-scoped slots receive
- * `sessionId` as a standard prop from the renderer (the scope the card is
- * rendered under), so prefer it, then an explicit node field. Never fall
- * back to the global current session — the Host re-validates whatever id is
- * sent, and an unresolvable owner must fail fast instead of silently
- * attributing the plan to whichever session happens to be selected.
- * @param props - slot component props.
- * @returns the owner session id, or null when it cannot be determined.
- */
- function resolveOwnerSessionId(props) {
- const candidates = [props?.sessionId, props?.node?.sessionId]
- for (const candidate of candidates) {
- if (typeof candidate === 'string' && candidate.length > 0)
- return candidate
- }
- return null
- }
-
- // ------------------------------------------------------------------
- // /undo command card: rendering.
- // ------------------------------------------------------------------
- const DIFF_COLORS = {
- delBg: 'rgba(248, 81, 73, 0.26)',
- addBg: 'rgba(63, 185, 80, 0.38)',
- del: 'var(--dsw-alias-state-error-primary, #f85149)',
- add: 'var(--dsw-alias-state-success-primary, #3fb950)',
- delText: 'var(--dsw-alias-state-error-primary, #ffb3ab)',
- addText: 'var(--dsw-alias-state-success-primary, #8ff0a4)',
- hunk: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- meta: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
- text: 'var(--dsw-alias-label-secondary, #cccccc)',
- bg: 'var(--dsw-alias-bg-layer-2, #161b22)',
- border: 'var(--dsw-alias-border-l2, #30363d)',
- }
-
- // Stop polling after this many consecutive failed status checks so a broken
- // or unreachable host route cannot spin the interval forever. 404/gone do
- // not count — they settle the plan immediately instead.
- const MAX_POLL_FAILURES = 5
-
- function diffLineStyle(kind) {
- switch (kind) {
- case 'del': return { background: DIFF_COLORS.delBg, color: DIFF_COLORS.delText }
- case 'add': return { background: DIFF_COLORS.addBg, color: DIFF_COLORS.addText }
- case 'hunk': return { color: DIFF_COLORS.hunk }
- case 'meta': return { color: DIFF_COLORS.meta }
- default: return { color: DIFF_COLORS.text }
- }
- }
-
- function diffSign(kind) {
- if (kind === 'del')
- return '-'
- if (kind === 'add')
- return '+'
- return ' '
- }
-
- function DiffLine(props) {
- const entry = props.entry
- return jsxs('div', {
- style: Object.assign(
- { display: 'flex', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: '12px', lineHeight: '19px', paddingLeft: 8, paddingRight: 8, whiteSpace: 'pre-wrap', wordBreak: 'break-all' },
- diffLineStyle(entry.kind),
- ),
- children: [
- jsx('span', {
- style: { width: 14, flex: 'none', color: entry.kind === 'del' ? DIFF_COLORS.del : entry.kind === 'add' ? DIFF_COLORS.add : 'transparent', userSelect: 'none' },
- children: diffSign(entry.kind),
- }),
- jsx('span', { style: { flex: 1 }, children: entry.text }),
- ],
- })
- }
-
- function NumBadge(props) {
- const { additions, deletions } = props
- if (additions === 0 && deletions === 0)
- return null
- return jsxs('span', {
- style: { display: 'inline-flex', gap: 6, flex: 'none', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11 },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-state-success-primary, #3fb950)' }, children: `+${additions}` }),
- jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: `-${deletions}` }),
- ],
- })
- }
-
- function classifyLine(raw) {
- const line = raw
- if (/^\s*(?:diff --git |index )/.test(line))
- return { kind: 'meta', text: line.trim() }
- if (/^\s*--- a\//.test(line) || /^\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 DiffBlock(props) {
- const file = props.file
- const rows = []
- for (const line of file.diff) {
- if (isFileSeparator(line))
- continue
- // VSCode-style clean diff: drop git plumbing noise (diff --git / index /
- // --- a/ / +++ b/ headers and the "\ No newline" markers) and keep only
- // hunk headers plus +/- content lines.
- const trimmed = line.trim()
- if (trimmed.startsWith('diff --git ') || trimmed.startsWith('index ') || trimmed.startsWith('--- a/') || trimmed.startsWith('+++ b/') || trimmed.startsWith('\\'))
- continue
- rows.push(jsx(DiffLine, { entry: classifyLine(line) }, `${file.path}:${rows.length}`))
- }
- return jsxs('div', {
- style: { marginTop: 8, border: `1px solid ${DIFF_COLORS.border}`, borderRadius: 8, overflow: 'hidden' },
- children: [
- jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 8, padding: '5px 10px', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 11.5, color: 'var(--dsw-alias-label-secondary, #cccccc)', borderBottom: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)' },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: file.change }),
- jsx('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: file.path }),
- jsx(NumBadge, { additions: file.additions, deletions: file.deletions }),
- ],
- }),
- jsx('div', { style: { maxHeight: 260, overflowY: 'auto', padding: '3px 0' }, children: rows }),
- ],
- })
- }
-
- function UndoCommandView(props) {
- const node = props.node || {}
- const ownerSessionId = resolveOwnerSessionId(props)
- const outcome = node.outcome
- const text = outcome && typeof outcome.text === 'string' ? outcome.text : ''
- const state = outcome == null ? 'running' : outcome.kind === 'error' ? 'error' : 'ok'
- const parsed = parseUndoOutput(text)
- const withDiff = parsed.files.filter(file => (file.diff?.length ?? 0) > 0)
- const totals = parsed.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 })
- const hasDiff = withDiff.length > 0
- const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')
- // Remember the user's collapse choice per command: a refresh must not
- // re-expand a card the user deliberately folded.
- const expandKey = `turnrewind.expanded.${node.id ?? parsed.planId ?? parsed.summary}`
- const [expanded, setExpanded] = React.useState(hasDiff)
- React.useEffect(() => {
- try {
- const stored = globalThis.localStorage.getItem(expandKey)
- if (stored === '0' || stored === '1')
- setExpanded(stored === '1')
- }
- catch {}
- }, [expandKey])
- function toggleExpanded() {
- setExpanded((v) => {
- const next = !v
- try {
- globalThis.localStorage.setItem(expandKey, next ? '1' : '0')
- }
- catch {}
- return next
- })
- }
- const [submitted, setSubmitted] = React.useState(null)
- const [submitError, setSubmitError] = React.useState(null)
- const [resultText, setResultText] = React.useState(null)
- // The plan's persisted status is the source of truth: it survives page
- // reloads, so the card state (buttons vs applied vs cancelled) rebuilds
- // from it instead of from in-memory React state.
- const [planStatus, setPlanStatus] = React.useState(null)
-
- // Poll the plan status: immediately on mount (a reload must rebuild the
- // card from the persisted state) and until the plan settles. 404/gone
- // settle the card as expired; repeated transport failures stop the poll
- // without changing the card state (the Host re-validates any submit).
- React.useEffect(() => {
- if (state !== 'ok' || !parsed.planId)
- return
- let stop = false
- let timer = null
- let failures = 0
- const controller = new AbortController()
- function haltPolling() {
- stop = true
- if (timer !== null) {
- clearInterval(timer)
- timer = null
- }
- }
- async function check() {
- if (stop)
- return
- try {
- const res = await fetch(`/api/turnrewind/status?planId=${encodeURIComponent(parsed.planId)}&sessionId=${encodeURIComponent(ownerSessionId ?? '')}`, { signal: controller.signal })
- const payload = await res.json().catch(() => ({}))
- if (stop)
- return
- const next = resolvePlanStatus(res, payload)
- if (next.status !== null)
- setPlanStatus(next.status)
- if (next.status === 'applied')
- setResultText(next.resultText ?? '已执行')
- if (next.stop) {
- haltPolling()
- return
- }
- failures = next.status === null ? failures + 1 : 0
- if (failures >= MAX_POLL_FAILURES)
- haltPolling()
- }
- catch {
- if (stop)
- return
- failures += 1
- if (failures >= MAX_POLL_FAILURES)
- haltPolling()
- }
- }
- void check()
- timer = setInterval(check, 1500)
- return () => {
- controller.abort()
- haltPolling()
- }
- }, [state, parsed.planId, ownerSessionId])
-
- const titleColor = state === 'error' ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-primary, #cccccc)'
- // Cancelled/expired plans collapse to a minimal red card: no file list,
- // no diffs, no buttons — nothing that a refresh could resurrect.
- const collapsed = planStatus === 'cancelled' || planStatus === 'gone'
- const showBody = expanded && !collapsed && (hasDiff || parsed.files.length > 0)
- const actionable = parsed.planId !== undefined && state === 'ok' && !collapsed && (planStatus === null || planStatus === 'pending')
- // A synchronous ref guard closes the re-render gap: React state updates
- // land a tick later, so fast double-clicks would both pass a state-only
- // check and fire two confirm requests.
- const submittingRef = React.useRef(false)
-
- async function submit(kind) {
- if (submittingRef.current || submitted || !parsed.planId)
- return
- submittingRef.current = true
- try {
- const line = kind === 'confirm'
- ? `/undo --confirm ${parsed.planId}`
- : `/undo --cancel ${parsed.planId}`
- const failure = submitLine ? await submitLine(line, ownerSessionId) : 'submit channel unavailable'
- if (failure) {
- // Keep the card actionable: the plan is still pending on the host,
- // so the user must be able to retry (or cancel) after the failure.
- setSubmitError(failure)
- submittingRef.current = false
- return
- }
- setSubmitted(kind)
- // Only a server-confirmed cancel folds the card; an optimistic fold
- // here would hide a still-pending plan behind a "已取消" label.
- if (kind === 'cancel')
- setPlanStatus('cancelled')
- }
- catch (error) {
- submittingRef.current = false
- setSubmitError(String(error?.message ?? error))
- }
- }
-
- const confirmLabel = submitted === 'confirm' ? '已提交执行确认' : '✓ 执行'
- const cancelLabel = submitted === 'cancel' ? '已取消' : '✕ 取消'
- const hint = submitError
- ? `执行确认失败:${submitError}`
- : resultText || (planStatus === 'applied' || submitted === 'confirm'
- ? '已提交,等待执行结果…'
- : planStatus === 'cancelled' || submitted === 'cancel' ? '已取消' : planStatus === 'gone' ? '该计划已过期,重新执行 /undo 可生成新预览' : '执行将恢复下方文件到本轮改动前')
- const hintColor = submitError
- ? 'var(--dsw-alias-state-error-primary, #f85149)'
- : resultText || planStatus === 'applied'
- ? 'var(--dsw-alias-state-success-primary, #3fb950)'
- : 'var(--dsw-alias-label-secondary, #333333)'
- // Buttons live only in the actionable footer; the outcome/error hint line
- // must survive after the plan settles, or the success note disappears.
- const showFooter = actionable || resultText !== null || submitError !== null || submitted !== null || planStatus === 'applied'
-
- // Cancelled/expired plans collapse to a frameless slim line, matching
- // the native tool-row look: no card frame, no body, no buttons.
- if (collapsed) {
- return jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px 2px 4px', margin: '2px 0 2px 4px', fontSize: 13 },
- children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '▸' }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)' }, children: node.name || 'undo' }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-dimmed, #8b8b8b)' }, children: '·' }),
- jsx('span', { style: { color: 'var(--dsw-alias-state-error-primary, #f85149)' }, children: hint }),
- ],
- })
- }
-
- return jsxs('div', {
- style: { border: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)', borderRadius: 12, margin: '4px 0 4px 4px', overflow: 'hidden', maxWidth: '100%' },
- children: [
- jsxs('button', {
- type: 'button',
- onClick() { toggleExpanded() },
- style: { display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left', background: 'transparent', border: 'none', cursor: 'pointer', padding: '8px 12px', color: titleColor, fontSize: 13 },
- children: [
- jsx('span', { style: { transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform .12s', display: 'inline-block', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)' }, children: '▸' }),
- jsx('span', { style: { fontWeight: 500 }, children: node.name || 'undo' }),
- jsx(NumBadge, { additions: totals.additions, deletions: totals.deletions }),
- jsx('span', { style: { color: 'var(--dsw-alias-label-secondary, #cccccc)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }, children: summary }),
- ],
- }),
- showBody
- ? jsx('div', { style: { borderTop: `1px solid ${DIFF_COLORS.border}`, padding: hasDiff ? '6px 10px 10px' : '6px 12px 10px' }, children:
- hasDiff
- ? withDiff.map(file => jsx(DiffBlock, { file }, file.path))
- : parsed.files.map(file => jsxs('div', { style: { display: 'flex', gap: 8, padding: '2px 0', fontFamily: 'var(--ds-font-family-code, monospace)', fontSize: 12 }, children: [
- jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', width: 64, flex: 'none' }, children: file.change }),
- jsx('span', { children: file.path }),
- ] }, file.path)) })
- : null,
- showFooter
- ? jsxs('div', {
- style: { display: 'flex', alignItems: 'center', gap: 10, borderTop: `1px solid ${DIFF_COLORS.border}`, padding: '8px 12px' },
- children: [
- actionable
- ? jsxs('button', {
- type: 'button',
- onClick() { submit('confirm') },
- disabled: submitted !== null,
- style: { background: 'var(--dsw-alias-button-primary-fill, #4f46e5)', color: 'var(--dsw-alias-label-primary-foreground, #ffffff)', border: 'none', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
- children: confirmLabel,
- })
- : null,
- actionable
- ? jsx('button', {
- type: 'button',
- onClick() { submit('cancel') },
- disabled: submitted !== null,
- style: { background: 'transparent', color: submitted === 'cancel' ? 'var(--dsw-alias-label-tertiary, #8b8b8b)' : 'var(--dsw-alias-state-error-primary, #f85149)', border: '1px solid var(--dsw-alias-border-l2, #30363d)', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },
- children: cancelLabel,
- })
- : null,
- jsx('span', { style: { flex: 1 } }),
- jsx('span', { style: { color: hintColor, fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: hint }),
- ],
- })
- : null,
- ],
- })
- }
-
- // ------------------------------------------------------------------
- // Unsupported-workspace dialog: storage, DOM, and runner.
- // ------------------------------------------------------------------
- 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 ensureDialog() {
- if (dialog)
- return dialog
- // Colors are app theme tokens (with hardcoded fallbacks), so the dialog
- // follows the in-app light/dark theme live — inline `var()` re-resolves
- // when the theme switches, no rebuild needed.
- 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: 'var(--dsw-alias-bg-mask-1, rgba(0, 0, 0, 0.45))',
- })
-
- 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: 'var(--dsw-alias-bg-layer-1, #ffffff)',
- color: 'var(--dsw-alias-label-primary, #111111)',
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- borderRadius: '12px',
- padding: '20px 22px',
- fontFamily: 'inherit',
- fontSize: '13px',
- lineHeight: '1.6',
- boxShadow: '0 20px 50px rgba(0, 0, 0, 0.25)',
- })
-
- const title = document.createElement('div')
- Object.assign(title.style, {
- fontSize: '15px',
- fontWeight: '600',
- marginBottom: '10px',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- })
-
- const intro = document.createElement('div')
- Object.assign(intro.style, { color: 'var(--dsw-alias-label-secondary, #333333)' })
-
- const reasonLabel = document.createElement('div')
- Object.assign(reasonLabel.style, { marginTop: '12px', color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: '12px' })
-
- const reasonBox = document.createElement('div')
- Object.assign(reasonBox.style, {
- marginTop: '6px',
- padding: '8px 10px',
- borderRadius: '8px',
- background: 'var(--dsw-alias-bg-layer-2, #f5f5f5)',
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- 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: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
- color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
- border: 'none',
- borderRadius: '8px',
- padding: '6px 18px',
- fontSize: '13px',
- cursor: 'pointer',
- })
- button.addEventListener('mouseover', () => {
- button.style.background = 'var(--dsw-alias-button-primary-hover, #4338ca)'
- })
- button.addEventListener('mouseout', () => {
- button.style.background = 'var(--dsw-alias-button-primary-fill, #4f46e5)'
- })
- 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
- }
-
- /**
- * Tear the modal down: removing the backdrop subtree detaches every
- * listener created in ensureDialog (they all live on nodes inside it), so a
- * plugin stop/update/HMR cannot leak the dialog or its handlers. The next
- * apply() builds a fresh dialog from scratch.
- */
- function disposeDialog() {
- if (!dialog)
- return
- dialog.backdrop.remove()
- dialog = undefined
- }
-
- 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'
- }
-
- // ------------------------------------------------------------------
- // Plugin apply: both features share the one cordis plugin this bundle
- // materializes into (the boot manifest imports the package name).
- // ------------------------------------------------------------------
- function apply(ctx) {
- console.warn('[turnrewind] client apply: command card + dialog runner starting')
-
- // The inject disposer is the effect's owned cleanup: returning it lets the
- // fiber unwind the declaration wait and any active registration on
- // stop/update, instead of relying on incidental fiber collection.
- ctx.effect(() => ctx.slots.inject('conversation.chat.commandview', () => {
- return ctx.slots.register({
- name: 'conversation.chat.commandview',
- key: 'undo',
- }, UndoCommandView)
- }), 'turnrewind command view')
-
- // Unsupported-workspace heads-up runner.
- 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')
- // The ✓/✗ buttons post to the plugin's same-origin routes — the most
- // direct client→host channel (no gateway RPC, no auth wiring). Returns
- // an error string so the card can surface real failures instead of
- // silently swallowing an async rejection. The session id comes from the
- // card's own session scope (never the global current selection); the
- // Host re-validates it against the plan's owner session either way.
- ctx.effect(() => {
- submitLine = async (line, ownerSessionId) => {
- try {
- if (typeof ownerSessionId !== 'string' || ownerSessionId.length === 0)
- return '无法确定该卡片所属的会话,请刷新页面后重试'
- const kind = line.includes('--confirm') ? 'confirm' : 'cancel'
- const planId = line.split(' ').at(-1)
- const res = await fetch(`/api/turnrewind/${kind}`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ planId, sessionId: ownerSessionId }),
- })
- const payload = await res.json().catch(() => ({}))
- if (!res.ok)
- return payload.error ?? `HTTP ${res.status}`
- return null
- }
- catch (error) {
- console.error('[turnrewind] failed to submit undo confirmation:', error)
- return String(error?.message ?? error)
- }
- }
- return () => {
- submitLine = null
- }
- }, 'turnrewind submit line')
-
- function checkOnce() {
- 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
- console.warn(`[turnrewind] unsupported heads-up visible: ${fresh.map(notice => notice.id).join(', ')}`)
- for (const notice of fresh) markSeen(notice.id)
- showDialog(t, fresh)
- }
-
- ctx.effect(() => {
- const unsubscribe = sessions.list.subscribe(checkOnce)
- // Projection frames can land while the page is loading, before the list
- // store has any subscribers; poll briefly so that ordering can never
- // silently swallow the heads-up.
- const poll = setInterval(checkOnce, 2000)
- const stopPolling = setTimeout(clearInterval, 120000, poll)
- return () => {
- unsubscribe()
- clearInterval(poll)
- clearTimeout(stopPolling)
- disposeDialog()
- }
- }, 'turnrewind dialog runner')
- }
-
- Object.assign(exports, { apply, inject, parseUndoOutput, resolveOwnerSessionId, resolvePlanStatus })
- return module.exports
-}
-
-// Browser boot path: the DSH client module contract, unchanged.
-if (globalThis.__ModuleLoader__) {
- globalThis.__ModuleLoader__.load({
- id: 'dsh-tauri-turnrewind/client',
- factory: createTurnrewindClient,
- })
-}
-else {
- // Node/test path: no module loader exists here, so expose the factory
- // itself — pure helpers stay unit-testable without a browser.
- globalThis.__turnrewindClientFactory = createTurnrewindClient
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js b/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js
deleted file mode 100644
index 9e4217f4..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * The `turnrewind` session projection: folds the session log and surfaces the
- * unsupported-workspace heads-up messages this plugin injected, so the client
- * half can raise a dialog from the session list snapshot it already receives.
- * Pure and unit-tested; registration is the only effect in index.js.
- */
-
-export const UNSUPPORTED_MARKER = '[Turn rewind unavailable]'
-
-const MAX_TRACKED_NOTICES = 20
-
-/**
- * Extract the dialog payload from one committed session event.
- * Matches the injected message by plugin source first, falling back to the
- * text marker in case a host version drops the source field.
- */
-export function extractUnsupportedNotice(event) {
- if (event?.type !== 'user/message')
- return undefined
- const message = event.data
- const text = Array.isArray(message?.content)
- ? message.content.find(part => part?.type === 'text')?.text
- : undefined
- const source = message?.source
- const matched = (source?.plugin === 'dsh-tauri-turnrewind' && source?.form === 'undo-unavailable-notice')
- || (typeof text === 'string' && text.startsWith(UNSUPPORTED_MARKER))
- if (!matched || typeof message?.id !== 'string')
- return undefined
- const reason = typeof text === 'string' ? /^Reason: (.+)$/mu.exec(text)?.[1] : undefined
- return { id: message.id, reason: reason ?? '' }
-}
-
-function parseNoticesValue(value) {
- if (typeof value !== 'object' || value === null || !Array.isArray(value.notices))
- throw new Error('TURNREWIND_PROJECTION_SHAPE: expected { notices: Array<{ id, reason }> }')
- return value
-}
-
-/**
- * Build the `turnrewind` projection unit. Registered on
- * `ctx.sessionProjections`; the registry requires `.parse` validators (zod in
- * other plugins) — hand-rolled ones keep this plugin dependency-free.
- */
-export function createDialogProjection() {
- return {
- key: 'turnrewind',
- stateVersion: 1,
- stateSchema: { parse: parseNoticesValue },
- init: () => ({ notices: [] }),
- apply(state, event) {
- const notice = extractUnsupportedNotice(event)
- if (!notice || state.notices.some(existing => existing.id === notice.id))
- return state
- return { notices: [...state.notices, notice].slice(-MAX_TRACKED_NOTICES) }
- },
- wire: {
- viewSchema: { parse: parseNoticesValue },
- view: state => ({ notices: state.notices }),
- },
- }
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js b/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
deleted file mode 100644
index 98160b91..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-snapshot.js
+++ /dev/null
@@ -1,754 +0,0 @@
-import { Buffer } from 'node:buffer'
-import { spawn } from 'node:child_process'
-import { createHash, randomUUID } from 'node:crypto'
-import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join, relative, resolve, sep } from 'node:path'
-import process from 'node:process'
-import { TextDecoder, TextEncoder } from 'node:util'
-import { gitUnavailableReason, gitWorkspace } from './git-workspace.js'
-
-const MAX_FILE_BYTES = 64 * 1024 * 1024
-const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
-
-// OpenCode-style storage delegates ordinary ignore behavior to the source
-// repository. Only turnrewind-owned temporary files are excluded explicitly.
-const SNAPSHOT_PATHSPECS = [
- ':(exclude,glob).git/**',
- ':(exclude,glob)**/.git/**',
- ':(exclude,glob).turnrewind/**',
- ':(exclude,glob)**/.turnrewind/**',
- ':(exclude,glob)**/*.turnrewind-*.tmp',
- ':(exclude,glob)**/*.turnrewind-restore.bak',
-]
-const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'
-
-/**
- * Hard wall-clock budget per git subprocess. A wedged git (hung remote fs,
- * antivirus stall) would otherwise leave the async path pending forever and
- * the sync paths frozen; 5 minutes is far above any legitimate capture.
- */
-const GIT_SUBPROCESS_TIMEOUT_MS = 5 * 60 * 1000
-
-/**
- * Run one git command without blocking the host event loop. All snapshot I/O
- * used to be synchronous, which froze the whole host — every session, the web
- * UI and the health check — for the duration of `git add` on big workspaces.
- */
-export function runGit(repoDir, workspaceDir, args, extraEnv = {}, maxBytes = MAX_OUTPUT_BYTES) {
- 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, ...extraEnv },
- })
- const chunks = []
- const errors = []
- let total = 0
- let settled = false
- let timeout
- const fail = (error) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- child.kill('SIGKILL')
- rejectPromise(error)
- }
- // SIGKILL so a git stuck in uninterruptible I/O cannot outlive the budget.
- timeout = setTimeout(() => fail(new Error(`TURNREWIND_GIT_TIMEOUT: git ${args.join(' ')} exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`)), GIT_SUBPROCESS_TIMEOUT_MS)
- child.stdout.on('data', (chunk) => {
- if (settled)
- return
- total += chunk.length
- if (total > maxBytes) {
- fail(new Error(`TURNREWIND_OUTPUT_TOO_LARGE: git output exceeded ${maxBytes} bytes`))
- return
- }
- chunks.push(chunk)
- })
- child.stderr.on('data', (chunk) => {
- if (!settled)
- errors.push(chunk)
- })
- child.on('error', error => fail(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
- child.on('close', (code, signal) => {
- if (settled)
- return
- const stdout = Buffer.concat(chunks)
- // A clean exit is the only path that resolves (see gitExitIsClean).
- // Our own timeout kill already settled above, so anything unclean
- // here is an external kill with truncated output.
- if (!gitExitIsClean(code, signal)) {
- const detail = Buffer.concat(errors).toString('utf8').trim() || stdout.toString('utf8').trim() || (signal ? `killed by ${signal}` : `exit ${code}`)
- fail(new Error(`TURNREWIND_GIT_FAILED: ${detail}`))
- return
- }
- settled = true
- clearTimeout(timeout)
- resolvePromise(stdout)
- })
- })
-}
-
-/**
- * Pure verdict for a git subprocess exit: only a clean exit (code 0, no
- * signal) may resolve. code null or a signal means the process died
- * externally (OOM killer, taskkill, antivirus, host suspension) and any
- * buffered output is a truncated half-stream that must reject - resolving
- * would e.g. commit a half-finished 'git add' as the turn snapshot.
- */
-export function gitExitIsClean(code, signal) {
- // Node passes signal as null (and older versions may pass undefined) on
- // a clean exit; treat both as no-signal.
- const noSignal = signal === null || signal === undefined
- return code === 0 && noSignal
-}
-
-async function runGitText(repoDir, workspaceDir, args, extraEnv = {}) {
- const output = await runGit(repoDir, workspaceDir, args, extraEnv)
- return output.toString('utf8')
-}
-
-let gitProbeResult
-let gitProbeFailedAt = 0
-
-/** Re-probe a failed availability check after this long (git may be installed while the host runs). */
-const GIT_PROBE_RETRY_MS = 5 * 60 * 1000
-
-/** The availability probe feeds the pre-step barrier: a hung `git --version` must not park a turn forever. */
-const GIT_PROBE_TIMEOUT_MS = 30 * 1000
-
-/**
- * Whether a usable git executable is on PATH. Successful probes are cached for
- * the host process; failed probes expire after GIT_PROBE_RETRY_MS so a git
- * installed (or PATH fixed) mid-session is picked up without a host restart.
- */
-export function gitAvailable() {
- const failedRecently = gitProbeResult !== undefined && gitProbeFailedAt > 0 && Date.now() - gitProbeFailedAt > GIT_PROBE_RETRY_MS
- if (failedRecently) {
- gitProbeResult = undefined
- gitProbeFailedAt = 0
- }
- gitProbeResult ??= new Promise((resolvePromise) => {
- const child = spawn('git', ['--version'])
- let settled = false
- // The probe feeds the pre-step barrier: without a budget a hung
- // `git --version` would park the barrier forever. A timed-out or
- // externally-killed probe counts as unavailable (retried after TTL).
- let probeTimeout
- const settle = (value) => {
- if (settled)
- return undefined
- settled = true
- clearTimeout(probeTimeout)
- resolvePromise(value)
- }
- const markFailure = () => {
- gitProbeFailedAt = Date.now()
- }
- probeTimeout = setTimeout(() => {
- markFailure()
- child.kill('SIGKILL')
- settle(false)
- }, GIT_PROBE_TIMEOUT_MS)
- child.on('error', () => {
- markFailure()
- settle(false)
- })
- child.on('close', (code, signal) => {
- if (code !== 0 || signal !== null)
- markFailure()
- settle(code === 0 && signal === null)
- })
- })
- return gitProbeResult
-}
-
-async function ensureRepository(store) {
- const { repoDir, workspaceDir, sourceCommonDir, sourceInfoExclude } = store
- const source = gitWorkspace(workspaceDir)
- if (!source || source.gitDir !== store.sourceGitDir)
- throw new Error(`TURNREWIND_GIT_REPOSITORY: ${workspaceDir} is not the expected Git worktree`)
- if (!existsSync(join(repoDir, 'HEAD'))) {
- mkdirSync(dirname(repoDir), { recursive: true })
- await new Promise((resolvePromise, rejectPromise) => {
- const child = spawn('git', ['init', '--bare', repoDir])
- const errors = []
- let settled = false
- const timeout = setTimeout(() => {
- settled = true
- child.kill('SIGKILL')
- rejectPromise(new Error(`TURNREWIND_GIT_TIMEOUT: git init exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`))
- }, GIT_SUBPROCESS_TIMEOUT_MS)
- child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', (error) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- rejectPromise(new Error(`TURNREWIND_GIT_INIT: ${error.message}`))
- })
- child.on('close', (code, signal) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- if (!gitExitIsClean(code, signal)) {
- const detail = Buffer.concat(errors).toString('utf8').trim() || (signal ? `killed by ${signal}` : `exit ${code}`)
- const code1 = signal ? 'TURNREWIND_GIT_FAILED' : 'TURNREWIND_GIT_INIT'
- rejectPromise(new Error(`${code1}: ${detail}`))
- return
- }
- resolvePromise()
- })
- })
- await runGitText(repoDir, workspaceDir, ['config', 'core.autocrlf', 'false'])
- await runGitText(repoDir, workspaceDir, ['config', 'core.symlinks', 'true'])
- await runGitText(repoDir, workspaceDir, ['config', 'core.longpaths', 'true'])
-
- // Reuse committed source objects, as OpenCode does, while new snapshot
- // objects stay in this private repository. A healed store stays
- // self-contained: alternates are never written again, so source-side
- // gc/prune can no longer break snapshot chains for this workspace.
- if (store.selfContained !== true) {
- const sourceObjects = join(sourceCommonDir, 'objects')
- if (existsSync(sourceObjects)) {
- const alternates = join(repoDir, 'objects', 'info', 'alternates')
- mkdirSync(dirname(alternates), { recursive: true })
- writeFileSync(alternates, `${sourceObjects}\n`)
- }
- }
- }
- if (sourceInfoExclude && existsSync(sourceInfoExclude)) {
- const exclude = join(repoDir, 'info', 'exclude')
- mkdirSync(dirname(exclude), { recursive: true })
- writeFileSync(exclude, readFileSync(sourceInfoExclude))
- }
-}
-
-function normalizeSnapshotRef(ref) {
- if (typeof ref !== 'string' || !ref.startsWith(SNAPSHOT_REF_PREFIX) || ref.includes('..') || ref.includes('\\') || ref.includes('//'))
- throw new Error(`TURNREWIND_REF_UNSUPPORTED: ${String(ref)}`)
- return ref
-}
-
-async function gitRef(repoDir, workspaceDir, ref) {
- try {
- const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', normalizeSnapshotRef(ref)])
- return output.trim()
- }
- catch {
- return undefined
- }
-}
-
-function assertSafePath(workspaceDir, path) {
- const root = resolve(workspaceDir)
- const target = resolve(root, path)
- if (target !== root && !target.startsWith(`${root}${sep}`)) {
- throw new Error(`TURNREWIND_PATH_ESCAPE: ${path}`)
- }
-
- let current = root
- const suffix = relative(root, target)
- for (const part of suffix.split(sep).filter(Boolean)) {
- current = join(current, part)
- // lstatSync must be used without an existsSync pre-check: existsSync
- // returns false for dangling links, but a dangling link is still an unsafe
- // path component and must never be replaced or traversed.
- try {
- if (lstatSync(current).isSymbolicLink())
- throw new Error(`TURNREWIND_SYMLINK_UNSUPPORTED: ${path}`)
- }
- catch (error) {
- if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR')
- continue
- throw error
- }
- }
- return target
-}
-
-/**
- * Canonical workspace identity shared by the ledger key, the snapshot repo
- * hash and maintenance purges: case-folded only on case-insensitive platforms,
- * so Unix paths differing in case stay distinct while Windows paths unify.
- */
-export function workspaceKey(workspaceDir) {
- const normalized = resolve(workspaceDir)
- return process.platform === 'win32' ? normalized.toLowerCase() : normalized
-}
-
-export function workspaceHash(workspaceDir) {
- return createHash('sha256').update(workspaceKey(workspaceDir)).digest('hex').slice(0, 24)
-}
-
-/**
- * Create one OpenCode-style private snapshot repository per Git worktree.
- * The source Git directory is read-only metadata/object input; the snapshot
- * repository keeps its own refs and alternate capture index.
- */
-export function createSnapshotStore(rootDir, workspaceDir) {
- const source = gitWorkspace(workspaceDir)
- if (!source)
- throw new Error(gitUnavailableReason() ?? `TURNREWIND_GIT_REQUIRED: ${resolve(workspaceDir)} is not a Git worktree`)
- const normalizedWorkspace = source.workspaceDir
- const repoDir = join(rootDir, 'snapshots', `${workspaceHash(normalizedWorkspace)}.git`)
- return {
- repoDir,
- workspaceDir: normalizedWorkspace,
- sourceGitDir: source.gitDir,
- sourceCommonDir: source.commonDir,
- sourceIndexPath: source.indexPath,
- sourceInfoExclude: source.infoExcludePath,
- }
-}
-
-/**
- * Git mode deliberately avoids a second full filesystem budget walk. The
- * project's Git ignore rules determine the snapshot surface; restore keeps a
- * per-file size limit because snapshot contents still have to fit in memory.
- */
-export function probeWorkspace(workspaceDir) {
- const source = gitWorkspace(workspaceDir)
- if (!source)
- return { ok: false, reason: gitUnavailableReason() ?? 'TURNREWIND_GIT_REQUIRED: workspace is not a Git worktree' }
- return { ok: true, workspaceDir: source.workspaceDir, commonDir: source.commonDir }
-}
-
-/**
- * Capture a snapshot, then verify every referenced object is still readable
- * through the snapshot repository (including its alternates). The source
- * repository can prune exactly the unreachable objects we borrowed —
- * `git gc --prune=now` after an amend/rebase is the everyday case — so a
- * capture that reuses a parent chain may silently reference deleted blobs.
- * When that happens, rebuild the store as a self-contained repository (no
- * alternates, no source-index seeding) and take a fresh baseline: old turns
- * become dead snapshots the planner already skips, and future turns never
- * borrow again.
- */
-export async function captureSnapshot(store, refName, message, parentRef) {
- let snapshot = await captureInto(store, refName, message, parentRef)
- if (await snapshotHasMissingObjects(store, snapshot.commit)) {
- console.warn(`turnrewind: snapshot objects for ${store.workspaceDir} disappeared from the source repository (gc/prune); rebuilding a self-contained baseline`)
- rmSync(store.repoDir, { recursive: true, force: true })
- store.selfContained = true
- snapshot = await captureInto(store, refName, message, undefined)
- if (await snapshotHasMissingObjects(store, snapshot.commit))
- throw new Error(`TURNREWIND_SNAPSHOT_INCOMPLETE: ${store.workspaceDir} baseline still misses objects after a self-contained rebuild`)
- }
- return snapshot
-}
-
-/**
- * `git rev-list --objects --missing=print` walks every object reachable from
- * the commit (through alternates) and prints missing ones as `?<oid>` lines
- * while exiting 0, so detection stays non-fatal on healthy stores.
- */
-async function snapshotHasMissingObjects(store, commit) {
- try {
- const output = await runGit(store.repoDir, store.workspaceDir, ['rev-list', '--objects', '--missing=print', commit])
- return output.toString('utf8').split('\n').some(line => line.startsWith('?'))
- }
- catch (error) {
- // Detection must never take healthy snapshots down: an unusable probe
- // (very old git, transient failure) only skips the self-heal path.
- console.warn(`turnrewind: snapshot connectivity check failed for ${store.workspaceDir}: ${error.message}`)
- return false
- }
-}
-
-async function captureInto(store, refName, message, parentRef) {
- const { repoDir, workspaceDir, sourceIndexPath } = store
- await ensureRepository(store)
- 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(tmpdir(), `turnrewind-index-${randomUUID()}`)
- try {
- const env = { GIT_INDEX_FILE: indexPath }
- if (parent)
- await runGit(repoDir, workspaceDir, ['read-tree', parent], env)
- else if (store.selfContained !== true && existsSync(sourceIndexPath))
- copyFileSync(sourceIndexPath, indexPath)
- // Git reads .gitignore and global excludes from the source worktree while
- // GIT_INDEX_FILE isolates the snapshot from the user's real index.
- await runGit(repoDir, workspaceDir, ['add', '--all', '--', '.', ...SNAPSHOT_PATHSPECS], env)
- const tree = (await runGit(repoDir, workspaceDir, ['write-tree'], env)).toString('utf8').trim()
- const identity = {
- GIT_AUTHOR_NAME: 'DSH Turn Rewind',
- GIT_AUTHOR_EMAIL: 'turnrewind@localhost',
- GIT_COMMITTER_NAME: 'DSH Turn Rewind',
- GIT_COMMITTER_EMAIL: 'turnrewind@localhost',
- }
- const args = ['commit-tree', tree, '-m', message]
- if (parent)
- args.push('-p', parent)
- const commit = (await runGit(repoDir, workspaceDir, args, { ...env, ...identity })).toString('utf8').trim()
- const ref = normalizeSnapshotRef(refName)
- await runGit(repoDir, workspaceDir, ['update-ref', ref, commit])
- return { commit, refName: ref }
- }
- finally {
- rmSync(indexPath, { force: true })
- }
-}
-
-export async function snapshotDiff(store, beforeCommit, afterCommit) {
- const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '-z', '--no-renames', beforeCommit, afterCommit])
- return [...new Set(output.toString('utf8').split('\0').filter(Boolean))]
-}
-
-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 = []
- let settled = false
- let timeout
- const fail = (error) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- child.kill('SIGKILL')
- rejectPromise(error)
- }
- timeout = setTimeout(() => fail(new Error(`TURNREWIND_GIT_TIMEOUT: git ${args.join(' ')} exceeded ${GIT_SUBPROCESS_TIMEOUT_MS / 1000}s`)), GIT_SUBPROCESS_TIMEOUT_MS)
- child.stdout.on('data', chunk => chunks.push(chunk))
- child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', error => fail(new Error(`TURNREWIND_GIT_EXEC: ${error.message}`)))
- child.on('close', (code, signal) => {
- if (settled)
- return
- // Unclean exit = external kill with truncated output (see
- // gitExitIsClean); our own timeout settled above. Leave settled=false
- // here so fail() can reject the promise and guard the race.
- if (!gitExitIsClean(code, signal)) {
- fail(new Error(`TURNREWIND_GIT_FAILED: ${Buffer.concat(errors).toString('utf8').trim() || (signal ? `killed by ${signal}` : `exit ${code}`)}`))
- return
- }
- settled = true
- clearTimeout(timeout)
- 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 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' || before.kind === 'tooLarge') && after.kind === 'absent')
- return 'deleted'
- return 'modified'
-}
-
-/** Unified diff of one path between two snapshot commits, truncated to 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).
-async function ensureEmptyBlob(store) {
- if (!store.emptyBlob) {
- const output = await runGitStdin(store.repoDir, store.workspaceDir, ['hash-object', '-w', '--stdin'], '')
- store.emptyBlob = output.toString('utf8').trim()
- }
- return store.emptyBlob
-}
-
-async function blobFor(store, commit, path) {
- if (!await commitEntry(store, commit, path))
- return ensureEmptyBlob(store)
- const output = await runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`])
- return output.toString('utf8').trim()
-}
-
-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 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 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 = await runGit(store.repoDir, store.workspaceDir, [
- 'diff',
- '--no-renames',
- '--src-prefix=snapshot/',
- '--dst-prefix=disk/',
- from,
- to,
- ])
- return truncateDiff(output.toString('utf8'), maxLines)
-}
-
-async function commitEntry(store, commit, path) {
- const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '--name-only', '-z', commit, '--', path])
- return output.toString('utf8').split('\0').includes(path)
-}
-
-/**
- * Blob size of one committed path, or undefined when absent or unknown.
- * Reading only the size never materializes the blob, so an oversized entry can
- * be surfaced without blowing the output limit.
- */
-async function commitEntrySize(store, commit, path) {
- const output = await runGit(store.repoDir, store.workspaceDir, ['ls-tree', '-r', '-l', '-z', commit, '--', path])
- for (const line of output.toString('utf8').split('\0')) {
- // mode SP type SP oid TAB size SP path (size is '-' for submodules).
- const tab = line.lastIndexOf('\t')
- if (tab !== -1 && line.slice(tab + 1) === path) {
- const size = Number(line.slice(0, tab).split(' ').at(-1))
- return Number.isFinite(size) ? size : undefined
- }
- }
- return undefined
-}
-
-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 output
-}
-
-function digest(bytes) {
- let comparable = bytes
- try {
- const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
- comparable = new TextEncoder().encode(text.replaceAll('\r\n', '\n'))
- }
- catch {
- // Binary data has no newline normalization; compare its exact bytes.
- }
- return createHash('sha256').update(comparable).digest('hex')
-}
-
-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 }
- // Oversized blobs are reported instead of thrown: the caller can mark the
- // entry and continue, so one huge file never aborts a whole undo preview.
- if (await commitEntrySize(store, commit, path) > MAX_FILE_BYTES)
- return { kind: 'tooLarge', digest: null }
- const bytes = await commitBytes(store, commit, path)
- return { kind: 'file', digest: digest(bytes) }
-}
-
-export function currentState(workspaceDir, path) {
- const target = assertSafePath(workspaceDir, path)
- if (!existsSync(target))
- return { kind: 'absent', digest: null }
- const info = lstatSync(target)
- if (!info.isFile() || info.size > MAX_FILE_BYTES)
- return { kind: 'unsupported', digest: null }
- return { kind: 'file', digest: digest(readFileSync(target)) }
-}
-
-/**
- * Crash-safe restore window. The pre-atomic sequence was delete-then-rename:
- * a crash between those two steps left the target missing and its only copy
- * in a .tmp file nobody resurrected. The swap keeps a full copy on disk at
- * every instant:
- *
- * target -> target.turnrewind-restore.bak (rename, atomic)
- * temp -> target (rename, atomic)
- * bak -> deleted (only after success)
- *
- * A crash anywhere leaves either the new content or the .bak; the startup
- * sweep (restoreCrashedSwaps) resurrects a .bak whose target is missing.
- */
-const BAK_SUFFIX = '.turnrewind-restore.bak'
-
-/**
- * Remove one path, retrying briefly: Windows antivirus/indexers hold
- * short-lived handles on freshly written files, and a transient EPERM/EBUSY
- * on the .bak delete must not fail an otherwise successful restore.
- */
-function rmSyncWithRetry(target, attempts = 5) {
- for (let attempt = 0; ; attempt += 1) {
- try {
- rmSync(target, { force: true })
- return
- }
- catch (error) {
- const retryable = error?.code === 'EBUSY' || error?.code === 'EPERM' || error?.code === 'EACCES'
- if (retryable && attempt < attempts) {
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30)
- continue
- }
- throw error
- }
- }
-}
-
-export async function restorePath(store, commit, path) {
- const target = assertSafePath(store.workspaceDir, path)
- if (!await commitEntry(store, commit, path)) {
- if (existsSync(target)) {
- const info = lstatSync(target)
- if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)
- rmSync(target, { recursive: info.isDirectory(), force: true })
- }
- return { path, result: 'removed' }
- }
-
- // Restoring an oversized blob would require materializing it through the
- // same output-limited channel. Fail this one path with a stable code so the
- // undo loop can report it as not restored instead of dying mid-plan.
- if (await commitEntrySize(store, commit, path) > MAX_FILE_BYTES)
- throw new Error(`TURNREWIND_FILE_TOO_LARGE: ${path} (${MAX_FILE_BYTES}-byte limit) cannot be restored; add it to .gitignore or restore it manually`)
- const bytes = await commitBytes(store, commit, path)
- mkdirSync(dirname(target), { recursive: true })
- const temp = `${target}.turnrewind-${randomUUID()}.tmp`
- writeFileSync(temp, bytes, { flag: 'wx' })
- let bak
- try {
- if (existsSync(target)) {
- const info = lstatSync(target)
- if (info.isSymbolicLink() || !info.isFile())
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)
- // Move the old content aside instead of deleting it: the swap keeps a
- // complete copy on disk across both renames.
- bak = `${target}${BAK_SUFFIX}`
- rmSync(bak, { force: true })
- renameSync(target, bak)
- }
- try {
- renameSync(temp, target)
- }
- catch (error) {
- // The swap failed halfway: put the old content back before reporting.
- if (bak !== undefined) {
- try {
- if (!existsSync(target))
- renameSync(bak, target)
- else
- rmSync(bak, { force: true })
- }
- catch { /* best-effort self-heal; a leftover .bak stays recoverable */ }
- }
- throw error
- }
- // New content is in place; the old copy is now redundant. The delete is
- // retried: a transient antivirus handle on the fresh .bak must not turn
- // a completed restore into a reported failure (the sweep cleans a
- // leftover .bak anyway).
- if (bak !== undefined)
- rmSyncWithRetry(bak)
- }
- catch (error) {
- rmSync(temp, { force: true })
- throw new Error(`TURNREWIND_RESTORE_FAILED: ${path}: ${error.message}`)
- }
- return { path, result: 'restored' }
-}
-
-/**
- * Startup sweep for atomic-swap leftovers. A .turnrewind-restore.bak next to
- * a missing target means the process died between the two renames: resurrect
- * the old content. A .bak next to an existing target is debris from a crash
- * after the second rename (before the delete) - safe to remove. Returns the
- * resurrected workspace-relative paths for logging.
- */
-export function restoreCrashedSwaps(workspaceDir) {
- const root = resolve(workspaceDir)
- const resurrected = []
- const visit = (dir) => {
- let entries
- try {
- entries = readdirSync(dir, { withFileTypes: true })
- }
- catch {
- return
- }
- for (const entry of entries) {
- const full = join(dir, entry.name)
- if (entry.isDirectory() && entry.name !== '.git' && !entry.name.endsWith('.turnrewind-restore.bak'))
- visit(full)
- if (entry.isFile() && entry.name.endsWith('.turnrewind-restore.bak')) {
- const target = full.slice(0, -BAK_SUFFIX.length)
- // Windows antivirus/indexers hold brief handles on freshly renamed
- // files; retry a few times before giving this bak up to the fence.
- for (let attempt = 0; ; attempt += 1) {
- try {
- if (!existsSync(target)) {
- renameSync(full, target)
- resurrected.push(relative(root, target))
- }
- else {
- rmSync(full, { force: true })
- }
- break
- }
- catch (error) {
- const retryable = error?.code === 'EBUSY' || error?.code === 'EPERM' || error?.code === 'EACCES'
- if (retryable && attempt < 5) {
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30)
- continue
- }
- break // deeper damage: leave for the recovery fence
- }
- }
- }
- }
- }
- visit(root)
- return resurrected
-}
-
-export function pathIsSafe(workspaceDir, path) {
- try {
- assertSafePath(workspaceDir, path)
- return true
- }
- catch {
- return false
- }
-}
-
-export { gitRef, MAX_FILE_BYTES }
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js b/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
deleted file mode 100644
index 7b92e161..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/git-workspace.js
+++ /dev/null
@@ -1,79 +0,0 @@
-import { spawnSync } from 'node:child_process'
-import { existsSync } from 'node:fs'
-import { resolve } from 'node:path'
-import process from 'node:process'
-
-const MAX_OUTPUT_BYTES = 1024 * 1024
-// spawnSync blocks the event loop; a hard timeout keeps a wedged git from
-// freezing the host forever. These are local metadata rev-parse calls only,
-// so 15s is already generous - a workload slow enough to hit it is wedged,
-// not busy (the heavy async captures keep their own 5-minute budget).
-const SYNC_GIT_TIMEOUT_MS = 15 * 1000
-
-function runGitSync(workspaceDir, args) {
- const result = spawnSync('git', ['-c', 'core.quotepath=false', ...args], {
- cwd: workspaceDir,
- env: { ...process.env },
- encoding: 'utf8',
- maxBuffer: MAX_OUTPUT_BYTES,
- timeout: SYNC_GIT_TIMEOUT_MS,
- killSignal: 'SIGKILL',
- })
- if (result.error)
- return { ok: false, error: result.error }
- if (result.status !== 0)
- return { ok: false, stderr: String(result.stderr ?? '').trim(), status: result.status }
- return { ok: true, stdout: String(result.stdout ?? '').trim() }
-}
-
-/**
- * Resolve the canonical Git worktree and its metadata without changing Git
- * state. The caller can use this to require a project Git boundary and to
- * reuse Git objects/ignore behavior without touching the user's index.
- *
- * Returns undefined when the directory is not a Git worktree. A missing git
- * executable (ENOENT on spawn) is distinguished by the module-level
- * `gitExecutableMissing` flag: `gitUnavailableReason()` exposes it so callers
- * report TURNREWIND_GIT_UNAVAILABLE instead of the misleading "not a Git
- * worktree" message.
- */
-let gitExecutableMissing = false
-
-export function gitUnavailableReason() {
- return gitExecutableMissing
- ? 'TURNREWIND_GIT_UNAVAILABLE: the git executable was not found on PATH; file undo is disabled'
- : undefined
-}
-
-export function gitWorkspace(workspaceDir) {
- const requestedDir = resolve(workspaceDir)
- gitExecutableMissing = false
- const inside = runGitSync(requestedDir, ['rev-parse', '--is-inside-work-tree'])
- if (inside.error?.code === 'ENOENT') {
- gitExecutableMissing = true
- return undefined
- }
- const top = runGitSync(requestedDir, ['rev-parse', '--show-toplevel'])
- const gitDir = runGitSync(requestedDir, ['rev-parse', '--git-dir'])
- const commonDir = runGitSync(requestedDir, ['rev-parse', '--git-common-dir'])
- const index = runGitSync(requestedDir, ['rev-parse', '--git-path', 'index'])
- const infoExclude = runGitSync(requestedDir, ['rev-parse', '--git-path', 'info/exclude'])
- if (!inside.ok || inside.stdout !== 'true' || !top.ok || !gitDir.ok || !commonDir.ok || !index.ok)
- return undefined
-
- const workspaceRoot = resolve(requestedDir, top.stdout)
- const resolvedGitDir = resolve(requestedDir, gitDir.stdout)
- const resolvedCommonDir = resolve(requestedDir, commonDir.stdout)
- const resolvedIndex = resolve(requestedDir, index.stdout)
- if (!existsSync(workspaceRoot) || !existsSync(resolvedGitDir) || !existsSync(resolvedCommonDir))
- return undefined
-
- return {
- workspaceDir: workspaceRoot,
- requestedDir,
- gitDir: resolvedGitDir,
- commonDir: resolvedCommonDir,
- indexPath: resolvedIndex,
- infoExcludePath: infoExclude.ok ? resolve(requestedDir, infoExclude.stdout) : undefined,
- }
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/guard.js b/plugins/dsh-tauri-turnrewind/lib/core/guard.js
deleted file mode 100644
index 363143db..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/guard.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import { realpathSync } from 'node:fs'
-import { homedir } from 'node:os'
-import { parse, resolve, sep } from 'node:path'
-import process from 'node:process'
-
-function normalizeDir(path) {
- const resolved = resolve(path)
- try {
- return realpathSync(resolved)
- }
- catch {
- // Missing or unreadable paths still need a deterministic comparison key.
- return resolved
- }
-}
-
-function foldCase(path) {
- return process.platform === 'win32' ? path.toLowerCase() : path
-}
-
-export function isSystemSensitiveWorkspace(workspaceDir) {
- const workspace = foldCase(normalizeDir(workspaceDir))
- const home = foldCase(normalizeDir(homedir()))
- if (workspace === home)
- return true
- // An ancestor of the home directory would snapshot every user profile
- // including the DSH data dir itself, so refuse it alongside the home dir.
- if (home.startsWith(`${workspace}${sep}`))
- return true
- return parse(workspace).root === workspace
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
deleted file mode 100644
index d892dc77..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ /dev/null
@@ -1,491 +0,0 @@
-import { randomUUID } from 'node:crypto'
-import { mkdirSync } from 'node:fs'
-import { dirname, join } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-
-const SCHEMA = `
- PRAGMA journal_mode = WAL;
- CREATE TABLE IF NOT EXISTS workspaces (
- workspace_key TEXT PRIMARY KEY,
- workspace_path TEXT NOT NULL,
- snapshot_repo TEXT NOT NULL,
- created_at TEXT NOT NULL
- );
- CREATE TABLE IF NOT EXISTS turns (
- turn_id TEXT PRIMARY KEY,
- session_id TEXT NOT NULL,
- parent_turn_id TEXT,
- workspace_key TEXT NOT NULL,
- status TEXT NOT NULL,
- started_at TEXT NOT NULL,
- settled_at TEXT,
- before_ref TEXT,
- after_ref TEXT,
- reversible INTEGER NOT NULL DEFAULT 0,
- error TEXT
- );
- CREATE INDEX IF NOT EXISTS turns_session_idx ON turns(session_id, started_at);
- CREATE INDEX IF NOT EXISTS turns_parent_idx ON turns(parent_turn_id);
- CREATE TABLE IF NOT EXISTS operations (
- operation_id TEXT PRIMARY KEY,
- kind TEXT NOT NULL,
- target_turn_id TEXT NOT NULL,
- requested_at TEXT NOT NULL,
- settled_at TEXT,
- outcome TEXT NOT NULL,
- before_ref TEXT,
- after_ref TEXT,
- error TEXT
- );
- CREATE TABLE IF NOT EXISTS rewind_notices (
- notice_id TEXT PRIMARY KEY,
- session_id TEXT NOT NULL,
- workspace_key TEXT NOT NULL,
- target_turn_id TEXT NOT NULL,
- turns_json TEXT NOT NULL DEFAULT '[]',
- paths_json TEXT NOT NULL,
- kind TEXT NOT NULL DEFAULT 'rewind',
- reason TEXT,
- status TEXT NOT NULL,
- created_at TEXT NOT NULL,
- claimed_at TEXT
- );
- CREATE INDEX IF NOT EXISTS rewind_notices_session_idx ON rewind_notices(session_id, status, created_at);
- CREATE TABLE IF NOT EXISTS pending_plans (
- plan_id TEXT PRIMARY KEY,
- session_id TEXT NOT NULL,
- workspace_key TEXT NOT NULL,
- turn_id TEXT NOT NULL,
- paths_json TEXT NOT NULL,
- status TEXT NOT NULL DEFAULT 'pending',
- result_text TEXT,
- created_at TEXT NOT NULL,
- expires_at TEXT NOT NULL
- );
-`
-
-export function openLedger(rootDir) {
- const path = join(rootDir, 'ledger.sqlite')
- mkdirSync(dirname(path), { recursive: true })
- const db = new DatabaseSync(path)
- db.exec(SCHEMA)
- // Older local prototypes may already have the table; add the new recovery column idempotently.
- try {
- db.exec('ALTER TABLE operations ADD COLUMN after_ref TEXT')
- }
- catch {
- // Column already exists.
- }
- try {
- db.exec('ALTER TABLE rewind_notices ADD COLUMN turns_json TEXT NOT NULL DEFAULT \'[]\'')
- }
- catch {
- // Column already exists.
- }
- try {
- db.exec('ALTER TABLE rewind_notices ADD COLUMN kind TEXT NOT NULL DEFAULT \'rewind\'')
- }
- catch {
- // Column already exists.
- }
- try {
- db.exec('ALTER TABLE rewind_notices ADD COLUMN reason TEXT')
- }
- catch {
- // Column already exists.
- }
- try {
- db.exec('ALTER TABLE pending_plans ADD COLUMN status TEXT NOT NULL DEFAULT \'pending\'')
- }
- catch {
- // Column already exists.
- }
- try {
- db.exec('ALTER TABLE pending_plans ADD COLUMN result_text TEXT')
- }
- catch {
- // Column already exists.
- }
- db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)
- db.prepare(`UPDATE operations SET outcome = 'needs-recovery', settled_at = COALESCE(settled_at, ?), error = 'plugin restarted while the operation was applying; workspace recovery is required' WHERE outcome = 'applying'`).run(new Date().toISOString())
- purgeExpiredPendingPlans(db)
- return db
-}
-
-// ------------------------------------------------------------------
-// Pending undo plans: /undo parks a confirmed-ready plan here; the client's
-// ✓ button runs `/undo --confirm <plan-id>` to execute it. Rows expire so an
-// ignored preview can never apply hours later against a changed workspace.
-// ------------------------------------------------------------------
-const PENDING_PLAN_TTL_MS = 5 * 60 * 1000
-const PENDING_PLAN_RESULT_TTL_MS = 30 * 60 * 1000
-
-export function purgeExpiredPendingPlans(db) {
- const now = new Date().toISOString()
- // Unacted plans die at their 5-minute mark; settled plans linger for the
- // client card to poll their outcome, then get cleaned up too.
- db.prepare('DELETE FROM pending_plans WHERE status = \'pending\' AND expires_at < ?').run(now)
- db.prepare('DELETE FROM pending_plans WHERE status <> \'pending\' AND created_at < ?').run(new Date(Date.now() - PENDING_PLAN_RESULT_TTL_MS).toISOString())
-}
-
-export function createPendingPlan(db, plan) {
- db.exec('BEGIN')
- try {
- // One live plan per session+workspace: a newer preview replaces the older.
- db.prepare('DELETE FROM pending_plans WHERE session_id = ? AND workspace_key = ?')
- .run(plan.sessionId, plan.workspaceKey)
- const planId = randomUUID()
- const createdAt = new Date().toISOString()
- db.prepare(`
- INSERT INTO pending_plans(plan_id, session_id, workspace_key, turn_id, paths_json, created_at, expires_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- `).run(planId, plan.sessionId, plan.workspaceKey, plan.turnId, JSON.stringify(plan.paths), createdAt, new Date(Date.now() + PENDING_PLAN_TTL_MS).toISOString())
- db.exec('COMMIT')
- return planId
- }
- catch (error) {
- db.exec('ROLLBACK')
- throw error
- }
-}
-
-/**
- * Atomically move one pending plan to `applying` so concurrent confirm/cancel
- * calls cannot interleave: the conditional UPDATE is serialized by SQLite, so
- * exactly one caller sees changes === 1 and everyone else gets a deterministic
- * failure. The pre-reads only pick a precise error code; the UPDATE decides.
- */
-export function claimPendingPlan(db, planId, sessionId) {
- const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId)
- if (row === undefined)
- return { ok: false, code: 404, error: 'plan expired or already applied — run /undo again' }
- if (row.session_id !== sessionId)
- return { ok: false, code: 403, error: 'the plan belongs to another session' }
- if (row.status !== 'pending')
- return { ok: false, code: 409, error: 'this plan was already applied, cancelled, or is being applied — run /undo again' }
- if (row.expires_at < new Date().toISOString()) {
- db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
- return { ok: false, code: 404, error: 'plan expired or already applied — run /undo again' }
- }
- const claimed = db.prepare(`
- UPDATE pending_plans SET status = 'applying'
- WHERE plan_id = ? AND session_id = ? AND status = 'pending'
- `).run(planId, sessionId)
- if (claimed.changes !== 1)
- return { ok: false, code: 409, error: 'this plan was already applied, cancelled, or is being applied — run /undo again' }
- return { ok: true, row: { ...row, paths: JSON.parse(row.paths_json) } }
-}
-
-/** Return an in-flight claim to `pending` after a failed confirm attempt. */
-export function releasePendingPlanClaim(db, planId) {
- db.prepare(`
- UPDATE pending_plans SET status = 'pending'
- WHERE plan_id = ? AND status = 'applying'
- `).run(planId)
-}
-
-/**
- * Plan lookup for the confirm HTTP route: keyed by plan id only — the client
- * does not know the workspace key, the row itself carries it (and the owner
- * session, which the route re-checks against the caller).
- */
-export function getPendingPlanRow(db, planId) {
- const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId)
- if (row === undefined)
- return undefined
- if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
- db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
- return undefined
- }
- return { ...row, paths: JSON.parse(row.paths_json) }
-}
-
-/** Dismissal from the ✕ button: workspace key is unknown client-side. */
-export function markPendingPlanCancelled(db, planId, sessionId) {
- const result = db.prepare(`
- UPDATE pending_plans SET status = 'cancelled'
- WHERE plan_id = ? AND session_id = ? AND status = 'pending'
- `).run(planId, sessionId)
- return result.changes > 0
-}
-
-/** Outcome written by the confirm route so the client card can poll it. Only a claimed (`applying`) plan can be applied. */
-export function markPendingPlanApplied(db, planId, sessionId, message) {
- db.prepare(`
- UPDATE pending_plans SET status = 'applied', result_text = ?
- WHERE plan_id = ? AND session_id = ? AND status = 'applying'
- `).run(message, planId, sessionId)
-}
-
-/** Poll face for the client card: undefined once purged, else the outcome. */
-export function getPendingPlanStatus(db, planId, sessionId) {
- const row = db.prepare('SELECT status, result_text, expires_at FROM pending_plans WHERE plan_id = ? AND session_id = ?').get(planId, sessionId)
- if (row === undefined)
- return undefined
- if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
- db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)
- return undefined
- }
- return { status: row.status, resultText: row.result_text }
-}
-
-export function registerWorkspace(db, workspaceKey, workspacePath, snapshotRepo) {
- db.prepare(`
- INSERT INTO workspaces(workspace_key, workspace_path, snapshot_repo, created_at)
- VALUES (?, ?, ?, ?)
- ON CONFLICT(workspace_key) DO UPDATE SET workspace_path = excluded.workspace_path, snapshot_repo = excluded.snapshot_repo
- `).run(workspaceKey, workspacePath, snapshotRepo, new Date().toISOString())
-}
-
-export function insertTurn(db, turn) {
- db.prepare(`
- INSERT INTO turns(turn_id, session_id, parent_turn_id, workspace_key, status, started_at, before_ref, reversible)
- VALUES (?, ?, ?, ?, 'active', ?, ?, 1)
- `).run(turn.turnId, turn.sessionId, turn.parentTurnId ?? null, turn.workspaceKey, turn.startedAt, turn.beforeRef)
-}
-
-export function settleTurn(db, turnId, afterRef) {
- db.prepare(`UPDATE turns SET status = 'settled', settled_at = ?, after_ref = ?, reversible = 1 WHERE turn_id = ?`)
- .run(new Date().toISOString(), afterRef, turnId)
-}
-
-export function settleInterruptedTurn(db, turnId, afterRef, reason) {
- db.prepare(`UPDATE turns SET status = 'interrupted', settled_at = ?, after_ref = ?, reversible = 1, error = ? WHERE turn_id = ?`)
- .run(new Date().toISOString(), afterRef, reason, turnId)
-}
-
-export function settleNoopTurn(db, turnId, afterRef) {
- db.prepare(`UPDATE turns SET status = 'settled', settled_at = ?, after_ref = ?, reversible = 0, error = ? WHERE turn_id = ?`)
- .run(new Date().toISOString(), afterRef, 'no file changes', turnId)
-}
-
-export function skipTurn(db, turn, reason) {
- db.prepare(`
- INSERT OR REPLACE INTO turns(turn_id, session_id, parent_turn_id, workspace_key, status, started_at, reversible, error)
- VALUES (?, ?, NULL, ?, 'skipped', ?, 0, ?)
- `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, reason)
-}
-
-export function listReversibleTurns(db, sessionId, workspaceKey) {
- return db.prepare(`
- SELECT * FROM turns
- WHERE session_id = ? AND workspace_key = ?
- AND reversible = 1
- AND status IN ('settled', 'interrupted')
- ORDER BY started_at DESC
- `).all(sessionId, workspaceKey)
-}
-
-export function markTurnSnapshotMissing(db, turnId) {
- db.prepare(`
- UPDATE turns SET reversible = 0, error = 'snapshot ref missing (snapshot repository was wiped)'
- WHERE turn_id = ?
- `).run(turnId)
-}
-
-export function recordSkippedTurn(db, turn, reason) {
- db.exec('BEGIN')
- try {
- skipTurn(db, turn, reason)
- // Queue one heads-up per session and workspace; repeated skips stay silent.
- const existing = db.prepare(`
- SELECT 1 FROM rewind_notices WHERE session_id = ? AND workspace_key = ? AND kind = 'unsupported' LIMIT 1
- `).get(turn.sessionId, turn.workspaceKey)
- if (!existing) {
- db.prepare(`
- INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, reason, status, created_at)
- VALUES (?, ?, ?, 'workspace-unsupported', '[]', '[]', 'unsupported', ?, 'pending', ?)
- `).run(randomUUID(), turn.sessionId, turn.workspaceKey, reason, new Date().toISOString())
- }
- db.exec('COMMIT')
- }
- catch (error) {
- db.exec('ROLLBACK')
- throw error
- }
-}
-
-export function failTurn(db, turnId, error) {
- db.prepare(`UPDATE turns SET status = 'failed', settled_at = ?, reversible = 0, error = ? WHERE turn_id = ?`)
- .run(new Date().toISOString(), String(error), turnId)
-}
-
-export function abandonTurn(db, turnId, reason) {
- db.prepare(`
- UPDATE turns SET status = 'abandoned', settled_at = ?, reversible = 0, error = ?
- WHERE turn_id = ? AND status = 'active'
- `).run(new Date().toISOString(), reason, turnId)
-}
-
-export function getTurn(db, turnId) {
- return db.prepare('SELECT * FROM turns WHERE turn_id = ?').get(turnId)
-}
-
-export function getLatestTurn(db, sessionId, workspaceKey) {
- return db.prepare(`
- SELECT * FROM turns
- WHERE session_id = ? AND workspace_key = ?
- AND reversible = 1
- AND status IN ('settled', 'interrupted')
- ORDER BY started_at DESC LIMIT 1
- `).get(sessionId, workspaceKey)
-}
-
-export function getLatestTurnSummary(db, sessionId) {
- return db.prepare(`
- SELECT turn_id, workspace_key, status, reversible, settled_at
- FROM turns WHERE session_id = ? ORDER BY started_at DESC LIMIT 1
- `).get(sessionId)
-}
-
-export function getLatestSnapshotRef(db, workspaceKey) {
- return db.prepare(`
- SELECT after_ref FROM turns
- WHERE workspace_key = ? AND after_ref IS NOT NULL
- ORDER BY settled_at DESC LIMIT 1
- `).get(workspaceKey)?.after_ref
-}
-
-export function listChildren(db, parentTurnId) {
- return db.prepare(`SELECT * FROM turns WHERE parent_turn_id = ? ORDER BY started_at ASC`).all(parentTurnId)
-}
-
-export function createOperation(db, operation) {
- db.prepare(`
- INSERT INTO operations(operation_id, kind, target_turn_id, requested_at, outcome, before_ref)
- VALUES (?, ?, ?, ?, 'applying', ?)
- `).run(operation.operationId, operation.kind, operation.targetTurnId, operation.requestedAt, operation.beforeRef ?? null)
-}
-
-export function settleOperation(db, operationId, outcome, error) {
- db.prepare(`UPDATE operations SET settled_at = ?, outcome = ?, error = ? WHERE operation_id = ?`)
- .run(new Date().toISOString(), outcome, error ? String(error) : null, operationId)
-}
-
-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, 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',
- )
-}
-
-export function claimRewindNotices(db, sessionId, workspaceKey) {
- const notices = db.prepare(`
- SELECT * FROM rewind_notices
- WHERE session_id = ? AND workspace_key = ? AND status = 'pending'
- ORDER BY created_at ASC
- `).all(sessionId, workspaceKey)
- if (notices.length === 0)
- return []
- const claimedAt = new Date().toISOString()
- const statement = db.prepare(`
- UPDATE rewind_notices SET status = 'consumed', claimed_at = ?
- WHERE notice_id = ? AND status = 'pending'
- `)
- db.exec('BEGIN')
- try {
- for (const notice of notices) statement.run(claimedAt, notice.notice_id)
- db.exec('COMMIT')
- }
- catch (error) {
- db.exec('ROLLBACK')
- throw error
- }
- return notices.map(notice => ({
- ...notice,
- turns: JSON.parse(notice.turns_json || '[]'),
- paths: JSON.parse(notice.paths_json),
- }))
-}
-
-export function listNeedsRecoveryWorkspaces(db) {
- return db.prepare(`
- SELECT DISTINCT t.workspace_key
- FROM operations o
- JOIN turns t ON t.turn_id = o.target_turn_id
- WHERE o.outcome = 'needs-recovery'
- `).all().map(row => row.workspace_key)
-}
-
-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, 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,
- notice.workspaceKey,
- notice.targetTurnId,
- JSON.stringify([notice.targetTurnId]),
- JSON.stringify(notice.paths),
- notice.createdAt,
- )
- db.exec('COMMIT')
- }
- catch (error) {
- db.exec('ROLLBACK')
- throw error
- }
-}
-
-/**
- * Delete long-consumed notice rows. Consumed rows keep two jobs — the
- * unsupported-heads-up dedup (one dialog per session+workspace) and audit —
- * so they are pruned by age instead of on claim: 7 days is far beyond any
- * session's lifetime while keeping the ledger from growing without bound.
- */
-export function pruneConsumedNotices(db, maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
- const cutoff = new Date(Date.now() - maxAgeMs).toISOString()
- return db.prepare(`DELETE FROM rewind_notices WHERE status = 'consumed' AND claimed_at < ?`).run(cutoff).changes
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js b/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
deleted file mode 100644
index d6542d89..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
+++ /dev/null
@@ -1,52 +0,0 @@
-import { existsSync, rmSync } from 'node:fs'
-import { homedir } from 'node:os'
-import { join, resolve } from 'node:path'
-import process from 'node:process'
-import { workspaceHash, workspaceKey } from './git-snapshot.js'
-import { openLedger } from './ledger.js'
-
-export function resolveRootDir(explicit) {
- if (explicit)
- return resolve(explicit)
- return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
-}
-
-/**
- * Remove every piece of turnrewind data bound to one workspace: the private
- * snapshot repository on disk and all ledger rows that reference it. Used to
- * recover from workspaces that were snapshotted before the eligibility guard
- * existed (for example a 250 GB home directory).
- */
-export function purgeWorkspace(rootDir, workspaceDir) {
- const workspaceIdentity = workspaceKey(workspaceDir)
- const repoDir = join(rootDir, 'snapshots', `${workspaceHash(workspaceDir)}.git`)
- const summary = { rootDir, repoDir, repoExisted: false, ledger: undefined }
-
- const ledgerPath = join(rootDir, 'ledger.sqlite')
- if (existsSync(ledgerPath)) {
- const db = openLedger(rootDir)
- try {
- db.exec('BEGIN')
- const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceIdentity)
- const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceIdentity)
- const plans = db.prepare('DELETE FROM pending_plans WHERE workspace_key = ?').run(workspaceIdentity)
- const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceIdentity)
- const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceIdentity)
- db.exec('COMMIT')
- summary.ledger = {
- operations: operations.changes,
- notices: notices.changes,
- plans: plans.changes,
- turns: turns.changes,
- workspaces: workspaces.changes,
- }
- }
- finally {
- db.close()
- }
- }
-
- summary.repoExisted = existsSync(repoDir)
- rmSync(repoDir, { recursive: true, force: true })
- return summary
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/planner.js b/plugins/dsh-tauri-turnrewind/lib/core/planner.js
deleted file mode 100644
index 62de63fb..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/core/planner.js
+++ /dev/null
@@ -1,36 +0,0 @@
-export function collectDescendantTurns(turn, childrenByParent) {
- const result = []
- const visit = (current) => {
- for (const child of childrenByParent.get(current.turn_id) ?? []) {
- visit(child)
- result.push(child)
- }
- }
- visit(turn)
- result.push(turn)
- return result
-}
-
-export function aggregatePathPlan(turns, pathReader) {
- const byPath = new Map()
- for (const turn of turns) {
- for (const path of pathReader(turn)) {
- const current = byPath.get(path)
- if (!current) {
- byPath.set(path, { path, firstTurn: turn.turn_id, lastTurn: turn.turn_id })
- }
- else {
- current.lastTurn = turn.turn_id
- }
- }
- }
- return [...byPath.values()]
-}
-
-export function classifyUndo(currentState, expectedState) {
- if (currentState.kind !== expectedState.kind)
- return 'conflict'
- if (currentState.digest !== expectedState.digest)
- return 'conflict'
- return 'safe'
-}
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
deleted file mode 100644
index 0a8ed794..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ /dev/null
@@ -1,1177 +0,0 @@
-import { Buffer } from 'node:buffer'
-import { createHash, randomUUID } from 'node:crypto'
-import { homedir } from 'node:os'
-import { join, resolve } from 'node:path'
-import process from 'node:process'
-import { createDialogProjection } from './core/dialog-projection.js'
-import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, MAX_FILE_BYTES, probeWorkspace, restoreCrashedSwaps, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceKey } from './core/git-snapshot.js'
-import { isSystemSensitiveWorkspace } from './core/guard.js'
-import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, recordSkippedTurn, registerWorkspace, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'
-import { classifyUndo } from './core/planner.js'
-
-const name = 'dsh-tauri-turnrewind'
-const inject = ['commands', 'sessionProjections', 'webServer']
-function rootDir() {
- return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
-}
-
-export function turnSnapshotRef(turnId, phase) {
- const digest = createHash('sha256').update(turnId).digest('hex').slice(0, 32)
- return `refs/turnrewind/turn-${digest}-${phase}`
-}
-
-function refSuffix(turnId, phase) {
- return turnSnapshotRef(turnId, phase)
-}
-
-function workspaceForAgent(agent) {
- return workspaceForSession(agent?.session)
-}
-
-function workspaceForSession(session) {
- const cwd = session?.header?.cwd
- if (typeof cwd !== 'string' || cwd.length === 0)
- return undefined
- const resolved = resolve(cwd)
- if (isSystemSensitiveWorkspace(resolved))
- return undefined
- const probe = probeWorkspace(resolved)
- return probe.ok ? probe.workspaceDir : undefined
-}
-
-function workspaceKeyFor(path) {
- return workspaceKey(path)
-}
-
-function workspaceIssue(workspaceDir) {
- if (isSystemSensitiveWorkspace(workspaceDir))
- return `TURNREWIND_WORKSPACE_UNSUPPORTED: ${workspaceDir} is a system directory`
- const probe = probeWorkspace(workspaceDir)
- return probe.ok ? undefined : probe.reason
-}
-
-function activeKey(sessionId, turn) {
- return `${sessionId}:${turn}`
-}
-
-function createDeferred() {
- let resolvePromise
- const promise = new Promise((resolveValue) => {
- resolvePromise = resolveValue
- })
- return { promise, resolve: resolvePromise, settled: false }
-}
-
-function settleDeferred(deferred, value) {
- if (deferred.settled)
- return
- deferred.settled = true
- deferred.resolve(value)
-}
-
-export async function waitForTurnBaseline(activeTurns, sessionId, turn, signal) {
- const entry = activeTurns.get(activeKey(sessionId, turn))
- if (!entry?.baseline)
- return undefined
- if (!signal)
- return entry.baseline.promise
- signal.throwIfAborted()
- let removeAbortListener
- const aborted = new Promise((resolvePromise) => {
- const onAbort = () => resolvePromise({ kind: 'aborted' })
- signal.addEventListener('abort', onAbort, { once: true })
- removeAbortListener = () => signal.removeEventListener('abort', onAbort)
- })
- try {
- const result = await Promise.race([
- entry.baseline.promise.then(value => ({ kind: 'baseline', value })),
- aborted,
- ])
- if (result.kind === 'aborted') {
- signal.throwIfAborted()
- return undefined
- }
- return result.value
- }
- finally {
- removeAbortListener?.()
- }
-}
-
-function parseUndoInput(rawInput) {
- const parts = rawInput.trim().split(/\s+/u).filter(Boolean)
- let turnId
- let dryRun = false
- let preview = false
- let skipConflicts = false
- let force = false
- let redo = false
- let confirm = false
- let cancel = false
- for (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 === '--confirm') {
- confirm = true
- }
- else if (part === '--cancel') {
- cancel = true
- }
- else if (part === '--subtree') {
- return { error: 'Recursive subtree undo is not available in the MVP.' }
- }
- else if (turnId === undefined) {
- turnId = part
- }
- else {
- return { error: 'Usage: /undo [--preview] | /undo --confirm <plan-id> | /undo --cancel <plan-id> | /undo <turn-id> --force' }
- }
- }
- if (skipConflicts && force)
- return { error: '--skip-conflicts and --force are mutually exclusive.' }
- if (redo && (turnId !== undefined || dryRun || preview || skipConflicts || force || confirm || cancel))
- return { error: '--redo cannot be combined with a turn id or other options.' }
- if ((confirm || cancel) && (dryRun || preview || skipConflicts || force))
- return { error: '--confirm/--cancel cannot be combined with preview or conflict-override flags.' }
- if (confirm && cancel)
- return { error: '--confirm and --cancel are mutually exclusive.' }
- if ((confirm || cancel) && turnId === undefined)
- return { error: confirm ? 'Usage: /undo --confirm <plan-id>' : 'Usage: /undo --cancel <plan-id>' }
- return { turnId, dryRun, preview, skipConflicts, force, redo, confirm, cancel }
-}
-
-function assertSessionOwner(target, agent) {
- if (target.session_id !== agent.session.id) {
- return { kind: 'error', text: 'The selected turn belongs to another session.' }
- }
- return undefined
-}
-
-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. */
-async function safeDiffAgainstDisk(store, ref, path) {
- try {
- 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. */
-async function diskMatchesSnapshot(runtime, workspaceDir, ref, path) {
- try {
- 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), whether the current on-disk state still matches
- * the turn's after snapshot, and whether the before-snapshot blob exceeds the
- * restore limit (oversized entries restore as failures, never silently).
- */
-async function buildPlanEntries(runtime, workspaceDir, target, paths) {
- return Promise.all(paths.map(async (path) => {
- const beforeState = await stateAt(runtime.store, target.before_ref, path)
- return {
- path,
- change: await classifyPathChange(runtime.store, target.before_ref, target.after_ref, path),
- conflict: !await diskMatchesSnapshot(runtime, workspaceDir, target.after_ref, path),
- tooLarge: beforeState.kind === 'tooLarge',
- }
- }))
-}
-
-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}`
-}
-
-async function formatPlan(runtime, target, entries, options) {
- const conflicts = entries.filter(entry => entry.conflict)
- const oversized = entries.filter(entry => entry.tooLarge)
- 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]' : ''
- const sizeFlag = entry.tooLarge ? ' [too large]' : ''
- lines.push(` ${entry.change.padEnd(8)} ${entry.path}${flag}${sizeFlag}`)
- }
- if (oversized.length > 0) {
- lines.push('')
- lines.push(`Oversized files (over the ${MAX_FILE_BYTES / (1024 * 1024)} MB restore limit) cannot be restored by this undo; they will be reported as not restored:`)
- for (const entry of oversized)
- lines.push(` ${entry.path}`)
- }
- if (options.preview || options.withDiffs) {
- lines.push('')
- lines.push('Undo will apply (turn output → restored state):')
- for (const entry of entries) {
- 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 = 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) {
- const paths = notice.paths.map(path => `- ${path}`).join('\n')
- const turns = notice.turns.length > 0 ? notice.turns.join(', ') : notice.target_turn_id
- 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',
- content: [{ type: 'text', text }],
- source: {
- kind: 'plugin',
- plugin: name,
- form: 'rewind-notice',
- sections: [{ name, text }],
- },
- }
-}
-
-function createUnsupportedNoticeMessage(notice) {
- const text = `[Turn rewind unavailable]\nUndo is disabled for this workspace.\nReason: ${notice.reason}\n\nTurns here still run normally, but their file changes are not recorded, so /undo cannot revert them. Move this session to a normal project directory if you want undoable turns.`
- return {
- id: `turnrewind-notice-${notice.notice_id}`,
- role: 'user',
- content: [{ type: 'text', text }],
- source: {
- kind: 'plugin',
- plugin: name,
- form: 'undo-unavailable-notice',
- sections: [{ name, text }],
- },
- }
-}
-
-function createNoticeMessage(notice) {
- return notice.kind === 'unsupported'
- ? createUnsupportedNoticeMessage(notice)
- : createRewindNoticeMessage(notice)
-}
-
-function workspaceHasActiveTurn(active, workspaceKey) {
- for (const entry of active.values()) {
- if (entry.workspaceKey === workspaceKey)
- return true
- }
- return false
-}
-
-function workspaceHasActiveTurnForOtherSession(active, workspaceKey, sessionId) {
- for (const entry of active.values()) {
- if (entry.workspaceKey === workspaceKey && entry.sessionId !== sessionId)
- return true
- }
- return false
-}
-
-async function settleActiveTurn(ledger, active, key, reason) {
- const current = active.get(key)
- if (!current || current.runtime.disposed)
- return
- try {
- const afterRef = refSuffix(current.turnId, 'after')
- await captureSnapshot(current.runtime.store, afterRef, `turnrewind after ${current.turnId}`, current.runtime.parentRef)
- if (current.runtime.disposed)
- return
- const changed = await snapshotDiff(current.runtime.store, current.beforeRef, afterRef)
- if (current.runtime.disposed)
- return
- if (changed.length === 0) {
- settleNoopTurn(ledger, current.turnId, afterRef)
- }
- else if (reason) {
- settleInterruptedTurn(ledger, current.turnId, afterRef, reason)
- }
- else {
- settleTurn(ledger, current.turnId, afterRef)
- }
- current.runtime.parentRef = afterRef
- }
- catch (error) {
- if (!current.runtime.disposed)
- failTurn(ledger, current.turnId, error)
- }
- finally {
- active.delete(key)
- }
-}
-
-async function settleSessionTurns(ledger, active, sessionId, exceptKey, reason) {
- for (const [key, entry] of [...active.entries()]) {
- if (key === exceptKey || !key.startsWith(`${sessionId}:`) || !entry.baselineReady)
- continue
- await settleActiveTurn(ledger, active, key, 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.' }
- }
- 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 = 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 = 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}`
- await captureSnapshot(runtime.store, beforeRef, `turnrewind redo ${turn.turn_id}`, runtime.parentRef)
- for (const path of paths)
- 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
- }
-}
-
-/**
- * Same-origin HTTP route helper mirroring the dsh-tauri-worktree pattern:
- * POST-only JSON in / JSON out, mutation routes restricted to loopback peers
- * (the harness web UI itself is served on this host, so its page qualifies).
- */
-const MAX_ROUTE_BODY_BYTES = 16 * 1024
-
-function jsonRoute(path, handler, { mutate = false } = {}) {
- return {
- kind: 'exact',
- path,
- handler(req, res) {
- const send = (code, payload) => {
- const body = JSON.stringify(payload)
- res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' })
- res.end(body)
- }
- if (mutate && req.method !== 'POST') {
- res.setHeader('allow', 'POST')
- return send(405, { error: 'mutation routes require POST' })
- }
- const parts = []
- let totalBytes = 0
- let tooLarge = false
- req.on('data', (chunk) => {
- if (tooLarge)
- return
- const value = typeof chunk === 'string' ? chunk : chunk.toString('utf8')
- totalBytes += Buffer.byteLength(value, 'utf8')
- if (totalBytes > MAX_ROUTE_BODY_BYTES) {
- tooLarge = true
- return
- }
- parts.push(value)
- })
- req.on('error', () => send(400, { error: 'request stream failed' }))
- req.on('end', () => {
- void (async () => {
- if (tooLarge)
- return send(413, { error: 'request body too large' })
- if (mutate) {
- const peer = req.socket?.remoteAddress ?? ''
- const loopback = peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'
- if (!loopback)
- return send(403, { error: 'mutation routes only accept loopback calls' })
- }
- try {
- const parsed = JSON.parse(parts.join('') || '{}')
- const [code, payload] = await handler(parsed, req)
- send(code, payload)
- }
- catch (error) {
- send(500, { error: String(error?.message ?? error) })
- }
- })()
- })
- },
- }
-}
-
-/**
- * Shared undo executor for both the command path and the confirm HTTP route.
- * Throws with a user-facing message on failure — after rolling back whatever
- * was already restored from the pre-operation snapshot.
- */
-async function executeUndoRestore(runtime, params) {
- const { sessionId, workspaceKey, target, paths, entries, skipConflicts } = params
- const operationId = randomUUID()
- const beforeRef = `refs/turnrewind/operation-${operationId}`
- await captureSnapshot(runtime.store, beforeRef, `turnrewind undo ${target.turn_id}`, runtime.parentRef)
- createOperation(runtime.db, {
- operationId,
- kind: 'undo',
- targetTurnId: target.turn_id,
- requestedAt: new Date().toISOString(),
- beforeRef,
- })
-
- try {
- const targets = skipConflicts ? entries.filter(entry => !entry.conflict) : entries
- const restoredPaths = []
- const failedPaths = []
- for (const entry of targets) {
- try {
- await restorePath(runtime.store, target.before_ref, entry.path)
- restoredPaths.push(entry.path)
- }
- catch (error) {
- // One unrestorable file (oversized blob, unsupported target) must not
- // abort the whole undo: the other files still restore, and the failure
- // is reported per path instead of triggering a full rollback.
- failedPaths.push({ path: entry.path, error: String(error.message ?? error) })
- }
- }
- const skippedPaths = skipConflicts
- ? entries.filter(entry => entry.conflict).map(entry => entry.path)
- : []
- completeUndoWithNotice(runtime.db, target.turn_id, {
- noticeId: randomUUID(),
- sessionId,
- workspaceKey,
- targetTurnId: target.turn_id,
- paths: restoredPaths,
- createdAt: new Date().toISOString(),
- })
- settleOperation(runtime.db, operationId, 'applied')
- runtime.parentRef = beforeRef
- 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(', ')}.`
- if (failedPaths.length > 0)
- text += ` Not restored (${failedPaths.length} file(s)): ${failedPaths.map(failure => `${failure.path} (${failure.error.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.error})`).join('; ')}.`
- return text
- }
- catch (error) {
- let rollbackError = null
- try {
- // `beforeRef` is the state immediately before this operation. Restore every
- // path this operation actually touched - with --skip-conflicts the skipped
- // conflicted files were never written, so rolling them back here would
- // overwrite the human edits the user explicitly chose to keep.
- const rollbackPaths = skipConflicts ? entries.filter(entry => !entry.conflict).map(entry => entry.path) : paths
- for (const path of rollbackPaths) await restorePath(runtime.store, beforeRef, path)
- settleOperation(runtime.db, operationId, 'rolled_back', error)
- }
- catch (rollbackFailure) {
- rollbackError = rollbackFailure
- }
- if (rollbackError)
- throw new Error(`Undo and automatic recovery both failed: ${String(error)}; rollback failed: ${String(rollbackError)}`)
- throw new Error(`Undo failed and the pre-undo file state was restored: ${String(error)}`)
- }
-}
-
-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)
- return { kind: 'error', text: parsed.error }
-
- const workspaceDir = workspaceForAgent(invocation.agent)
- if (!workspaceDir) {
- // The hard guard refused the cwd; report the actual reason when there is one.
- const cwd = invocation.agent?.session?.header?.cwd
- const issue = typeof cwd === 'string' && cwd.length > 0 ? workspaceIssue(resolve(cwd)) : undefined
- if (issue)
- return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
- return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
- }
- const workspaceKey = workspaceKeyFor(workspaceDir)
- if (workspaceHasActiveTurn(active, workspaceKey)) {
- return { kind: 'error', text: 'Undo is unavailable while an Agent turn is still active in this workspace.' }
- }
- 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)
-
- // Pending-plan lifecycle: --cancel marks a parked plan cancelled; --confirm
- // validates it and falls through to execution below.
- if (parsed.cancel) {
- const removed = markPendingPlanCancelled(runtime.db, parsed.turnId, invocation.agent.session.id)
- return { kind: 'success', text: removed ? 'Pending undo cancelled.' : 'No pending undo plan matched (it may have expired or already run).' }
- }
-
- let target
- let pendingPlan
- let pendingPlanClaimed = false
- let pendingPlanCommitted = false
- function abortPendingPlanClaim() {
- if (pendingPlanClaimed) {
- releasePendingPlanClaim(runtime.db, parsed.turnId)
- pendingPlanClaimed = false
- }
- runtime.undoing = false
- }
- if (parsed.confirm) {
- const claim = claimPendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id)
- if (!claim.ok)
- return { kind: 'error', text: claim.error }
- pendingPlanClaimed = true
- // Reserve the workspace before the first await so another confirm route
- // cannot start a concurrent restore during snapshot validation.
- runtime.undoing = true
- pendingPlan = { turnId: claim.row.turn_id, paths: claim.row.paths, createdAt: claim.row.created_at }
- target = getTurn(runtime.db, pendingPlan.turnId)
- if (!target || !await turnRefsExist(runtime.store, target)) {
- abortPendingPlanClaim()
- return { kind: 'error', text: 'The pending plan\u0027s snapshot data no longer exists. Run /undo again to preview a fresh plan.' }
- }
- }
- else 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
- ? ` Latest turn ${latest.turn_id} is ${latest.status} (reversible=${latest.reversible}) in workspace ${latest.workspace_key}.`
- : ''
- return { kind: 'error', text: `No reversible turn was found for this session.${detail}` }
- }
- const ownershipError = assertSessionOwner(target, invocation.agent)
- if (ownershipError) {
- abortPendingPlanClaim()
- return ownershipError
- }
- if (target.workspace_key !== workspaceKey) {
- abortPendingPlanClaim()
- return { kind: 'error', text: 'The selected turn belongs to another workspace.' }
- }
- if (!['settled', 'interrupted'].includes(target.status) || target.reversible !== 1 || !target.before_ref || !target.after_ref) {
- abortPendingPlanClaim()
- return { kind: 'error', text: 'The selected turn does not have a complete reversible snapshot.' }
- }
-
- runtime.undoing = true
- try {
- const paths = await snapshotDiff(runtime.store, target.before_ref, target.after_ref)
- if (paths.length === 0) {
- if (pendingPlanClaimed) {
- markPendingPlanApplied(runtime.db, parsed.turnId, invocation.agent.session.id, 'No file changes were recorded for this turn.')
- pendingPlanCommitted = true
- }
- return { kind: 'success', text: 'No file changes were recorded for this turn.' }
- }
-
- const entries = await buildPlanEntries(runtime, workspaceDir, target, paths)
- const conflicts = entries.filter(entry => entry.conflict)
- const directExecute = parsed.force || parsed.skipConflicts
-
- // Read-only plan/preview: never touch disk.
- if (parsed.dryRun)
- return { kind: 'success', text: await formatPlan(runtime, target, entries, parsed) }
-
- // Bare /undo and --preview park a pending plan; execution waits for the
- // ✓ button (which sends /undo --confirm <plan-id>) so the user cannot
- // accidentally skip the preview. The card always carries the per-file
- // diffs — seeing what will be reverted is the point of the preview.
- if (!directExecute && !parsed.confirm) {
- const planText = await formatPlan(runtime, target, entries, { ...parsed, withDiffs: true })
- if (conflicts.length > 0)
- return { kind: parsed.preview ? 'success' : 'error', text: planText }
- const planId = createPendingPlan(runtime.db, {
- sessionId: invocation.agent.session.id,
- workspaceKey,
- turnId: target.turn_id,
- paths,
- })
- return {
- kind: 'success',
- text: `${planText}\nplan ${planId}\nSend /undo --confirm ${planId} to apply, or /undo --cancel ${planId} to dismiss.`,
- }
- }
-
- // Confirmed execution: re-verify nothing changed on disk since the
- // preview before overwriting anything.
- if (parsed.confirm && conflicts.length > 0) {
- abortPendingPlanClaim()
- return { kind: 'error', text: `The workspace changed since the preview (${conflicts.length} conflicted file(s)). Run /undo again to refresh the plan; use --force/--skip-conflicts deliberately if needed.` }
- }
-
- try {
- const text = await executeUndoRestore(runtime, {
- sessionId: invocation.agent.session.id,
- workspaceKey,
- target,
- paths,
- entries,
- skipConflicts: parsed.skipConflicts,
- })
- if (parsed.confirm) {
- markPendingPlanApplied(runtime.db, parsed.turnId, invocation.agent.session.id, text)
- pendingPlanCommitted = true
- }
- return { kind: 'success', text }
- }
- catch (error) {
- return { kind: 'error', text: String(error?.message ?? error) }
- }
- }
- finally {
- if (pendingPlanClaimed && !pendingPlanCommitted)
- abortPendingPlanClaim()
- else
- runtime.undoing = false
- }
-}
-
-function apply(ctx) {
- // Git mode uses the project's Git worktree as the snapshot boundary. Its
- // ignore rules replace the old full-directory eligibility scan, while path
- // validation, conflict checks and the private snapshot repository remain.
- const dataRoot = rootDir()
- const ledger = openLedger(dataRoot)
- const recoveryWorkspaces = new Set(listNeedsRecoveryWorkspaces(ledger))
- // One-shot at startup: consumed notices older than a week have no readers
- // left (their dedup window is long gone) and would otherwise accumulate
- // without bound on long-lived installs.
- pruneConsumedNotices(ledger)
- const active = new Map()
- const untrackedTurns = new Set()
- const workspaceStores = new Map()
- let disposed = false
- 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')
-
- // Same-origin HTTP routes powering the ✓/✗ buttons on the undo card: the
- // harness page itself is served from this host, so these need no extra
- // auth wiring (and mutations are loopback-only on top).
- ctx.effect(() => {
- function confirmRoute(body) {
- const planId = String(body.planId ?? '')
- const sessionId = String(body.sessionId ?? '')
- if (planId === '' || sessionId === '')
- return [400, { error: 'planId and sessionId are required' }]
- const previewRow = getPendingPlanRow(ledger, planId)
- if (previewRow === undefined)
- return [404, { error: 'plan expired or already applied — run /undo again' }]
- if (previewRow.session_id !== sessionId)
- return [403, { error: 'the plan belongs to another session' }]
- if (previewRow.status !== 'pending')
- return [409, { error: 'this plan was already applied or cancelled — run /undo again' }]
- const planRuntime = workspaceStores.get(previewRow.workspace_key)
- if (planRuntime === undefined)
- return [409, { error: 'the host restarted since this preview; run /undo again' }]
- if (planRuntime.undoing || workspaceHasActiveTurn(active, previewRow.workspace_key))
- return [409, { error: 'the workspace is busy — wait for the current turn to finish' }]
- const claim = claimPendingPlan(ledger, planId, sessionId)
- if (!claim.ok)
- return [claim.code, { error: claim.error }]
- const row = claim.row
- planRuntime.undoing = true
- let committed = false
- return (async () => {
- try {
- const target = getTurn(ledger, row.turn_id)
- if (target === undefined || target.reversible !== 1 || !target.before_ref || !target.after_ref || !await turnRefsExist(planRuntime.store, target))
- return [409, { error: 'the planned turn\u0027s snapshot data no longer exists — run /undo again' }]
- const paths = await snapshotDiff(planRuntime.store, target.before_ref, target.after_ref)
- if (paths.length === 0) {
- markPendingPlanApplied(ledger, planId, sessionId, 'No file changes were recorded for this turn.')
- committed = true
- return [200, { ok: true, message: 'No file changes were recorded for this turn.' }]
- }
- const entries = await buildPlanEntries(planRuntime, planRuntime.workspaceDir, target, paths)
- const conflicts = entries.filter(entry => entry.conflict)
- if (conflicts.length > 0)
- return [409, { error: `the workspace changed since the preview (${conflicts.length} conflicted file(s)) — run /undo again to refresh the plan` }]
- const message = await executeUndoRestore(planRuntime, {
- sessionId,
- workspaceKey: row.workspace_key,
- target,
- paths,
- entries,
- skipConflicts: false,
- })
- markPendingPlanApplied(ledger, planId, sessionId, message)
- committed = true
- return [200, { ok: true, message }]
- }
- finally {
- if (!committed)
- releasePendingPlanClaim(ledger, planId)
- planRuntime.undoing = false
- }
- })()
- }
-
- function cancelRoute(body) {
- const planId = String(body.planId ?? '')
- const sessionId = String(body.sessionId ?? '')
- if (planId === '' || sessionId === '')
- return [400, { error: 'planId and sessionId are required' }]
- const removed = markPendingPlanCancelled(ledger, planId, sessionId)
- return [200, { ok: true, message: removed ? 'Pending undo cancelled.' : 'No pending plan matched (it may have expired).' }]
- }
-
- function statusRoute(body, req) {
- const url = new URL(req.url ?? '/', 'http://localhost')
- const planId = String(url.searchParams.get('planId') ?? '')
- const sessionId = String(url.searchParams.get('sessionId') ?? '')
- if (planId === '' || sessionId === '')
- return [400, { error: 'planId and sessionId are required' }]
- const status = getPendingPlanStatus(ledger, planId, sessionId)
- if (status === undefined)
- return [404, { error: 'plan expired, unavailable, or owned by another session — run /undo again' }]
- return [200, status]
- }
-
- const routes = [
- jsonRoute('/api/turnrewind/confirm', confirmRoute, { mutate: true }),
- jsonRoute('/api/turnrewind/cancel', cancelRoute, { mutate: true }),
- jsonRoute('/api/turnrewind/status', statusRoute),
- ]
- const disposers = routes.map(route => ctx.webServer.register(route))
- return () => disposers.map(dispose => dispose())
- }, 'turnrewind routes')
-
- // 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()
- const endedTurns = new Map()
- const MAX_ENDED_TURNS = 4096
-
- function enqueueTurnTask(sessionId, task) {
- const previous = sessionChains.get(sessionId) ?? Promise.resolve()
- const next = previous.then(task)
- const settled = next.catch(() => {})
- sessionChains.set(sessionId, settled)
- void settled.then(() => {
- if (sessionChains.get(sessionId) === settled)
- sessionChains.delete(sessionId)
- })
- return next
- }
-
- function rememberEndedTurn(key) {
- const alreadyEnded = endedTurns.has(key)
- endedTurns.set(key, true)
- while (endedTurns.size > MAX_ENDED_TURNS)
- endedTurns.delete(endedTurns.keys().next().value)
- return alreadyEnded
- }
-
- function ensureRuntime(agent) {
- const workspaceDir = workspaceForAgent(agent)
- if (!workspaceDir)
- return undefined
- const workspaceKey = workspaceKeyFor(workspaceDir)
- let runtime = workspaceStores.get(workspaceKey)
- if (!runtime) {
- const store = createSnapshotStore(dataRoot, workspaceDir)
- const latest = getLatestSnapshotRef(ledger, workspaceKey)
- registerWorkspace(ledger, workspaceKey, workspaceDir, store.repoDir)
- // First touch since plugin start: resurrect files left mid-swap by a
- // crash in a previous host process (target missing + .bak present)
- // and clear debris (target present + .bak present) - both shapes only
- // exist inside the atomic-restore crash window.
- const resurrected = restoreCrashedSwaps(workspaceDir)
- for (const path of resurrected)
- console.warn(`turnrewind: resurrected ${path} in ${workspaceDir} from a crashed restore swap`)
- runtime = {
- db: ledger,
- store,
- workspaceKey,
- workspaceDir,
- parentRef: latest,
- undoing: false,
- disposed: false,
- }
- workspaceStores.set(workspaceKey, runtime)
- }
- return runtime
- }
-
- function recordSkipped(turnId, sessionId, workspaceKey, startedAt, reason, notify = true) {
- untrackedTurns.add(turnId)
- try {
- if (notify) {
- recordSkippedTurn(ledger, {
- turnId,
- sessionId,
- workspaceKey,
- startedAt,
- }, reason)
- }
- else {
- skipTurn(ledger, {
- turnId,
- sessionId,
- workspaceKey,
- startedAt,
- }, reason)
- }
- }
- catch (error) {
- console.error(`turnrewind: failed to record skipped turn ${turnId}: ${String(error)}`)
- }
- console.error(`turnrewind: skipped turn ${turnId}: ${reason}`)
- }
-
- function reserveTurnBaseline(agent, turn) {
- if (disposed)
- return undefined
- const sessionId = agent.session.id
- const key = activeKey(sessionId, turn)
- const existing = active.get(key)
- if (existing)
- return existing
- if (untrackedTurns.has(key) || endedTurns.has(key))
- return undefined
- const existingTurn = getTurn(ledger, key)
- if (existingTurn)
- return undefined
- const startedAt = new Date().toISOString()
- const workspaceDir = workspaceForAgent(agent)
- if (!workspaceDir) {
- // Git-only mode rejects system directories and non-Git workspaces. Keep a
- // durable skipped record so /undo explains why the turn was not tracked.
- const cwd = agent?.session?.header?.cwd
- if (typeof cwd === 'string' && cwd.length > 0) {
- const issue = workspaceIssue(resolve(cwd))
- if (issue)
- recordSkipped(key, sessionId, workspaceKeyFor(resolve(cwd)), startedAt, issue)
- }
- return undefined
- }
-
- const workspaceKey = workspaceKeyFor(workspaceDir)
- if (recoveryWorkspaces.has(workspaceKey)) {
- recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_RECOVERY_REQUIRED: a previous undo or redo was interrupted; inspect the workspace and clear its recovery state before using rewind again')
- return undefined
- }
- const issue = workspaceIssue(workspaceDir)
- if (issue) {
- recordSkipped(key, sessionId, workspaceKey, startedAt, issue)
- return undefined
- }
-
- const runtime = ensureRuntime(agent)
- if (!runtime)
- return undefined
-
- if (runtime.undoing) {
- recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_WORKSPACE_BUSY: an undo operation is running')
- return undefined
- }
- if (workspaceHasActiveTurnForOtherSession(active, workspaceKey, sessionId)) {
- recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_WORKSPACE_BUSY: another session is using this workspace')
- return undefined
- }
-
- // `agent/inbox/claimed` is a fire-and-forget notification. Create the
- // deferred synchronously so the awaited pre-step waterfall can always find
- // the reservation after Inbox.claim() returns.
- const beforeRef = refSuffix(key, 'before')
- const baseline = createDeferred()
- const entry = {
- runtime,
- sessionId,
- workspaceKey: runtime.workspaceKey,
- turnId: key,
- beforeRef,
- baseline,
- baselineReady: false,
- startedAt,
- turn,
- }
- active.set(key, entry)
-
- const baselineTask = async () => {
- if (disposed || active.get(key) !== entry) {
- settleDeferred(baseline, { ok: false, reason: 'turn was replaced before baseline capture' })
- return
- }
- try {
- const available = await gitAvailable()
- if (disposed || runtime.disposed) {
- settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })
- return
- }
- if (!available) {
- active.delete(key)
- const reason = 'TURNREWIND_GIT_UNAVAILABLE: the git executable was not found on PATH; file undo is disabled'
- recordSkipped(key, sessionId, runtime.workspaceKey, startedAt, reason)
- settleDeferred(baseline, { ok: false, reason })
- return
- }
- // A model switch can open B immediately after A is interrupted. Finalize A
- // before capturing B's baseline so B does not absorb A's partial files.
- await settleSessionTurns(ledger, active, sessionId, key, 'interrupted by a newer turn in the same session')
- if (disposed || runtime.disposed) {
- settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })
- return
- }
- await captureSnapshot(runtime.store, beforeRef, `turnrewind before ${key}`, runtime.parentRef)
- if (disposed || runtime.disposed) {
- settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })
- return
- }
- insertTurn(ledger, {
- turnId: key,
- sessionId,
- parentTurnId: undefined,
- workspaceKey: runtime.workspaceKey,
- startedAt,
- beforeRef,
- })
- entry.baselineReady = true
- settleDeferred(baseline, { ok: true })
- }
- catch (error) {
- active.delete(key)
- const reason = `TURNREWIND_CAPTURE_FAILED: ${String(error)}`
- // Transient capture failure (disk full, permissions): record the skip
- // before releasing the barrier, so the turn is explicitly untracked.
- if (!disposed && !runtime.disposed)
- recordSkipped(key, sessionId, runtime.workspaceKey, startedAt, reason, false)
- settleDeferred(baseline, { ok: false, reason })
- if (!disposed && !runtime.disposed)
- console.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)
- }
- }
- void enqueueTurnTask(sessionId, baselineTask).catch((error) => {
- // Keep the barrier finite even if future changes add an exception outside
- // baselineTask's guarded body.
- if (active.get(key) === entry)
- active.delete(key)
- const reason = `TURNREWIND_CAPTURE_FAILED: ${String(error)}`
- if (!disposed && !runtime.disposed)
- recordSkipped(key, sessionId, runtime.workspaceKey, startedAt, reason, false)
- settleDeferred(baseline, { ok: false, reason })
- if (!disposed && !runtime.disposed)
- console.error(`turnrewind: baseline queue failed for ${key}: ${String(error)}`)
- })
- return entry
- }
-
- ctx.on('agent/pre-step', async ({ agent, turn, signal }, next) => {
- // `agent/inbox/claimed` is an emit notification: Cordis deliberately does
- // not await listener promises. It synchronously reserves the active entry
- // and starts the baseline task, while this awaited waterfall is the actual
- // execution barrier. No downstream pre-step listener, model request, or
- // tool call may run until the before snapshot (or an explicit skip/failure)
- // has settled. The fallback creates the reservation here as well, so a
- // missed notification cannot silently allow an unprotected turn through.
- const key = activeKey(agent.session.id, turn)
- const entry = active.get(key) ?? (untrackedTurns.has(key) || endedTurns.has(key) ? undefined : reserveTurnBaseline(agent, turn))
- await waitForTurnBaseline(active, agent.session.id, turn, signal)
- signal.throwIfAborted()
- if (disposed)
- return { kind: 'reject' }
- if (!entry && workspaceForAgent(agent) && !untrackedTurns.has(key) && !endedTurns.has(key))
- console.error(`turnrewind: no baseline reservation for ${key}; turn is explicitly untracked`)
- const decision = await next()
- if (decision.kind === 'reject' || signal.aborted || disposed)
- return decision
- // Claiming must work even when workspaceForAgent refuses the cwd (home
- // dir): that is exactly the session kind the unsupported heads-up is
- // queued for. Fall back to the raw cwd as the workspace key.
- const cwd = agent?.session?.header?.cwd
- const workspaceDir = workspaceForAgent(agent)
- ?? (typeof cwd === 'string' && cwd.length > 0 ? resolve(cwd) : undefined)
- if (!workspaceDir)
- return decision
- const notices = claimRewindNotices(ledger, agent.session.id, workspaceKeyFor(workspaceDir))
- if (notices.length === 0)
- return decision
- return {
- ...decision,
- messages: [...decision.messages, ...notices.map(createNoticeMessage)],
- }
- })
-
- ctx.on('agent/inbox/claimed', (payload) => {
- if (!disposed)
- reserveTurnBaseline(payload.agent, payload.turn)
- })
-
- ctx.on('session/event', (session, event) => {
- if (disposed || event.type !== 'turn/end' || typeof event.data?.turn !== 'number')
- return
- const key = activeKey(session.id, event.data.turn)
- rememberEndedTurn(key)
- if (untrackedTurns.delete(key))
- return
- if (!active.has(key))
- return
- const reason = event.data.reason?.kind
- const interrupted = reason === 'aborted' || reason === 'error' || reason === 'cancelled'
- enqueueTurnTask(session.id, () => settleActiveTurn(ledger, active, key, interrupted ? `turn ended with ${reason}` : undefined))
- })
- ctx.on('agent/turn-stopping', () => {
- // A normal turn reaches the durable turn/end event immediately after this
- // listener. Wait for that authoritative boundary so interrupted writes are
- // included in the after snapshot.
- })
- ctx.on('agent/error', (payload) => {
- // Keep the active record until turn/end or the idle fallback. In particular,
- // model switching can emit an error before the final partial writes finish.
- console.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)
- })
- ctx.on('agent/status', ({ agent, status }) => {
- if (disposed || status !== 'idle')
- return
- const sessionId = agent.session.id
- for (const key of [...active.keys()]) {
- if (key.startsWith(`${sessionId}:`))
- enqueueTurnTask(sessionId, () => settleActiveTurn(ledger, active, key, 'agent became idle after interruption'))
- }
- })
- ctx.effect(() => () => {
- // A plugin stop/HMR can happen while pre-step is awaiting a baseline. Mark
- // every runtime first, release waiters, then wait for FIFO tasks before
- // closing SQLite.
- disposed = true
- for (const runtime of workspaceStores.values())
- runtime.disposed = true
- for (const entry of active.values())
- settleDeferred(entry.baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })
- active.clear()
- untrackedTurns.clear()
- endedTurns.clear()
- workspaceStores.clear()
- return (async () => {
- await Promise.allSettled([...sessionChains.values()])
- ledger.close()
- })()
- }, 'turnrewind runtime')
- ctx.effect(() => commands.register({
- name: 'undo',
- description: 'Plan or undo file changes made by the latest Agent turn',
- input: { hint: '[turn-id] [--dry-run|--preview] [--skip-conflicts|--force] | --redo' },
- handler: (invocation) => {
- const workspaceDir = workspaceForAgent(invocation.agent)
- if (!workspaceDir) {
- // The hard guard refused the cwd; report the actual reason when there is one.
- const cwd = invocation.agent?.session?.header?.cwd
- const issue = typeof cwd === 'string' && cwd.length > 0 ? workspaceIssue(resolve(cwd)) : undefined
- if (issue)
- return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
- return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
- }
- const workspaceIdentity = workspaceKeyFor(workspaceDir)
- if (recoveryWorkspaces.has(workspaceIdentity))
- return { kind: 'error', text: 'Undo is unavailable because a previous undo or redo was interrupted. Inspect the workspace, then purge its turnrewind data before retrying.' }
- const issue = workspaceIssue(workspaceDir)
- if (issue)
- return { kind: 'error', text: `Undo is unavailable for this workspace. ${issue}` }
- const runtime = ensureRuntime(invocation.agent)
- if (!runtime) {
- return { kind: 'error', text: 'Undo is unavailable because the Git workspace could not be initialized.' }
- }
- return applyUndo(runtime, active, invocation)
- },
- }), 'turnrewind command')
-}
-
-export { apply, applyUndo, inject, name }
diff --git a/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js b/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js
deleted file mode 100644
index c7fde4c2..00000000
--- a/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import process from 'node:process'
-import { purgeWorkspace, resolveRootDir } from './core/maintenance.js'
-
-function usage() {
- console.error('Usage: node purge-workspace.js <workspace-dir> [--home <dsh-home>]')
- console.error('')
- console.error('Removes the turnrewind snapshot repository and all ledger rows bound to')
- console.error('one workspace. Stop the DSH host process before running this command.')
- console.error('Defaults to the release data home (~/.dsh); pass --home or set DSH_HOME')
- console.error('to target the debug home (~/.dsh.dev).')
-}
-
-function main() {
- const args = process.argv.slice(2)
- const positional = []
- let home
- for (let index = 0; index < args.length; index += 1) {
- if (args[index] === '--home') {
- home = args[index + 1]
- index += 1
- continue
- }
- positional.push(args[index])
- }
- if (positional.length !== 1) {
- usage()
- process.exit(1)
- }
-
- const rootDir = resolveRootDir(home)
- const summary = purgeWorkspace(rootDir, positional[0])
- console.error(`turnrewind root: ${summary.rootDir}`)
- console.error(`snapshot repo: ${summary.repoDir} (${summary.repoExisted ? 'removed' : 'not found'})`)
- if (summary.ledger)
- console.error(`ledger rows removed: ${JSON.stringify(summary.ledger)}`)
- else
- console.error('ledger: not found, nothing to purge')
-}
-
-main()
diff --git a/plugins/dsh-tauri-turnrewind/package.json b/plugins/dsh-tauri-turnrewind/package.json
deleted file mode 100644
index f8c6167b..00000000
--- a/plugins/dsh-tauri-turnrewind/package.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "name": "dsh-tauri-turnrewind",
- "type": "module",
- "version": "0.1.0-dev.4",
- "description": "Local turn-aware workspace undo for DeepSeek Harness",
- "exports": {
- ".": "./lib/index.js",
- "./client": "./lib/client.js",
- "./cordis.patch.yml": "./cordis.patch.yml",
- "./package.json": "./package.json"
- },
- "main": "lib/index.js",
- "files": ["README.md", "cordis.patch.yml", "lib"],
- "dsh": {
- "runtime": "host",
- "bundle": {
- "patch": "./cordis.patch.yml"
- },
- "client": {
- "platform": "web",
- "inject": [
- "@deepseek-ai/dsh-client-runtime",
- "@deepseek-ai/dsh-client-locale"
- ]
- }
- },
- "engines": {
- "node": ">=22.15.0"
- },
- "scripts": {
- "test": "vitest run test --testTimeout=120000"
- },
- "devDependencies": {
- "vitest": "^4.1.11"
- }
-}
diff --git a/plugins/dsh-tauri-turnrewind/pnpm-lock.yaml b/plugins/dsh-tauri-turnrewind/pnpm-lock.yaml
deleted file mode 100644
index 50729709..00000000
--- a/plugins/dsh-tauri-turnrewind/pnpm-lock.yaml
+++ /dev/null
@@ -1,699 +0,0 @@
-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
-
- 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
-
-
-
-
-
-
- dependencies:
- '@types/estree': 1.0.9
-
-
- 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
-
-
-
-
-
-
- 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
-
-
-
-
-
-
-
- dependencies:
- fdir: 6.5.0([email protected])
- picomatch: 4.0.7
-
-
- 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.2
diff --git a/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.js b/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.js
deleted file mode 100644
index 1cfb3f65..00000000
--- a/plugins/dsh-tauri-turnrewind/test/atomic-restore.test.js
+++ /dev/null
@@ -1,97 +0,0 @@
-import assert from 'node:assert/strict'
-import { existsSync } from 'node:fs'
-import { mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join, sep } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restoreCrashedSwaps, restorePath, stateAt } from '../lib/core/git-snapshot.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-it('restores without leaving any swap debris', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'v1\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/atomic-1', 'before')
- await writeFile(join(workspace, 'a.txt'), 'v2\n')
- await captureSnapshot(store, 'refs/turnrewind/atomic-2', 'after', 'refs/turnrewind/atomic-1')
-
- await restorePath(store, before.commit, 'a.txt')
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')
- // No .bak, no .tmp anywhere in the workspace after a clean restore.
- const leftovers = (await readdir(join(workspace))).filter(name => name.includes('turnrewind'))
- assert.deepEqual(leftovers, [])
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('the startup sweep resurrects a target lost mid-swap', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-bak-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'old content\n')
- // Simulate the crash window: the target was renamed aside, the second
- // rename never happened, so only the .bak exists.
- await mkdir(join(workspace, 'nested'), { recursive: true })
- await writeFile(join(workspace, 'nested', 'b.txt'), 'nested old\n')
- await rename(join(workspace, 'a.txt'), join(workspace, 'a.txt.turnrewind-restore.bak'))
- await rename(join(workspace, 'nested', 'b.txt'), join(workspace, 'nested', 'b.txt.turnrewind-restore.bak'))
- assert.equal(existsSync(join(workspace, 'a.txt')), false)
-
- const resurrected = restoreCrashedSwaps(workspace)
- assert.deepEqual(resurrected.map(path => path.split(sep).join('/')).sort(), ['a.txt', 'nested/b.txt'])
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'old content\n')
- assert.equal(await readFile(join(workspace, 'nested', 'b.txt'), 'utf8'), 'nested old\n')
- // The workspace is clean again - no bak files remain.
- assert.equal(existsSync(join(workspace, 'a.txt.turnrewind-restore.bak')), false)
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('the startup sweep removes debris when the target survived', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-debris-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- // Crash happened after the second rename, before the bak delete: the new
- // content is in place and the bak is redundant.
- await writeFile(join(workspace, 'a.txt'), 'new content\n')
- await writeFile(join(workspace, 'a.txt.turnrewind-restore.bak'), 'old content\n')
-
- const resurrected = restoreCrashedSwaps(workspace)
- assert.deepEqual(resurrected, [])
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'new content\n')
- assert.equal(existsSync(join(workspace, 'a.txt.turnrewind-restore.bak')), false)
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('a leftover .bak never enters a snapshot', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-atomic-snap-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'a\n')
- // A bak left by a crashed swap sits next to a missing target.
- await writeFile(join(workspace, 'lost.txt.turnrewind-restore.bak'), 'lost old\n')
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/atomic-snap', 'snap')
- // The bak must not be tracked: restoring it as a normal path would
- // resurrect debris into the workspace on a later undo.
- assert.equal((await stateAt(store, snapshot.commit, 'lost.txt.turnrewind-restore.bak')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'a.txt')).kind, 'file')
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/barrier.test.js b/plugins/dsh-tauri-turnrewind/test/barrier.test.js
deleted file mode 100644
index 4ed67003..00000000
--- a/plugins/dsh-tauri-turnrewind/test/barrier.test.js
+++ /dev/null
@@ -1,194 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { it } from 'vitest'
-import { createSnapshotStore, gitRef } from '../lib/core/git-snapshot.js'
-import { apply, turnSnapshotRef } from '../lib/index.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-function createHarnessContext() {
- const events = new Map()
- const cleanups = []
- const routes = new Map()
- const commands = []
- const ctx = {
- commands: {
- register(command) {
- commands.push(command)
- return () => {}
- },
- },
- sessionProjections: {
- register() {
- return () => {}
- },
- },
- webServer: {
- register(route) {
- routes.set(route.path, route)
- return () => routes.delete(route.path)
- },
- },
- logger: {
- warn() {},
- },
- on(name, handler) {
- const listeners = events.get(name) ?? []
- listeners.push(handler)
- events.set(name, listeners)
- return () => {}
- },
- effect(factory) {
- const cleanup = factory()
- if (typeof cleanup === 'function')
- cleanups.push(cleanup)
- return cleanup
- },
- }
- return { ctx, events, cleanups, routes, commands }
-}
-
-async function waitForRef(store, workspace, ref, timeoutMs = 15000) {
- const deadline = Date.now() + timeoutMs
- while (Date.now() < deadline) {
- const value = await gitRef(store.repoDir, workspace, ref)
- if (value)
- return value
- await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
- }
- return undefined
-}
-
-async function withHarness(test) {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-barrier-test-'))
- const workspace = join(root, 'workspace')
- const dshHome = join(root, 'dsh-home')
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'before.txt'), 'before\n')
-
- const previousHome = process.env.DSH_HOME
- process.env.DSH_HOME = dshHome
- const harness = createHarnessContext()
- try {
- apply(harness.ctx)
- await test({ root, workspace, dshHome, harness })
- }
- finally {
- for (const dispose of harness.cleanups.reverse())
- await dispose()
- if (previousHome === undefined)
- delete process.env.DSH_HOME
- else
- process.env.DSH_HOME = previousHome
- await rm(root, { recursive: true, force: true })
- }
-}
-
-it('blocks the first model step until the claimed baseline completes', async () => {
- await withHarness(async ({ harness, workspace }) => {
- const agent = { session: { id: 'barrier-session', header: { cwd: workspace } } }
- const claimed = harness.events.get('agent/inbox/claimed')
- const preStep = harness.events.get('agent/pre-step')
- assert.equal(claimed?.length, 1)
- assert.equal(preStep?.length, 1)
-
- claimed[0]({ agent, turn: 1 })
- let continued = false
- const controller = new AbortController()
- const step = preStep[0]({ agent, turn: 1, signal: controller.signal }, async () => {
- continued = true
- return { kind: 'enter', messages: [] }
- })
-
- await Promise.resolve()
- assert.equal(continued, false)
- const decision = await step
- assert.equal(decision.kind, 'enter')
- assert.equal(continued, true)
- })
-})
-
-it('keeps consecutive claimed turns independent until both baselines are ready', async () => {
- await withHarness(async ({ harness, workspace, dshHome }) => {
- const agent = { session: { id: 'barrier-sequence', header: { cwd: workspace } } }
- const claimed = harness.events.get('agent/inbox/claimed')
- const preStep = harness.events.get('agent/pre-step')
- claimed[0]({ agent, turn: 1 })
- claimed[0]({ agent, turn: 2 })
-
- const controller = new AbortController()
- const firstStep = preStep[0]({ agent, turn: 1, signal: controller.signal }, async () => ({ kind: 'enter', messages: [] }))
- const secondStep = preStep[0]({ agent, turn: 2, signal: controller.signal }, async () => ({ kind: 'enter', messages: [] }))
- await Promise.all([firstStep, secondStep])
-
- const store = createSnapshotStore(dshHome, workspace)
- assert.ok(await waitForRef(store, workspace, turnSnapshotRef('barrier-sequence:1', 'before')))
- assert.ok(await waitForRef(store, workspace, turnSnapshotRef('barrier-sequence:2', 'before')))
- })
-})
-
-it('does not recreate a completed turn after a duplicate claim', async () => {
- await withHarness(async ({ harness, workspace, dshHome }) => {
- const agent = { session: { id: 'barrier-duplicate', header: { cwd: workspace } } }
- const claimed = harness.events.get('agent/inbox/claimed')
- const preStep = harness.events.get('agent/pre-step')
- const events = harness.events.get('session/event')
- const controller = new AbortController()
-
- claimed[0]({ agent, turn: 1 })
- await preStep[0]({ agent, turn: 1, signal: controller.signal }, async () => ({ kind: 'enter', messages: [] }))
- events[0](agent.session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })
- await new Promise(resolvePromise => setTimeout(resolvePromise, 300))
-
- const store = createSnapshotStore(dshHome, workspace)
- const beforeRef = turnSnapshotRef('barrier-duplicate:1', 'before')
- const afterRef = turnSnapshotRef('barrier-duplicate:1', 'after')
- const before = await waitForRef(store, workspace, beforeRef)
- const after = await waitForRef(store, workspace, afterRef)
- assert.ok(before)
- assert.ok(after)
-
- claimed[0]({ agent, turn: 1 })
- await Promise.resolve()
- await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
- assert.equal(await gitRef(store.repoDir, workspace, beforeRef), before)
- assert.equal(await gitRef(store.repoDir, workspace, afterRef), after)
- })
-})
-
-it('does not snapshot overlapping turns from another session in the same workspace', async () => {
- await withHarness(async ({ harness, workspace, dshHome }) => {
- const claimed = harness.events.get('agent/inbox/claimed')
- const preStep = harness.events.get('agent/pre-step')
- const first = { session: { id: 'workspace-owner', header: { cwd: workspace } } }
- const second = { session: { id: 'workspace-other', header: { cwd: workspace } } }
-
- claimed[0]({ agent: first, turn: 1 })
- await preStep[0]({ agent: first, turn: 1, signal: new AbortController().signal }, async () => ({ kind: 'enter', messages: [] }))
- claimed[0]({ agent: second, turn: 1 })
- await preStep[0]({ agent: second, turn: 1, signal: new AbortController().signal }, async () => ({ kind: 'enter', messages: [] }))
-
- const store = createSnapshotStore(dshHome, workspace)
- assert.ok(await gitRef(store.repoDir, workspace, turnSnapshotRef('workspace-owner:1', 'before')))
- assert.equal(await gitRef(store.repoDir, workspace, turnSnapshotRef('workspace-other:1', 'before')), undefined)
- })
-})
-
-it('ignores a late claim after turn/end without leaving a live baseline', async () => {
- await withHarness(async ({ harness, workspace, dshHome }) => {
- const agent = { session: { id: 'barrier-late-claim', header: { cwd: workspace } } }
- const claimed = harness.events.get('agent/inbox/claimed')
- const preStep = harness.events.get('agent/pre-step')
- const events = harness.events.get('session/event')
- const controller = new AbortController()
-
- events[0](agent.session, { type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } })
- claimed[0]({ agent, turn: 2 })
- const decision = await preStep[0]({ agent, turn: 2, signal: controller.signal }, async () => ({ kind: 'enter', messages: [] }))
- assert.equal(decision.kind, 'enter')
- await new Promise(resolvePromise => setTimeout(resolvePromise, 100))
- const store = createSnapshotStore(dshHome, workspace)
- assert.equal(await gitRef(store.repoDir, workspace, turnSnapshotRef('barrier-late-claim:2', 'before')), undefined)
- })
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/client-view.test.js b/plugins/dsh-tauri-turnrewind/test/client-view.test.js
deleted file mode 100644
index a823d294..00000000
--- a/plugins/dsh-tauri-turnrewind/test/client-view.test.js
+++ /dev/null
@@ -1,132 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import '../lib/client.js'
-
-/**
- * Load the client bundle the way the tests need it: the DSH module loader is
- * absent under Node, so client.js exposes its factory on globalThis and the
- * pure helpers can be exercised with a stub `require` (nothing dereferences
- * React/jsx-runtime at load time — only inside component bodies).
- */
-function loadBundle() {
- const factory = globalThis.__turnrewindClientFactory
- assert.equal(typeof factory, 'function', 'client.js must expose its factory when __ModuleLoader__ is absent')
- const stubRequire = () => ({ jsx: () => null, jsxs: () => null })
- return factory(stubRequire)
-}
-
-it('exposes the cordis plugin face and pure helpers', () => {
- const bundle = loadBundle()
- assert.equal(typeof bundle.apply, 'function')
- assert.deepEqual(bundle.inject, ['slots', 'sessions', 'locale'])
- assert.equal(typeof bundle.parseUndoOutput, 'function')
- assert.equal(typeof bundle.resolvePlanStatus, 'function')
- assert.equal(typeof bundle.resolveOwnerSessionId, 'function')
-})
-
-it('resolvePlanStatus settles an expired plan as gone and stops polling', () => {
- const bundle = loadBundle()
- // The host route answers 404 once the pending plan expired or was purged.
- const expired = bundle.resolvePlanStatus({ ok: false, status: 404 }, {})
- assert.deepEqual(expired, { status: 'gone', stop: true, resultText: null })
- // A host that ever reports gone explicitly settles the same way.
- const explicit = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'gone' })
- assert.deepEqual(explicit, { status: 'gone', stop: true, resultText: null })
-})
-
-it('resolvePlanStatus stops polling once the plan settles', () => {
- const bundle = loadBundle()
- const applied = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied', resultText: 'Undid turn x' })
- assert.deepEqual(applied, { status: 'applied', stop: true, resultText: 'Undid turn x' })
- // Missing resultText stays null so the card can substitute its own label.
- const appliedBare = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied' })
- assert.deepEqual(appliedBare, { status: 'applied', stop: true, resultText: null })
- const cancelled = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'cancelled' })
- assert.deepEqual(cancelled, { status: 'cancelled', stop: true, resultText: null })
-})
-
-it('resolvePlanStatus keeps polling pending plans', () => {
- const bundle = loadBundle()
- const pending = bundle.resolvePlanStatus({ ok: true, status: 200 }, { status: 'pending' })
- assert.deepEqual(pending, { status: 'pending', stop: false, resultText: null })
-})
-
-it('resolvePlanStatus keeps polling on non-404 failures without touching state', () => {
- const bundle = loadBundle()
- for (const res of [{ ok: false, status: 500 }, { ok: false, status: 503 }, { ok: true, status: 200 }]) {
- const next = bundle.resolvePlanStatus(res, res.ok ? {} : { error: 'boom' })
- assert.deepEqual(next, { status: null, stop: false, resultText: null })
- }
-})
-
-it('resolveOwnerSessionId prefers the session-scoped prop over the node', () => {
- const bundle = loadBundle()
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: 'session-b' } }), 'session-a')
- // Node field is the fallback for hosts that attach it to the command node.
- assert.equal(bundle.resolveOwnerSessionId({ node: { sessionId: 'session-b' } }), 'session-b')
-})
-
-it('resolveOwnerSessionId never guesses from missing or invalid ids', () => {
- const bundle = loadBundle()
- assert.equal(bundle.resolveOwnerSessionId({}), null)
- assert.equal(bundle.resolveOwnerSessionId(undefined), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: '' }), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 42 }), null)
- assert.equal(bundle.resolveOwnerSessionId({ sessionId: 'session-a', node: { sessionId: '' } }), 'session-a')
-})
-
-it('parseUndoOutput still extracts the pending plan id', () => {
- const bundle = loadBundle()
- const parsed = bundle.parseUndoOutput([
- 'Undo preflight: turn s:1; 1 file(s); 0 conflicts.',
- ' modified a.txt',
- '',
- 'Undo will apply (turn output → restored state):',
- '--- a.txt',
- ' -v2',
- ' +v1',
- 'plan 0f1e2d3c',
- 'Send /undo --confirm 0f1e2d3c to apply, or /undo --cancel 0f1e2d3c to dismiss.',
- ].join('\n'))
- assert.equal(parsed.planId, '0f1e2d3c')
- assert.equal(parsed.summary, 'Undo preflight: turn s:1; 1 file(s); 0 conflicts.')
- assert.equal(parsed.files.length, 1)
-})
-
-it('parseUndoOutput keeps paths with spaces and plan flags out of the conflict fallback', () => {
- const bundle = loadBundle()
- const parsed = bundle.parseUndoOutput([
- 'Undo preflight: turn s:1; 3 file(s) (modified 2, created 1, deleted 0); 1 conflict(s).',
- ' modified my notes.txt',
- ' created reports/q3 summary.md',
- ' modified assets/logo.png [conflict]',
- ' modified assets/hero.png [too large]',
- '',
- 'Oversized files (over the 64 MB restore limit) cannot be restored by this undo; they will be reported as not restored:',
- ' assets/hero.png',
- '',
- 'Undo will apply (turn output → restored state):',
- '--- my notes.txt',
- ' -new',
- ' +old',
- 'plan 0f1e2d3c',
- 'Send /undo --confirm 0f1e2d3c to apply, or /undo --cancel 0f1e2d3c to dismiss.',
- ].join('\n'))
-
- assert.equal(parsed.files.length, 4)
- assert.deepEqual(
- parsed.files.map(file => [file.path, file.change, file.conflict]),
- [
- ['my notes.txt', 'modified', false],
- ['reports/q3 summary.md', 'created', false],
- ['assets/logo.png', 'modified', true],
- ['assets/hero.png', 'modified', false],
- ],
- )
- // The diff section attaches to the spaced path instead of creating a
- // duplicate "conflict" entry for it.
- const spaced = parsed.files.find(file => file.path === 'my notes.txt')
- assert.equal(spaced.diff.length, 2)
- assert.equal(spaced.additions, 1)
- assert.equal(spaced.deletions, 1)
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js b/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js
deleted file mode 100644
index 0ceb83eb..00000000
--- a/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { createDialogProjection, extractUnsupportedNotice } from '../lib/core/dialog-projection.js'
-
-function unsupportedEvent(id, reason, withSource = true) {
- const text = `[Turn rewind unavailable]\nUndo is disabled for this workspace.\nReason: ${reason}\n\nTurns here still run normally.`
- const message = { id, role: 'user', content: [{ type: 'text', text }] }
- if (withSource)
- message.source = { kind: 'plugin', plugin: 'dsh-tauri-turnrewind', form: 'undo-unavailable-notice', sections: [] }
- return { type: 'user/message', seq: 1, data: message }
-}
-
-it('extracts unsupported notices from plugin messages with and without source', () => {
- const withSource = extractUnsupportedNotice(unsupportedEvent('turnrewind-notice-a', 'TURNREWIND_WORKSPACE_UNSUPPORTED: home'))
- assert.deepEqual(withSource, { id: 'turnrewind-notice-a', reason: 'TURNREWIND_WORKSPACE_UNSUPPORTED: home' })
- const byText = extractUnsupportedNotice(unsupportedEvent('turnrewind-notice-b', 'TURNREWIND_WORKSPACE_TOO_LARGE: budget', false))
- assert.deepEqual(byText, { id: 'turnrewind-notice-b', reason: 'TURNREWIND_WORKSPACE_TOO_LARGE: budget' })
-})
-
-it('ignores unrelated session events', () => {
- assert.equal(extractUnsupportedNotice({ type: 'turn/start', data: { turn: 1 } }), undefined)
- assert.equal(extractUnsupportedNotice({
- type: 'user/message',
- data: { id: 'plain', role: 'user', content: [{ type: 'text', text: '你好' }] },
- }), undefined)
- assert.equal(extractUnsupportedNotice(undefined), undefined)
-})
-
-it('folds notices into the view, dedupes by id, and caps the list', () => {
- const projection = createDialogProjection()
- let state = projection.init()
- state = projection.apply(state, unsupportedEvent('notice-1', 'r1'))
- assert.equal(projection.wire.view(state).notices.length, 1)
- const unchanged = state
- state = projection.apply(state, unsupportedEvent('notice-1', 'r1'))
- assert.equal(state, unchanged)
- for (let index = 2; index <= 25; index += 1)
- state = projection.apply(state, unsupportedEvent(`notice-${index}`, `r${index}`))
- const view = projection.wire.view(state)
- assert.equal(view.notices.length, 20)
- assert.equal(view.notices.at(-1).id, 'notice-25')
- assert.equal(view.notices[0].id, 'notice-6')
-})
-
-it('validates persisted state through the schema face', () => {
- const projection = createDialogProjection()
- assert.deepEqual(projection.stateSchema.parse({ notices: [] }), { notices: [] })
- assert.throws(() => projection.stateSchema.parse({ broken: true }), /TURNREWIND_PROJECTION_SHAPE/)
- assert.throws(() => projection.wire.viewSchema.parse(null), /TURNREWIND_PROJECTION_SHAPE/)
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/git-gc.test.js b/plugins/dsh-tauri-turnrewind/test/git-gc.test.js
deleted file mode 100644
index 1dfab5be..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-gc.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import assert from 'node:assert/strict'
-import { existsSync } from 'node:fs'
-import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restorePath, stateAt } from '../lib/core/git-snapshot.js'
-import { commitAll, gitOutput, initGitWorkspace, runGit } from './git-test-utils.js'
-
-it('detects source-pruned objects and rebuilds a self-contained baseline', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-gc-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'committed.txt'), 'committed\n')
- await commitAll(workspace, 'initial')
- await writeFile(join(workspace, 'borrowed.txt'), 'borrowed content\n')
- // An unreachable source object: present in the source object store but
- // referenced by no ref, exactly like the leftovers of an amend or rebase.
- const borrowedBlob = (await gitOutput(workspace, ['hash-object', '-w', 'borrowed.txt'])).trim()
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const first = await captureSnapshot(store, 'refs/turnrewind/gc-before', 'before')
- // The blob was borrowed through alternates instead of being copied.
- assert.equal((await stateAt(store, first.commit, 'borrowed.txt')).kind, 'file')
- assert.equal(existsSync(join(store.repoDir, 'objects', 'info', 'alternates')), true)
- await gitOutput(workspace, ['--git-dir', store.repoDir, 'cat-file', '-e', `${first.commit}:borrowed.txt`])
-
- // The turn: rewrite one file and delete the borrowed one.
- await writeFile(join(workspace, 'committed.txt'), 'changed\n')
- await rm(join(workspace, 'borrowed.txt'))
- // The source repository prunes its unreachable objects. Files still on
- // disk get their blobs re-written locally on the next capture (read-tree
- // seeds a stat-less index, so git add re-hashes everything), but a
- // deleted file's borrowed blob is never re-written: only the parent
- // chain still references it.
- await runGit(workspace, ['gc', '--quiet', '--prune=now'])
- await assert.rejects(() => gitOutput(workspace, ['cat-file', '-t', borrowedBlob]))
- // Reads of the old snapshot now break: the borrowed blob is gone everywhere.
- await assert.rejects(() => stateAt(store, first.commit, 'borrowed.txt'))
-
- // The next capture detects the hole through the parent chain and heals
- // into a self-contained store.
- const second = await captureSnapshot(store, 'refs/turnrewind/gc-after', 'after', 'refs/turnrewind/gc-before')
- assert.notEqual(second.commit, first.commit)
- assert.equal(existsSync(join(store.repoDir, 'objects', 'info', 'alternates')), false)
- assert.equal((await stateAt(store, second.commit, 'committed.txt')).kind, 'file')
- assert.equal((await stateAt(store, second.commit, 'borrowed.txt')).kind, 'absent')
-
- // Later captures stay self-contained and keep reading without the source.
- const third = await captureSnapshot(store, 'refs/turnrewind/gc-third', 'third', 'refs/turnrewind/gc-after')
- assert.equal((await stateAt(store, third.commit, 'committed.txt')).kind, 'file')
- await restorePath(store, third.commit, 'committed.txt')
- assert.equal(await readFile(join(workspace, 'committed.txt'), 'utf8'), 'changed\n')
-
- // The healed store physically owns its objects: with no alternates file
- // the snapshot chain no longer depends on the source repository's
- // object store at all.
- const objects = await readdir(join(store.repoDir, 'objects'), { withFileTypes: true })
- assert.equal(existsSync(join(store.repoDir, 'objects', 'info', 'alternates')), false)
- assert.ok(objects.some(entry => entry.isDirectory() && entry.name !== 'info'))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/git-ignore.test.js b/plugins/dsh-tauri-turnrewind/test/git-ignore.test.js
deleted file mode 100644
index 45e463eb..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-ignore.test.js
+++ /dev/null
@@ -1,130 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, stateAt } from '../lib/core/git-snapshot.js'
-import { gitOutput, initGitWorkspace } from './git-test-utils.js'
-
-it('applies nested .gitignore patterns including negations', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-ignore-nested-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, '.gitignore'), '*.log\n!keep.log\n')
- await mkdir(join(workspace, 'nested'))
- await writeFile(join(workspace, 'nested', '.gitignore'), 'inner-secret.txt\n')
- await writeFile(join(workspace, 'debug.log'), 'log')
- await writeFile(join(workspace, 'keep.log'), 'keep')
- await writeFile(join(workspace, 'nested', 'inner-secret.txt'), 'secret')
- await writeFile(join(workspace, 'nested', 'ok.txt'), 'ok')
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/ignore-nested', 'nested ignore')
-
- assert.equal((await stateAt(store, snapshot.commit, 'debug.log')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'keep.log')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'nested/inner-secret.txt')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'nested/ok.txt')).kind, 'file')
- // The rule files themselves are ordinary tracked-able files.
- assert.equal((await stateAt(store, snapshot.commit, '.gitignore')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'nested/.gitignore')).kind, 'file')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('honors .git/info/exclude and re-syncs it when the source rules change', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-ignore-exclude-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'excluded.txt'), 'excluded')
- await writeFile(join(workspace, 'kept.txt'), 'kept')
- const sourceExclude = join(workspace, '.git', 'info', 'exclude')
- await mkdir(dirname(sourceExclude), { recursive: true })
- await writeFile(sourceExclude, 'excluded.txt\n')
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const first = await captureSnapshot(store, 'refs/turnrewind/ignore-exclude-1', 'first')
- assert.equal((await stateAt(store, first.commit, 'excluded.txt')).kind, 'absent')
- assert.equal((await stateAt(store, first.commit, 'kept.txt')).kind, 'file')
-
- // The source exclude file is mirrored into the private snapshot repo on
- // every capture, so relaxing the rule re-opens the file to snapshots.
- await writeFile(sourceExclude, '')
- const second = await captureSnapshot(store, 'refs/turnrewind/ignore-exclude-2', 'second', first.commit)
- assert.equal((await stateAt(store, second.commit, 'excluded.txt')).kind, 'file')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('honors the global excludes file like the source repository', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-ignore-global-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'globally-ignored.txt'), 'ignored')
- await writeFile(join(workspace, 'kept.txt'), 'kept')
- const globalExcludes = join(root, 'global-excludes')
- const globalConfig = join(root, 'global-gitconfig')
- await writeFile(globalExcludes, 'globally-ignored.txt\n')
- await writeFile(globalConfig, `[core]\n\texcludesFile = ${globalExcludes.replaceAll('\\', '/')}\n`)
-
- const previous = process.env.GIT_CONFIG_GLOBAL
- process.env.GIT_CONFIG_GLOBAL = globalConfig
- try {
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/ignore-global', 'global ignore')
- assert.equal((await stateAt(store, snapshot.commit, 'globally-ignored.txt')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'kept.txt')).kind, 'file')
- }
- finally {
- if (previous === undefined)
- delete process.env.GIT_CONFIG_GLOBAL
- else
- process.env.GIT_CONFIG_GLOBAL = previous
- }
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('normalizes text=auto files on capture and keeps -text files byte-exact', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-ignore-attributes-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, '.gitattributes'), '*.txt text=auto\n*.bin -text\n')
- await writeFile(join(workspace, 'crlf.txt'), 'a\r\nb\r\n')
- await writeFile(join(workspace, 'lf.txt'), 'a\nb\n')
- await writeFile(join(workspace, 'crlf.bin'), 'a\r\nb\r\n')
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/attributes', 'attributes')
-
- // text=auto: the stored blob is LF-normalized, so the CRLF and LF twins
- // share one object. (stateAt digests normalize line endings too, so the
- // blob bytes are read directly to pin the object content.)
- const crlf = await stateAt(store, snapshot.commit, 'crlf.txt')
- const lf = await stateAt(store, snapshot.commit, 'lf.txt')
- assert.equal(crlf.kind, 'file')
- assert.equal(lf.kind, 'file')
- assert.equal(crlf.digest, lf.digest)
- assert.equal(await gitOutput(workspace, ['--git-dir', store.repoDir, 'cat-file', 'blob', `${snapshot.commit}:crlf.txt`]), 'a\nb\n')
- assert.equal(await gitOutput(workspace, ['--git-dir', store.repoDir, 'cat-file', 'blob', `${snapshot.commit}:lf.txt`]), 'a\nb\n')
-
- // -text: no conversion anywhere, the blob is byte-identical to the disk file.
- assert.equal(
- await gitOutput(workspace, ['--git-dir', store.repoDir, 'cat-file', 'blob', `${snapshot.commit}:crlf.bin`]),
- await readFile(join(workspace, 'crlf.bin'), 'utf8'),
- )
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/git-kill.test.js b/plugins/dsh-tauri-turnrewind/test/git-kill.test.js
deleted file mode 100644
index 8c677b1d..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-kill.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import assert from 'node:assert/strict'
-import { spawn } from 'node:child_process'
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, gitExitIsClean, runGit } from '../lib/core/git-snapshot.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-/**
- * External kills deliver either close(null, signal) or, on Windows, a
- * nonzero exit with no signal. Neither is a clean exit: partial stdout must
- * never be accepted as a complete Git result.
- */
-it('gitExitIsClean only accepts a successful unsignalled exit', () => {
- assert.equal(gitExitIsClean(0, null), true)
- assert.equal(gitExitIsClean(0, undefined), true)
- assert.equal(gitExitIsClean(null, 'SIGKILL'), false)
- assert.equal(gitExitIsClean(null, 'SIGTERM'), false)
- assert.equal(gitExitIsClean(1, null), false)
- assert.equal(gitExitIsClean(null, null), false)
-})
-
-it('an abruptly terminated child is classified as unclean on every platform', async () => {
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => process.kill(process.pid, "SIGKILL"), 50)'])
- const result = await new Promise((resolvePromise) => {
- child.on('close', (code, signal) => resolvePromise({ code, signal }))
- })
- assert.equal(gitExitIsClean(result.code, result.signal), false)
-})
-
-it('runGit keeps succeeding on the normal exit path after the kill guard', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-kill-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'a\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/kill-test', 'kill test')
- const output = await runGit(store.repoDir, store.workspaceDir, ['rev-parse', '--verify', 'refs/turnrewind/kill-test'])
- assert.ok(output.length > 0)
- assert.ok(snapshot.commit)
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js b/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
deleted file mode 100644
index c97a32f4..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-snapshot.test.js
+++ /dev/null
@@ -1,257 +0,0 @@
-import assert from 'node:assert/strict'
-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, 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'
-import { initGitWorkspace } from './git-test-utils.js'
-
-it('captures and restores modified, added, and deleted files', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'modified.txt'), 'before')
- await writeFile(join(workspace, 'deleted.txt'), 'to delete')
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/test-before', 'before')
-
- await writeFile(join(workspace, 'modified.txt'), 'after')
- await rm(join(workspace, 'deleted.txt'))
- await writeFile(join(workspace, 'added.txt'), 'new')
- const after = await captureSnapshot(store, 'refs/turnrewind/test-after', 'after', before.commit)
-
- assert.deepEqual((await snapshotDiff(store, before.commit, after.commit)).sort(), ['added.txt', 'deleted.txt', 'modified.txt'])
- assert.notEqual((await stateAt(store, before.commit, 'modified.txt')).digest, (await stateAt(store, after.commit, 'modified.txt')).digest)
-
- await restorePath(store, before.commit, 'modified.txt')
- await restorePath(store, before.commit, 'deleted.txt')
- await restorePath(store, before.commit, 'added.txt')
-
- assert.equal(await readFile(join(workspace, 'modified.txt'), 'utf8'), 'before')
- assert.equal(await readFile(join(workspace, 'deleted.txt'), 'utf8'), 'to delete')
- await assert.rejects(stat(join(workspace, 'added.txt')))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('allows sequential undo of an interrupted turn after a later turn', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-sequence-test-'))
- const workspace = join(root, 'workspace')
- const filesA = ['a-1.txt', 'a-2.txt']
- const filesB = ['b-1.txt', 'b-2.txt']
- const db = openLedger(join(root, 'ledger'))
- try {
- await initGitWorkspace(workspace)
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const beforeA = await captureSnapshot(store, 'refs/turnrewind/a-before', 'A before')
- for (const file of filesA) await writeFile(join(workspace, file), 'A')
- const afterA = await captureSnapshot(store, 'refs/turnrewind/a-after', 'A after', beforeA.commit)
- insertTurn(db, {
- turnId: 'session:A',
- sessionId: 'session',
- workspaceKey: workspace.toLowerCase(),
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/a-before',
- })
- settleInterruptedTurn(db, 'session:A', 'refs/turnrewind/a-after', 'interrupted')
-
- const beforeB = await captureSnapshot(store, 'refs/turnrewind/b-before', 'B before', afterA.commit)
- for (const file of filesB) await writeFile(join(workspace, file), 'B')
- const afterB = await captureSnapshot(store, 'refs/turnrewind/b-after', 'B after', beforeB.commit)
- insertTurn(db, {
- turnId: 'session:B',
- sessionId: 'session',
- workspaceKey: workspace.toLowerCase(),
- startedAt: '2026-01-01T00:01:00.000Z',
- beforeRef: 'refs/turnrewind/b-before',
- })
- settleTurn(db, 'session:B', 'refs/turnrewind/b-after')
-
- for (const file of await snapshotDiff(store, beforeB.commit, afterB.commit)) await restorePath(store, beforeB.commit, file)
- completeUndoWithNotice(db, 'session:B', {
- noticeId: 'notice-b',
- sessionId: 'session',
- workspaceKey: workspace.toLowerCase(),
- targetTurnId: 'session:B',
- paths: filesB,
- createdAt: '2026-01-01T00:02:00.000Z',
- })
- assert.equal(getLatestTurn(db, 'session', workspace.toLowerCase()).turn_id, 'session:A')
-
- for (const file of await snapshotDiff(store, beforeA.commit, afterA.commit)) await restorePath(store, beforeA.commit, file)
- for (const file of [...filesA, ...filesB]) await assert.rejects(stat(join(workspace, file)))
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('handles non-ASCII paths without reporting a false restore', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-unicode-test-'))
- const workspace = join(root, 'workspace')
- const fileName = '新建文本文档.txt'
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, fileName), 'before')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/unicode-before', 'before')
- await writeFile(join(workspace, fileName), 'after')
- const after = await captureSnapshot(store, 'refs/turnrewind/unicode-after', 'after', before.commit)
- assert.deepEqual(await snapshotDiff(store, before.commit, after.commit), [fileName])
- await restorePath(store, before.commit, fileName)
- assert.equal(await readFile(join(workspace, fileName), 'utf8'), 'before')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('does not treat CRLF conversion as a file conflict', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-crlf-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'line-endings.txt'), 'before\nline\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/crlf-before', 'before')
- await writeFile(join(workspace, 'line-endings.txt'), 'after\nline\n')
- const after = await captureSnapshot(store, 'refs/turnrewind/crlf-after', 'after', before.commit)
- await writeFile(join(workspace, 'line-endings.txt'), 'after\r\nline\r\n')
- assert.equal(currentState(workspace, 'line-endings.txt').digest, (await stateAt(store, after.commit, 'line-endings.txt')).digest)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-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 initGitWorkspace(workspace)
- 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 = 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 = await captureSnapshot(store, 'refs/turnrewind/diff-after', 'after', before.commit)
-
- 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 = 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(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 = 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(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 initGitWorkspace(workspace)
- await writeFile(join(workspace, 'big.txt'), 'old\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- 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 = 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')
- try {
- await initGitWorkspace(workspace)
- assert.throws(() => currentState(workspace, '../outside.txt'), /TURNREWIND_PATH_ESCAPE/)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('accepts Git worktrees and rejects ordinary directories', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-probe-'))
- const workspace = join(root, 'ws')
- const plain = join(root, 'plain')
- try {
- await initGitWorkspace(workspace)
- await mkdir(plain, { recursive: true })
- const tracked = probeWorkspace(workspace)
- assert.equal(tracked.ok, true)
- assert.equal(tracked.workspaceDir, workspace)
- const rejected = probeWorkspace(plain)
- assert.equal(rejected.ok, false)
- assert.match(rejected.reason, /GIT_REQUIRED/u)
- }
- 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 initGitWorkspace(workspace)
- 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 --git a/plugins/dsh-tauri-turnrewind/test/git-state.test.js b/plugins/dsh-tauri-turnrewind/test/git-state.test.js
deleted file mode 100644
index 9077b88d..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-state.test.js
+++ /dev/null
@@ -1,107 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtemp, readdir, 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, restorePath } from '../lib/core/git-snapshot.js'
-import { commitAll, gitOutput, initGitWorkspace } from './git-test-utils.js'
-
-/**
- * The full logical state of the user's source repository. If any snapshot or
- * restore command leaked into the real HEAD, branch, index, refs, stash or
- * commit history, one of these fields would drift.
- */
-async function sourceRepoState(workspace) {
- return {
- head: await gitOutput(workspace, ['rev-parse', 'HEAD']),
- branch: await gitOutput(workspace, ['branch', '--show-current']),
- symbolicRef: await gitOutput(workspace, ['symbolic-ref', 'HEAD']),
- status: await gitOutput(workspace, ['status', '--porcelain=v1', '-z']),
- index: await gitOutput(workspace, ['ls-files', '-s']),
- staged: await gitOutput(workspace, ['diff', '--cached']),
- refs: await gitOutput(workspace, ['for-each-ref']),
- history: await gitOutput(workspace, ['log', '--oneline', '--all']),
- stash: await gitOutput(workspace, ['stash', 'list']),
- }
-}
-
-/**
- * A deliberately dirty repository: one commit, one staged change, one
- * unstaged change on the same file and one untracked file. A clean repo
- * could hide index pollution; this state cannot.
- */
-async function setupDirtyWorkspace(root) {
- const workspace = join(root, 'workspace')
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'tracked.txt'), 'v1\n')
- await commitAll(workspace, 'initial')
- await writeFile(join(workspace, 'tracked.txt'), 'staged v2\n')
- await gitOutput(workspace, ['add', 'tracked.txt'])
- await writeFile(join(workspace, 'tracked.txt'), 'unstaged v3\n')
- await writeFile(join(workspace, 'untracked.txt'), 'untracked\n')
- return workspace
-}
-
-async function workspaceEntries(workspace) {
- return (await readdir(workspace)).filter(entry => entry !== '.git').sort()
-}
-
-it('captures snapshots without touching HEAD, branch, index, status, refs or stash', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-git-state-'))
- try {
- const workspace = await setupDirtyWorkspace(root)
- const before = await sourceRepoState(workspace)
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const first = await captureSnapshot(store, 'refs/turnrewind/git-state-before', 'before')
- // A second capture with a parent exercises the incremental path; the
- // workspace itself is untouched between captures so the full logical
- // state, including `git status`, must stay byte-identical.
- const second = await captureSnapshot(store, 'refs/turnrewind/git-state-after', 'after', first.commit)
- assert.notEqual(first.commit, second.commit)
-
- assert.deepEqual(await sourceRepoState(workspace), before)
- assert.deepEqual(await workspaceEntries(workspace), ['tracked.txt', 'untracked.txt'])
-
- // Snapshot refs live only under refs/turnrewind/ in the private repo...
- const snapshotRefs = await gitOutput(workspace, ['--git-dir', store.repoDir, 'for-each-ref'])
- assert.match(snapshotRefs, /refs\/turnrewind\//)
- assert.doesNotMatch(snapshotRefs, /refs\/(heads|tags|remotes)\//)
- // ...and never leak into the user's ref namespace.
- assert.doesNotMatch(before.refs, /turnrewind/)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('restores worktree files while the index, HEAD, refs and stash stay untouched', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-git-state-restore-'))
- try {
- const workspace = await setupDirtyWorkspace(root)
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const baseline = await captureSnapshot(store, 'refs/turnrewind/restore-before', 'before')
- const stateBefore = await sourceRepoState(workspace)
-
- // The "turn": rewrite a tracked file and add a new one.
- await writeFile(join(workspace, 'tracked.txt'), 'turn output\n')
- await writeFile(join(workspace, 'turn-output.txt'), 'output\n')
- await captureSnapshot(store, 'refs/turnrewind/restore-after', 'after', baseline.commit)
-
- await restorePath(store, baseline.commit, 'tracked.txt')
- await restorePath(store, baseline.commit, 'turn-output.txt')
-
- // The undo restored the pre-turn worktree content ('unstaged v3'), not
- // the staged blob: snapshots capture the filesystem, never the index.
- assert.equal(await readFile(join(workspace, 'tracked.txt'), 'utf8'), 'unstaged v3\n')
- await assert.rejects(stat(join(workspace, 'turn-output.txt')))
- assert.deepEqual(await workspaceEntries(workspace), ['tracked.txt', 'untracked.txt'])
-
- // The index still holds the staged 'v2' blob, so the porcelain state is
- // byte-identical: same MM entry for tracked.txt, same untracked file.
- assert.deepEqual(await sourceRepoState(workspace), stateBefore)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/git-test-utils.js b/plugins/dsh-tauri-turnrewind/test/git-test-utils.js
deleted file mode 100644
index 05b22ad0..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-test-utils.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import { Buffer } from 'node:buffer'
-import { spawn } from 'node:child_process'
-import { mkdir } from 'node:fs/promises'
-
-export function runGit(cwd, args) {
- return new Promise((resolvePromise, rejectPromise) => {
- const child = spawn('git', args, { cwd })
- const errors = []
- child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', rejectPromise)
- child.on('close', (code) => {
- if (code !== 0) {
- rejectPromise(new Error(`git ${args.join(' ')} failed: ${Buffer.concat(errors).toString('utf8').trim()}`))
- return
- }
- resolvePromise()
- })
- })
-}
-
-export function gitOutput(cwd, args) {
- return new Promise((resolvePromise, rejectPromise) => {
- const child = spawn('git', args, { cwd })
- const chunks = []
- const errors = []
- child.stdout.on('data', chunk => chunks.push(chunk))
- child.stderr.on('data', chunk => errors.push(chunk))
- child.on('error', rejectPromise)
- child.on('close', (code) => {
- if (code !== 0) {
- rejectPromise(new Error(`git ${args.join(' ')} failed: ${Buffer.concat(errors).toString('utf8').trim()}`))
- return
- }
- resolvePromise(Buffer.concat(chunks).toString('utf8'))
- })
- })
-}
-
-export async function commitAll(workspace, message) {
- await runGit(workspace, ['add', '--all'])
- await runGit(workspace, ['commit', '--quiet', '-m', message])
-}
-
-export async function initGitWorkspace(workspace) {
- await mkdir(workspace, { recursive: true })
- await runGit(workspace, ['init', '--quiet'])
- await runGit(workspace, ['config', 'user.name', 'Turn Rewind Test'])
- await runGit(workspace, ['config', 'user.email', 'turnrewind-test@localhost'])
- // Pin line-ending behavior so fixtures are deterministic on machines whose
- // Git for Windows system config sets core.autocrlf=true: checkout and add
- // then write and hash the exact bytes the test wrote.
- await runGit(workspace, ['config', 'core.autocrlf', 'false'])
- return workspace
-}
diff --git a/plugins/dsh-tauri-turnrewind/test/git-worktree.test.js b/plugins/dsh-tauri-turnrewind/test/git-worktree.test.js
deleted file mode 100644
index 498606fd..00000000
--- a/plugins/dsh-tauri-turnrewind/test/git-worktree.test.js
+++ /dev/null
@@ -1,105 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, gitRef, restorePath, stateAt } from '../lib/core/git-snapshot.js'
-import { commitAll, gitOutput, initGitWorkspace, runGit } from './git-test-utils.js'
-
-it('isolates linked worktrees of one repository into separate snapshot stores', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-worktree-test-'))
- const main = join(root, 'main')
- const linked = join(root, 'linked')
- try {
- await initGitWorkspace(main)
- await writeFile(join(main, 'shared.txt'), 'committed\n')
- await commitAll(main, 'initial')
- await runGit(main, ['worktree', 'add', '--quiet', linked, '-b', 'linked-branch'])
- await writeFile(join(linked, 'linked-only.txt'), 'linked\n')
-
- const data = join(root, 'data')
- const mainStore = createSnapshotStore(data, main)
- const linkedStore = createSnapshotStore(data, linked)
-
- // Two worktrees of one repository are two snapshot domains, not one.
- assert.notEqual(mainStore.repoDir, linkedStore.repoDir)
- assert.equal(mainStore.workspaceDir, resolve(main))
- assert.equal(linkedStore.workspaceDir, resolve(linked))
-
- const beforeStatus = await gitOutput(main, ['status', '--porcelain=v1', '-z'])
- const beforeLinkedStatus = await gitOutput(linked, ['status', '--porcelain=v1', '-z'])
- const mainHead = await gitOutput(main, ['rev-parse', 'HEAD'])
- const linkedHead = await gitOutput(linked, ['rev-parse', 'HEAD'])
- const mainBranch = await gitOutput(main, ['branch', '--show-current'])
- const mainRefs = await gitOutput(main, ['for-each-ref'])
-
- const mainSnap = await captureSnapshot(mainStore, 'refs/turnrewind/wt-main', 'main worktree')
- const linkedSnap = await captureSnapshot(linkedStore, 'refs/turnrewind/wt-linked', 'linked worktree')
-
- // Both private repos borrow objects from the same common object store.
- const mainAlternates = (await readFile(join(mainStore.repoDir, 'objects', 'info', 'alternates'), 'utf8')).trim()
- const linkedAlternates = (await readFile(join(linkedStore.repoDir, 'objects', 'info', 'alternates'), 'utf8')).trim()
- assert.equal(mainAlternates, linkedAlternates)
- assert.match(mainAlternates, /main[\\/]\.git[\\/]objects/)
-
- // Each ref exists only in its own snapshot repository.
- assert.ok(await gitRef(mainStore.repoDir, main, 'refs/turnrewind/wt-main'))
- assert.equal(await gitRef(linkedStore.repoDir, linked, 'refs/turnrewind/wt-main'), undefined)
- assert.ok(await gitRef(linkedStore.repoDir, linked, 'refs/turnrewind/wt-linked'))
- assert.equal(await gitRef(mainStore.repoDir, main, 'refs/turnrewind/wt-linked'), undefined)
-
- // The linked worktree's own file is captured only by its own store.
- assert.equal((await stateAt(linkedStore, linkedSnap.commit, 'linked-only.txt')).kind, 'file')
- assert.equal((await stateAt(mainStore, mainSnap.commit, 'linked-only.txt')).kind, 'absent')
-
- // Neither capture touched the user repository: same HEADs, refs and
- // porcelain status in both worktrees.
- assert.equal(await gitOutput(main, ['rev-parse', 'HEAD']), mainHead)
- assert.equal(await gitOutput(linked, ['rev-parse', 'HEAD']), linkedHead)
- assert.equal(await gitOutput(main, ['branch', '--show-current']), mainBranch)
- assert.equal((await gitOutput(linked, ['branch', '--show-current'])).trim(), 'linked-branch')
- assert.equal(await gitOutput(main, ['status', '--porcelain=v1', '-z']), beforeStatus)
- assert.equal(await gitOutput(linked, ['status', '--porcelain=v1', '-z']), beforeLinkedStatus)
- assert.equal(await gitOutput(main, ['for-each-ref']), mainRefs)
-
- // A session started inside a subdirectory of the linked worktree joins
- // that worktree's snapshot domain, not the main worktree's.
- await mkdir(join(linked, 'sub'))
- const subStore = createSnapshotStore(data, join(linked, 'sub'))
- assert.equal(subStore.repoDir, linkedStore.repoDir)
- assert.equal(subStore.workspaceDir, resolve(linked))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('captures and restores through alternates when the source objects are packed', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-worktree-packed-'))
- const main = join(root, 'main')
- const linked = join(root, 'linked')
- try {
- await initGitWorkspace(main)
- await writeFile(join(main, 'packed.txt'), 'packed content\n')
- await commitAll(main, 'initial')
- // Pack the source repository so the reused blobs live in packfiles, the
- // common real-world shape alternates have to read through.
- await runGit(main, ['gc', '--quiet', '--prune=now'])
- await runGit(main, ['worktree', 'add', '--quiet', linked, '-b', 'linked-branch'])
-
- const store = createSnapshotStore(join(root, 'data'), linked)
- const before = await captureSnapshot(store, 'refs/turnrewind/packed-before', 'before')
-
- await writeFile(join(linked, 'packed.txt'), 'changed\n')
- const after = await captureSnapshot(store, 'refs/turnrewind/packed-after', 'after', before.commit)
- assert.notEqual(before.commit, after.commit)
-
- // The baseline blob is the source's packed object, read through the
- // alternates link, and restorePath writes those exact bytes back.
- await restorePath(store, before.commit, 'packed.txt')
- assert.equal(await readFile(join(linked, 'packed.txt'), 'utf8'), 'packed content\n')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/guard.test.js b/plugins/dsh-tauri-turnrewind/test/guard.test.js
deleted file mode 100644
index c90ecdfb..00000000
--- a/plugins/dsh-tauri-turnrewind/test/guard.test.js
+++ /dev/null
@@ -1,102 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { homedir, tmpdir } from 'node:os'
-import { dirname, join, parse, resolve } from 'node:path'
-import { it } from 'vitest'
-import { createSnapshotStore, probeWorkspace } from '../lib/core/git-snapshot.js'
-import { isSystemSensitiveWorkspace } from '../lib/core/guard.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-it('refuses the home directory, its ancestors, and drive roots', () => {
- assert.equal(isSystemSensitiveWorkspace(homedir()), true)
- assert.equal(isSystemSensitiveWorkspace(dirname(homedir())), true)
- assert.equal(isSystemSensitiveWorkspace(parse(homedir()).root), true)
- assert.equal(isSystemSensitiveWorkspace(parse(tmpdir()).root), true)
-})
-
-it('refuses plain directories that are not Git worktrees', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-plain-'))
- try {
- await writeFile(join(root, 'a.txt'), 'a')
- const probe = probeWorkspace(root)
- assert.equal(probe.ok, false)
- assert.match(probe.reason, /TURNREWIND_GIT_REQUIRED/)
- assert.throws(
- () => createSnapshotStore(join(root, 'data'), root),
- /TURNREWIND_GIT_REQUIRED/,
- )
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('accepts an ordinary Git worktree', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-git-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'a')
- const probe = probeWorkspace(workspace)
- assert.equal(probe.ok, true)
- assert.equal(probe.workspaceDir, resolve(workspace))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('canonicalizes a session cwd below the worktree root to the Git root', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-subdir-'))
- const workspace = join(root, 'workspace')
- const nested = join(workspace, 'packages', 'app')
- try {
- await initGitWorkspace(workspace)
- await mkdir(nested, { recursive: true })
- await writeFile(join(nested, 'a.txt'), 'a')
-
- // A session started from a subdirectory still belongs to the one Git
- // worktree: it must not become a second snapshot domain.
- const probe = probeWorkspace(nested)
- assert.equal(probe.ok, true)
- assert.equal(probe.workspaceDir, resolve(workspace))
-
- const nestedStore = createSnapshotStore(join(root, 'data'), nested)
- const rootStore = createSnapshotStore(join(root, 'data'), workspace)
- assert.equal(nestedStore.repoDir, rootStore.repoDir)
- assert.equal(nestedStore.workspaceDir, resolve(workspace))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('reports the missing git executable instead of a misleading not-a-worktree reason', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-nogit-'))
- try {
- await writeFile(join(root, 'plain.txt'), 'x')
- const savedPath = process.env.PATH
- // An empty PATH makes the synchronous spawn fail with ENOENT, exactly
- // like a machine without git on PATH.
- process.env.PATH = ''
- try {
- const probe = probeWorkspace(root)
- assert.equal(probe.ok, false)
- assert.match(probe.reason, /TURNREWIND_GIT_UNAVAILABLE/)
- assert.throws(
- () => createSnapshotStore(join(root, 'data'), root),
- /TURNREWIND_GIT_UNAVAILABLE/,
- )
- }
- finally {
- process.env.PATH = savedPath
- }
- // With git back on PATH the same directory reports the ordinary reason.
- const probe = probeWorkspace(root)
- assert.equal(probe.ok, false)
- assert.match(probe.reason, /TURNREWIND_GIT_REQUIRED/)
- }
- 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.js
deleted file mode 100644
index 8305e77b..00000000
--- a/plugins/dsh-tauri-turnrewind/test/ledger.test.js
+++ /dev/null
@@ -1,456 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtemp, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { it } from 'vitest'
-import { claimPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, pruneConsumedNotices, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, 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-'))
- 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-session-1-before',
- })
- settleTurn(db, 'session:1', 'refs/turnrewind/turn-session-1-after')
- assert.equal(getTurn(db, 'session:1').status, 'settled')
- assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:1')
- assert.equal(getLatestSnapshotRef(db, 'workspace'), 'refs/turnrewind/turn-session-1-after')
-
- insertTurn(db, {
- turnId: 'session:2',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:01:00.000Z',
- beforeRef: 'refs/turnrewind/turn-session-2-before',
- })
- settleNoopTurn(db, 'session:2', 'refs/turnrewind/turn-session-2-after')
- assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:1')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('marks undo and queues its one-time notice atomically', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-undo-notice-test-'))
- const db = openLedger(root)
- try {
- insertTurn(db, {
- turnId: 'session:undo',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/undo-before',
- })
- settleTurn(db, 'session:undo', 'refs/turnrewind/undo-after')
- completeUndoWithNotice(db, 'session:undo', {
- noticeId: 'notice-undo',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:undo',
- paths: ['src/reverted.ts'],
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- assert.equal(getTurn(db, 'session:undo').status, 'undone')
- const notices = claimRewindNotices(db, 'session', 'workspace')
- assert.equal(notices.length, 1)
- assert.equal(notices[0].notice_id, 'notice-undo')
- assert.deepEqual(notices[0].paths, ['src/reverted.ts'])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('merges multiple pending rewind notices and delivers them once', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-test-'))
- const db = openLedger(root)
- try {
- queueRewindNotice(db, {
- noticeId: 'notice-one',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:1',
- paths: ['src/old.ts'],
- createdAt: '2026-01-01T00:00:00.000Z',
- })
- queueRewindNotice(db, {
- noticeId: 'notice-two',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:2',
- paths: ['src/new.ts'],
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- const notices = claimRewindNotices(db, 'session', 'workspace')
- assert.equal(notices.length, 2)
- assert.deepEqual(notices.map(notice => notice.notice_id), ['notice-one', 'notice-two'])
- assert.deepEqual(notices.map(notice => notice.turns), [['session:1'], ['session:2']])
- assert.deepEqual(notices.map(notice => notice.paths), [['src/old.ts'], ['src/new.ts']])
- assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('records a skipped turn with a single unsupported-workspace heads-up', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-skip-test-'))
- const db = openLedger(root)
- try {
- const turn = {
- sessionId: 'session',
- workspaceKey: 'c:\\users\\someone',
- startedAt: '2026-01-01T00:00:00.000Z',
- }
- recordSkippedTurn(db, { ...turn, turnId: 'session:1' }, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
- recordSkippedTurn(db, { ...turn, turnId: 'session:2' }, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
- assert.equal(getTurn(db, 'session:1').status, 'skipped')
- assert.equal(getTurn(db, 'session:2').status, 'skipped')
- const notices = claimRewindNotices(db, 'session', 'c:\\users\\someone')
- assert.equal(notices.length, 1)
- assert.equal(notices[0].kind, 'unsupported')
- assert.equal(notices[0].reason, 'TURNREWIND_WORKSPACE_UNSUPPORTED: home directory')
- assert.equal(claimRewindNotices(db, 'session', 'c:\\users\\someone').length, 0)
- recordSkippedTurn(db, { ...turn, turnId: 'session:3' }, 'TURNREWIND_WORKSPACE_TOO_LARGE: budget')
- assert.equal(db.prepare(`SELECT COUNT(*) AS count FROM rewind_notices WHERE kind = 'unsupported'`).get().count, 1)
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('merges a C-B-A undo sequence into one complete notice', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-cba-test-'))
- const db = openLedger(root)
- try {
- for (const [turnId, time] of [
- ['session:A', '2026-01-01T00:00:00.000Z'],
- ['session:B', '2026-01-01T00:01:00.000Z'],
- ['session:C', '2026-01-01T00:02:00.000Z'],
- ]) {
- insertTurn(db, {
- turnId,
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: time,
- beforeRef: `${turnId}-before`,
- })
- settleTurn(db, turnId, `${turnId}-after`)
- }
- for (const [turnId, path, time] of [
- ['session:C', 'c.ts', '2026-01-01T00:03:00.000Z'],
- ['session:B', 'b.ts', '2026-01-01T00:04:00.000Z'],
- ['session:A', 'a.ts', '2026-01-01T00:05:00.000Z'],
- ]) {
- completeUndoWithNotice(db, turnId, {
- noticeId: `notice-${turnId}`,
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: turnId,
- paths: [path],
- createdAt: time,
- })
- }
- const notices = claimRewindNotices(db, 'session', 'workspace')
- assert.deepEqual(notices.map(notice => notice.turns), [['session:C'], ['session:B'], ['session:A']])
- assert.deepEqual(notices.map(notice => notice.paths), [['c.ts'], ['b.ts'], ['a.ts']])
- assert.deepEqual(claimRewindNotices(db, 'session', 'workspace'), [])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('keeps an interrupted turn reversible when it captured file changes', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-interrupt-test-'))
- const db = openLedger(root)
- try {
- insertTurn(db, {
- turnId: 'session:settled',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/settled-before',
- })
- settleTurn(db, 'session:settled', 'refs/turnrewind/settled-after')
- insertTurn(db, {
- turnId: 'session:interrupted',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:01:00.000Z',
- beforeRef: 'refs/turnrewind/interrupted-before',
- })
- settleInterruptedTurn(
- db,
- 'session:interrupted',
- 'refs/turnrewind/interrupted-after',
- 'agent became idle after interruption',
- )
- assert.equal(getTurn(db, 'session:interrupted').status, 'interrupted')
- assert.equal(getTurn(db, 'session:interrupted').reversible, 1)
- assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('selects an interrupted turn after a later turn is undone', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-sequence-test-'))
- const db = openLedger(root)
- try {
- insertTurn(db, {
- turnId: 'session:interrupted',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/interrupted-before',
- })
- settleInterruptedTurn(db, 'session:interrupted', 'refs/turnrewind/interrupted-after', 'interrupted')
- insertTurn(db, {
- turnId: 'session:later',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:01:00.000Z',
- beforeRef: 'refs/turnrewind/later-before',
- })
- settleTurn(db, 'session:later', 'refs/turnrewind/later-after')
- completeUndoWithNotice(db, 'session:later', {
- noticeId: 'notice-later',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:later',
- paths: ['later.txt'],
- createdAt: '2026-01-01T00:02:00.000Z',
- })
- assert.equal(getLatestTurn(db, 'session', 'workspace').turn_id, 'session:interrupted')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-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('claims a pending plan exactly once and serializes cancel/apply outcomes', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-plan-claim-test-'))
- const db = openLedger(root)
- try {
- const planId = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'workspace',
- turnId: 'session:1',
- paths: ['a.txt'],
- })
- const first = claimPendingPlan(db, planId, 'session')
- assert.equal(first.ok, true)
- assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'applying')
- assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
- assert.equal(markPendingPlanCancelled(db, planId, 'session'), false)
-
- releasePendingPlanClaim(db, planId)
- assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'pending')
- const second = claimPendingPlan(db, planId, 'session')
- assert.equal(second.ok, true)
- markPendingPlanApplied(db, planId, 'session', 'applied once')
- assert.deepEqual(getPendingPlanStatus(db, planId, 'session'), { status: 'applied', resultText: 'applied once' })
- assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('fences applying operations as recovery-required on reopen', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-operation-recovery-test-'))
- const first = openLedger(root)
- insertTurn(first, {
- turnId: 'session:applying',
- sessionId: 'session',
- workspaceKey: 'workspace-recovery',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/applying-before',
- })
- settleTurn(first, 'session:applying', 'refs/turnrewind/applying-after')
- createOperation(first, {
- operationId: 'operation-applying',
- kind: 'undo',
- targetTurnId: 'session:applying',
- requestedAt: '2026-01-01T00:01:00.000Z',
- beforeRef: 'refs/turnrewind/operation-before',
- })
- first.close()
-
- const reopened = openLedger(root)
- try {
- const operation = reopened.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('operation-applying')
- assert.equal(operation.outcome, 'needs-recovery')
- assert.match(operation.error, /restarted while the operation was applying/u)
- assert.deepEqual(listNeedsRecoveryWorkspaces(reopened), ['workspace-recovery'])
- }
- finally {
- reopened.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)
- insertTurn(first, {
- turnId: 'session:active',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/active-before',
- })
- first.close()
- const reopened = openLedger(root)
- try {
- assert.equal(getTurn(reopened, 'session:active').status, 'abandoned')
- assert.equal(getTurn(reopened, 'session:active').reversible, 0)
- }
- finally {
- reopened.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('prunes only long-consumed notices and keeps the dedup rows', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-prune-'))
- try {
- const db = openLedger(root)
- db.exec('BEGIN')
- // Old consumed row (past the cutoff) and a fresh consumed row.
- db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
- VALUES ('old', 's1', 'ws1', 't1', '[]', '[]', 'undo', 'consumed', ?, ?)`).run('2020-01-01T00:00:00.000Z', '2020-01-01T00:00:01.000Z')
- db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at, claimed_at)
- VALUES ('fresh', 's2', 'ws1', 't2', '[]', '[]', 'undo', 'consumed', ?, ?)`).run(new Date().toISOString(), new Date().toISOString())
- // A pending row must survive regardless of age.
- db.prepare(`INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, status, created_at)
- VALUES ('pending', 's3', 'ws1', 't3', '[]', '[]', 'unsupported', 'pending', '2020-01-01T00:00:00.000Z')`).run()
- db.exec('COMMIT')
-
- db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
- const removed = pruneConsumedNotices(db)
- assert.equal(removed, 1)
- const survivors = db.prepare('SELECT notice_id FROM rewind_notices ORDER BY notice_id').all().map(row => row.notice_id)
- assert.deepEqual(survivors, ['fresh', 'pending'])
- db.exec('PRAGMA wal_checkpoint(TRUNCATE)')
- db.close()
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
deleted file mode 100644
index 6867fd21..00000000
--- a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js
+++ /dev/null
@@ -1,214 +0,0 @@
-import assert from 'node:assert/strict'
-import { 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 { captureSnapshot, createSnapshotStore } from '../lib/core/git-snapshot.js'
-import { getTurn, insertTurn, openLedger, settleTurn } from '../lib/core/ledger.js'
-import { applyUndo, waitForTurnBaseline } from '../lib/index.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-async function setupTurn() {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-lifecycle-test-'))
- const workspace = join(root, 'workspace')
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'v1\n')
- const db = openLedger(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- 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')
- 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 }
-}
-
-/** Bare /undo now parks a pending plan; execute it like the ✓ button would. */
-async function undoWithConfirm(runtime, active, invocation) {
- const preview = await applyUndo(runtime, active, invocation())
- assert.equal(preview.kind, 'success')
- const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]
- assert.ok(planId, 'preview must carry a pending plan id')
- return applyUndo(runtime, active, invocation(`--confirm ${planId}`))
-}
-
-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', { timeout: 30000 }, async () => {
- const { root, workspace, db, runtime, active, invocation } = await setupTurn()
- try {
- const undo = await undoWithConfirm(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 undoWithConfirm(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 undoWithConfirm(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 })
- }
-})
-
-it('waits for a claimed turn baseline before allowing the next step', async () => {
- let release
- const baseline = new Promise((resolvePromise) => {
- release = resolvePromise
- })
- const active = new Map([
- ['session:7', { baseline: { promise: baseline } }],
- ])
- const controller = new AbortController()
- let continued = false
- const waiting = waitForTurnBaseline(active, 'session', 7, controller.signal).then((result) => {
- continued = true
- assert.equal(result.ok, true)
- })
-
- await Promise.resolve()
- assert.equal(continued, false)
- release({ ok: true })
- await waiting
- assert.equal(continued, true)
-})
-
-it('unblocks an aborted pre-step without cancelling baseline bookkeeping', async () => {
- let release
- const baseline = new Promise((resolvePromise) => {
- release = resolvePromise
- })
- const active = new Map([
- ['session:8', { baseline: { promise: baseline } }],
- ])
- const controller = new AbortController()
- const waiting = waitForTurnBaseline(active, 'session', 8, controller.signal)
- controller.abort(new Error('turn interrupted'))
- await assert.rejects(waiting, /turn interrupted/u)
-
- let baselineCompleted = false
- const bookkeeping = baseline.then((result) => {
- baselineCompleted = result.ok
- })
- release({ ok: true })
- await bookkeeping
- assert.equal(baselineCompleted, true)
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/maintenance.test.js b/plugins/dsh-tauri-turnrewind/test/maintenance.test.js
deleted file mode 100644
index b9fc4405..00000000
--- a/plugins/dsh-tauri-turnrewind/test/maintenance.test.js
+++ /dev/null
@@ -1,167 +0,0 @@
-import assert from 'node:assert/strict'
-import { existsSync } from 'node:fs'
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, workspaceHash, workspaceKey } from '../lib/core/git-snapshot.js'
-import { createOperation, createPendingPlan, getTurn, insertTurn, openLedger, queueRewindNotice, registerWorkspace, settleTurn } from '../lib/core/ledger.js'
-import { purgeWorkspace } from '../lib/core/maintenance.js'
-import { commitAll, gitOutput, initGitWorkspace } from './git-test-utils.js'
-
-it('purges ledger rows and the snapshot repository for one workspace', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-purge-test-'))
- const workspace = join(root, 'ws')
- const workspaceKey = resolve(workspace).toLowerCase()
- try {
- const db = openLedger(root)
- registerWorkspace(db, workspaceKey, workspace, join(root, 'snapshots', 'x.git'))
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey,
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/turn-session-1-before',
- })
- settleTurn(db, 'session:1', 'refs/turnrewind/turn-session-1-after')
- createOperation(db, {
- operationId: 'op-1',
- kind: 'undo',
- targetTurnId: 'session:1',
- requestedAt: '2026-01-01T00:01:00.000Z',
- })
- queueRewindNotice(db, {
- noticeId: 'notice-1',
- sessionId: 'session',
- workspaceKey,
- targetTurnId: 'session:1',
- paths: ['a.txt'],
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- db.close()
-
- const repoDir = join(root, 'snapshots', `${workspaceHash(workspace)}.git`)
- await mkdir(join(repoDir, 'objects'), { recursive: true })
- await writeFile(join(repoDir, 'HEAD'), 'ref: refs/heads/main\n')
-
- const summary = purgeWorkspace(root, workspace)
- assert.equal(summary.repoExisted, true)
- assert.deepEqual(summary.ledger, { operations: 1, notices: 1, plans: 0, turns: 1, workspaces: 1 })
- assert.equal(existsSync(repoDir), false)
-
- const verify = openLedger(root)
- try {
- assert.equal(getTurn(verify, 'session:1'), undefined)
- assert.equal(verify.prepare('SELECT COUNT(*) AS count FROM operations').get().count, 0)
- assert.equal(verify.prepare('SELECT COUNT(*) AS count FROM rewind_notices').get().count, 0)
- assert.equal(verify.prepare('SELECT COUNT(*) AS count FROM workspaces').get().count, 0)
- }
- finally {
- verify.close()
- }
-
- const repeat = purgeWorkspace(root, workspace)
- assert.equal(repeat.repoExisted, false)
- assert.deepEqual(repeat.ledger, { operations: 0, notices: 0, plans: 0, turns: 0, workspaces: 0 })
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('purges only turnrewind data; the user repository and other workspaces stay intact', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-purge-safety-'))
- const dataRoot = join(root, 'dsh-home')
- const userProject = join(root, 'user-project')
- const otherProject = join(root, 'other-project')
- try {
- await initGitWorkspace(userProject)
- await initGitWorkspace(otherProject)
- await writeFile(join(userProject, 'tracked.txt'), 'v1\n')
- await commitAll(userProject, 'initial')
- const userHead = await gitOutput(userProject, ['rev-parse', 'HEAD'])
- const userStatus = await gitOutput(userProject, ['status', '--porcelain=v1', '-z'])
-
- const userStore = createSnapshotStore(dataRoot, userProject)
- await captureSnapshot(userStore, 'refs/turnrewind/purge-before', 'before')
- const otherStore = createSnapshotStore(dataRoot, otherProject)
- await captureSnapshot(otherStore, 'refs/turnrewind/other-before', 'other')
-
- const db = openLedger(dataRoot)
- registerWorkspace(db, workspaceKey(userProject), userProject, userStore.repoDir)
- registerWorkspace(db, workspaceKey(otherProject), otherProject, otherStore.repoDir)
- insertTurn(db, {
- turnId: 'user-session:1',
- sessionId: 'user-session',
- workspaceKey: workspaceKey(userProject),
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/purge-before',
- })
- db.close()
-
- const summary = purgeWorkspace(dataRoot, userProject)
- assert.equal(summary.repoExisted, true)
- assert.deepEqual(summary.ledger, { operations: 0, notices: 0, plans: 0, turns: 1, workspaces: 1 })
- assert.equal(existsSync(userStore.repoDir), false)
-
- // The user's repository is completely untouched: .git directory, HEAD,
- // porcelain status and worktree files all survive the purge.
- assert.equal(existsSync(join(userProject, '.git')), true)
- assert.equal(await gitOutput(userProject, ['rev-parse', 'HEAD']), userHead)
- assert.equal(await gitOutput(userProject, ['status', '--porcelain=v1', '-z']), userStatus)
- assert.equal(await readFile(join(userProject, 'tracked.txt'), 'utf8'), 'v1\n')
-
- // The purge removed exactly this workspace's data; the other workspace's
- // snapshot repository and ledger rows survive.
- assert.equal(existsSync(otherStore.repoDir), true)
- const verify = openLedger(dataRoot)
- try {
- assert.equal(verify.prepare('SELECT COUNT(*) AS count FROM workspaces').get().count, 1)
- assert.equal(verify.prepare('SELECT COUNT(*) AS count FROM turns').get().count, 0)
- }
- finally {
- verify.close()
- }
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('purges pending plans bound to the workspace', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-purge-plans-'))
- const workspace = join(root, 'ws')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'a')
- const db = openLedger(root)
- createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: workspaceKey(workspace),
- turnId: 'session:1',
- paths: ['a.txt'],
- })
- createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: workspaceKey(join(root, 'other')),
- turnId: 'session:2',
- paths: ['b.txt'],
- })
- db.close()
-
- const summary = purgeWorkspace(root, workspace)
- assert.deepEqual(summary.ledger, { operations: 0, notices: 0, plans: 1, turns: 0, workspaces: 0 })
-
- const verify = openLedger(root)
- try {
- const remaining = verify.prepare('SELECT workspace_key FROM pending_plans').all().map(row => row.workspace_key)
- assert.deepEqual(remaining, [workspaceKey(join(root, 'other'))])
- }
- finally {
- verify.close()
- }
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/oversize.test.js b/plugins/dsh-tauri-turnrewind/test/oversize.test.js
deleted file mode 100644
index 0ed7c8c1..00000000
--- a/plugins/dsh-tauri-turnrewind/test/oversize.test.js
+++ /dev/null
@@ -1,120 +0,0 @@
-import assert from 'node:assert/strict'
-import { Buffer } from 'node:buffer'
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join, resolve } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restorePath, stateAt } from '../lib/core/git-snapshot.js'
-import { insertTurn, openLedger, settleTurn } from '../lib/core/ledger.js'
-import { applyUndo } from '../lib/index.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-// 64 MiB + 1 byte: the smallest blob over the restore limit. The buffer is
-// mostly zeros so compression keeps the fixture cheap, but the blob size
-// still crosses the line.
-const OVER_LIMIT_BYTES = 64 * 1024 * 1024 + 1
-
-async function undoWithConfirm(runtime, active, invocation) {
- const preview = await applyUndo(runtime, active, invocation(''))
- assert.equal(preview.kind, 'success')
- const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]
- assert.ok(planId, 'preview must carry a pending plan id')
- return applyUndo(runtime, active, invocation(`--confirm ${planId}`))
-}
-
-it('reports oversized blobs instead of failing the whole preview', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-oversize-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'small.txt'), 'small\n')
- // A >64 MiB file: sparse so the fixture stays fast, content only at the end.
- const big = Buffer.alloc(OVER_LIMIT_BYTES)
- big.write('payload at the end', OVER_LIMIT_BYTES - 20)
- await writeFile(join(workspace, 'big.bin'), big)
-
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/size-before', 'before')
-
- // stateAt surfaces the limit as a kind, not an exception: the plan can
- // keep listing other files and mark this one.
- assert.equal((await stateAt(store, before.commit, 'small.txt')).kind, 'file')
- assert.equal((await stateAt(store, before.commit, 'big.bin')).kind, 'tooLarge')
-
- // restorePath fails for the oversized entry alone...
- await assert.rejects(
- () => restorePath(store, before.commit, 'big.bin'),
- /TURNREWIND_FILE_TOO_LARGE/,
- )
- // ...while other paths in the same commit keep restoring normally.
- await writeFile(join(workspace, 'small.txt'), 'changed\n')
- await restorePath(store, before.commit, 'small.txt')
- assert.equal(await readFile(join(workspace, 'small.txt'), 'utf8'), 'small\n')
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('undoes the other files while reporting the oversized one as not restored', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-oversize-undo-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'small.txt'), 'before\n')
- const big = Buffer.alloc(OVER_LIMIT_BYTES)
- big.write('payload at the end', OVER_LIMIT_BYTES - 20)
- await writeFile(join(workspace, 'big.bin'), big)
-
- const db = openLedger(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- await captureSnapshot(store, 'refs/turnrewind/o1-before', 'before')
-
- // The turn modifies both files; the plan must show the oversize flag.
- await writeFile(join(workspace, 'small.txt'), 'after\n')
- await writeFile(join(workspace, 'big.bin'), big.subarray(0, OVER_LIMIT_BYTES - 1))
- await captureSnapshot(store, 'refs/turnrewind/o1-after', 'after', 'refs/turnrewind/o1-before')
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: resolve(workspace).toLowerCase(),
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/o1-before',
- })
- settleTurn(db, 'session:1', 'refs/turnrewind/o1-after')
-
- const runtime = {
- db,
- store,
- workspaceKey: resolve(workspace).toLowerCase(),
- parentRef: 'refs/turnrewind/o1-after',
- undoing: false,
- }
- const invocation = (rawInput = '') => ({
- rawInput,
- agent: { session: { id: 'session', header: { cwd: workspace } } },
- })
-
- const preview = await applyUndo(runtime, new Map(), invocation(''))
- assert.equal(preview.kind, 'success')
- assert.match(preview.text, /big\.bin \[too large\]/u)
- assert.match(preview.text, /Oversized files \(over the 64 MB restore limit\)/u)
-
- const result = await undoWithConfirm(runtime, new Map(), invocation)
- assert.equal(result.kind, 'success')
- // The normal file came back; the oversized one failed per-path.
- assert.match(result.text, /restored 1 file\(s\)/u)
- assert.match(result.text, /Not restored \(1 file\(s\)\): big\.bin \(over the size limit\)/u)
- assert.equal(await readFile(join(workspace, 'small.txt'), 'utf8'), 'before\n')
- // The oversized file on disk is untouched (still the turn's output).
- assert.equal((await readFile(join(workspace, 'big.bin'))).length, OVER_LIMIT_BYTES - 1)
-
- // The turn is settled as undone and the ledger's operation completed.
- const row = db.prepare('SELECT status FROM turns WHERE turn_id = ?').get('session:1')
- assert.equal(row.status, 'undone')
- db.close()
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/planner.test.js b/plugins/dsh-tauri-turnrewind/test/planner.test.js
deleted file mode 100644
index 101b7eab..00000000
--- a/plugins/dsh-tauri-turnrewind/test/planner.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { aggregatePathPlan, classifyUndo, collectDescendantTurns } from '../lib/core/planner.js'
-
-it('collects a selected turn subtree in leaf-first order', () => {
- const root = { turn_id: 'p' }
- const children = new Map([
- ['p', [{ turn_id: 'a' }, { turn_id: 'c' }]],
- ['a', [{ turn_id: 'b' }]],
- ['c', []],
- ['b', []],
- ])
- assert.deepEqual(collectDescendantTurns(root, children).map(turn => turn.turn_id), ['b', 'a', 'c', 'p'])
-})
-
-it('aggregates paths without duplicating overlapping files', () => {
- const turns = [{ turn_id: 'b' }, { turn_id: 'a' }]
- const paths = new Map([
- ['b', ['src/a.ts', 'src/b.ts']],
- ['a', ['src/a.ts']],
- ])
- assert.deepEqual(aggregatePathPlan(turns, turn => paths.get(turn.turn_id)).map(entry => entry.path), ['src/a.ts', 'src/b.ts'])
-})
-
-it('classifies stale content as a conflict', () => {
- assert.equal(classifyUndo({ kind: 'file', digest: 'same' }, { kind: 'file', digest: 'same' }), 'safe')
- assert.equal(classifyUndo({ kind: 'file', digest: 'new' }, { kind: 'file', digest: 'old' }), 'conflict')
- assert.equal(classifyUndo({ kind: 'absent', digest: null }, { kind: 'file', digest: 'old' }), 'conflict')
-})
diff --git a/plugins/dsh-tauri-turnrewind/test/security.test.js b/plugins/dsh-tauri-turnrewind/test/security.test.js
deleted file mode 100644
index ef53c6c6..00000000
--- a/plugins/dsh-tauri-turnrewind/test/security.test.js
+++ /dev/null
@@ -1,156 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readdir, rm, symlink, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, currentState, restorePath, stateAt } from '../lib/core/git-snapshot.js'
-import { initGitWorkspace } from './git-test-utils.js'
-
-it('delegates secret-file exclusion to the source repository ignore rules', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-secret-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, '.gitignore'), [
- '.env',
- 'credentials.json',
- 'secrets.yaml',
- 'server.pem',
- 'config/credentials.json',
- 'nested/secrets.yaml',
- '',
- ].join('\n'))
- await writeFile(join(workspace, '.env'), 'TOKEN=do-not-store')
- await writeFile(join(workspace, 'credentials.json'), '{"token":"do-not-store"}')
- await writeFile(join(workspace, 'secrets.yaml'), 'key: do-not-store')
- await writeFile(join(workspace, 'server.pem'), '-----BEGIN')
- await writeFile(join(workspace, 'unignored.pem'), '-----BEGIN UNIGNORED')
- await writeFile(join(workspace, 'safe.txt'), 'safe')
- await mkdir(join(workspace, 'config'), { recursive: true })
- await mkdir(join(workspace, 'nested'), { recursive: true })
- await writeFile(join(workspace, 'config', 'credentials.json'), '{"token":"nested-do-not-store"}')
- await writeFile(join(workspace, 'nested', 'secrets.yaml'), 'key: nested-do-not-store')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/security', 'security')
-
- // Git mode dropped the hardcoded secret-name rules: the source repo's own
- // ignore rules decide what a snapshot contains. An unignored secret-named
- // file is deliberately captured — the project opted in by not ignoring it.
- assert.equal((await stateAt(store, snapshot.commit, '.env')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'credentials.json')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'secrets.yaml')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'server.pem')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'config/credentials.json')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'nested/secrets.yaml')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'unignored.pem')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'safe.txt')).kind, 'file')
- const snapshotFiles = await readdir(join(root, 'data', 'snapshots'))
- assert.equal(snapshotFiles.length, 1)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('keeps legitimate source files whose names resemble secrets', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-token-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await mkdir(join(workspace, 'src'), { recursive: true })
- await mkdir(join(workspace, 'docs'), { recursive: true })
- await writeFile(join(workspace, 'src', 'token.ts'), 'export const token = 1')
- await writeFile(join(workspace, 'src', 'tokenizer.py'), 'def tokenize(): pass')
- await writeFile(join(workspace, 'src', 'secret_manager.js'), 'export const hide = 1')
- await writeFile(join(workspace, 'docs', 'credentials.module.ts'), 'export const config = 1')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/token-source', 'token source')
-
- // These were silently excluded by the old *token*/*secret*/credentials*
- // globs, so undo could never restore them and the dry-run never showed them.
- assert.equal((await stateAt(store, snapshot.commit, 'src/token.ts')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'src/tokenizer.py')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'src/secret_manager.js')).kind, 'file')
- assert.equal((await stateAt(store, snapshot.commit, 'docs/credentials.module.ts')).kind, 'file')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('excludes abandoned turnrewind temporary files from snapshots', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-temp-file-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await mkdir(join(workspace, 'nested'), { recursive: true })
- await writeFile(join(workspace, 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp'), 'temporary')
- await writeFile(join(workspace, 'nested', 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp'), 'temporary')
- await writeFile(join(workspace, 'kept.txt'), 'kept')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/temp-files', 'temp files')
- assert.equal((await stateAt(store, snapshot.commit, 'file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'nested/file.turnrewind-01234567-89ab-cdef-0123-456789abcdef.tmp')).kind, 'absent')
- assert.equal((await stateAt(store, snapshot.commit, 'kept.txt')).kind, 'file')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('refuses dangling symlink workspace paths during inspection and restore', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-dangling-link-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- try {
- await symlink(join(root, 'missing-target'), join(workspace, 'dangling'))
- }
- catch (error) {
- if (error.code === 'EPERM' || error.code === 'EACCES')
- return
- throw error
- }
- const store = createSnapshotStore(join(root, 'data'), workspace)
- assert.throws(() => currentState(workspace, 'dangling'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
- await assert.rejects(
- () => restorePath(store, 'refs/turnrewind/missing', 'dangling'),
- /TURNREWIND_SYMLINK_UNSUPPORTED/,
- )
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('refuses symlinked workspace paths during inspection and restore', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-test-'))
- const workspace = join(root, 'workspace')
- const outside = join(root, 'outside')
- try {
- await initGitWorkspace(workspace)
- await mkdir(outside, { recursive: true })
- await writeFile(join(outside, 'secret.txt'), 'outside')
- try {
- await symlink(outside, join(workspace, 'linked'))
- }
- catch (error) {
- if (error.code === 'EPERM' || error.code === 'EACCES')
- return
- throw error
- }
- const store = createSnapshotStore(join(root, 'data'), workspace)
- assert.throws(() => currentState(workspace, 'linked/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/symlink', 'symlink')
- // The snapshot stores the link itself; paths below it are never tracked.
- assert.equal((await stateAt(store, snapshot.commit, 'linked/secret.txt')).kind, 'absent')
- // Restore refuses to traverse or replace a symlinked path.
- await assert.rejects(
- () => restorePath(store, snapshot.commit, 'linked/secret.txt'),
- /TURNREWIND_SYMLINK_UNSUPPORTED/,
- )
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/plugins/dsh-tauri-turnrewind/vitest.config.js b/plugins/dsh-tauri-turnrewind/vitest.config.js
deleted file mode 100644
index b5e21240..00000000
--- a/plugins/dsh-tauri-turnrewind/vitest.config.js
+++ /dev/null
@@ -1,10 +0,0 @@
-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: 120000,
- },
-})