Skip to content

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

feat(turnrewind): open files in the sidebar on the new kernel, stay silent on the old one

hairyff93c64b099d7
diff --git a/archiving/dsh-tauri-turnrewind-ts/README.md b/archiving/dsh-tauri-turnrewind-ts/README.md
deleted file mode 100644
index 658dc90d..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/README.md
+++ /dev/null
@@ -1,380 +0,0 @@
-# dsh-tauri-turnrewind
-
-本地开发中的 DSH turn 回滚插件(**TypeScript 重写版**,位于 `packages/`,遵循 workspace 插件规范;旧 JS 版已移除)。
-
-> **分发(2026-09-06 起)**:插件已随桌面构建打包——列入 `dsh-tauri-bundle` 依赖(构建期部署进 `src-tauri/resources/node_modules/`)与 `src-tauri/resources/internal-plugins.json` 预装清单,**下载桌面版即装即用,无需任何手动配置**。定位仍是实验功能:恢复路径直接使用 Node/Git,尚未接入受控的宿主 sandbox/Tauri bridge,请在可丢弃的工作区先行试用。
->
-> **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`。
-
-## 当前状态
-
-这是 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 链互相污染。同步开销已收敛:工作区解析合并为**单次 rev-parse 子进程**并带 60s 缓存(过期后先回缓存值、后台异步刷新),冲突检测的文件读取(上限 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`,不再做全目录预算扫描(见「工作区资格」);
-- **不可用弹窗**:客户端半(`src/client/`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、跟随应用主题)。**单会话只报一次**:提示以会话内消息形式永久留档可查,弹窗只对页面存活期间新到达的提示触发,历史提示(重启后重新进入会话)不会重复弹窗;
-- **两阶段 `/undo`**:先出预览卡(红绿 diff + `+x -y` 徽标 + 文件清单),卡内 ✓/✗ 按钮确认执行或取消——不看预览就不会误执行;计划 5 分钟过期。**过期与取消都只锁执行、不抹账本记录**:过期的 plan 卡片保留文件清单与 diff 供随时回看(归档视图);取消的 plan 是用户主动放弃,卡片塌缩为一行「已取消」留痕。确认时二次校验磁盘与预览绑定;
-- 恢复前比较当前文件与 turn 完成时的快照,发现变化则拒绝覆盖,并给出「turn 产物 → 当前磁盘」的冲突 diff;
-- 冲突可用 `--skip-conflicts`(只恢复无冲突文件)或 `--force`(强制覆盖)直接执行;
-- `/undo --redo`(重做最近一次已应用的 undo)**已禁用**:入口在解析层直接拒绝,底层恢复路径加固代码保留但未开放(见「已禁用:redo」);
-- 注册人类命令 `/undo`;
-- `/undo` 默认处理当前会话最新的单个可恢复 turn,也可指定完整 turn ID;
-- 同一 workspace 的活动 turn 或 undo 操作互斥;
-- 插件重启时将未完成 turn 标记为 abandoned;未完成的 **Undo 与 Redo** operation 会标记为 `needs-recovery`,对应 workspace 在清理前拒绝新的 rewind 操作,避免未知磁盘状态被继续覆盖。**恢复面板**:不可用弹窗在 reason 命中恢复围栏时提供「打开恢复面板」入口,可查看被围 workspace 的中断操作明细,并选择「已检查,保留历史并解锁」(operation 转 recovery-acknowledged 终态)或「清除 rewind 数据并解锁」(等价 purge);
-- `/undo --doctor`:只读诊断——git 可用性、工作区资格、账本规模与围栏、快照仓库健康(refs / alternates)、最近 turn 状态、备份新旧;
-- 账本打开时执行 `PRAGMA quick_check`(损坏显式拒绝加载,`TURNREWIND_LEDGER_CORRUPT`),并每日滚动备份到 `ledger.sqlite.bak`(`VACUUM INTO` 一致性快照),损坏时可按「还原 .bak → 重启」恢复;
-- 每次 Undo 的回退提示独立持久化;下一次模型 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 --cancel <plan-id> # 取消一个待确认的预览计划
-/undo --doctor # 只读诊断报告(不能与其他选项组合)
-```
-
-当前不支持 / 已禁用:
-
-```text
-/undo --redo # 已禁用(功能冻结),入口直接拒绝
-/undo --subtree # 未实现
-```
-
-父对话递归撤销、消息旁 Undo 按钮和设置页模式切换尚未实现。
-
-## 工作区资格(Git-only)
-
-曾有用户在 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 各自成域。
-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` 会话投影(`src/host/service/dialog-projection.ts`)把提示折叠进会话列表快照,客户端半(`src/client/register/dialog.ts`)从 `sessions.list` 的 `projectionValues.turnrewind` 读到后弹出模态对话框。去重不在浏览器存储里做(localStorage 会因换端口/清存储丢「已读」):按「单会话一次」种子逻辑,进入会话时已存在的提示视为历史留档(会话内消息永久可见)不弹,只有页面存活期间新到达的提示弹一次。
-
-- **敏感文件提醒**:会话首次追踪一个工作区时做一次浅层启发式扫描(根 + 两层、上限 500 文件、跳过 node_modules),命中 `.env`/密钥类且**未被 ignore** 的文件时发一条一次性 `[Turn rewind privacy notice]`(每会话+工作区一条),列出会被快照的具体文件与退出方式(加 ignore)。扫描失败静默跳过——这是提醒,不是门禁。
-大工作区的取舍:不再做预算预扫描,快照耗时与磁盘占用随仓库规模增长(Git ignore 能排除 `node_modules` 等,但容量/性能风险仍由使用者自行承担);单文件快照/恢复上限为 64 MB——超限文件仍会被捕获进快照,`/undo` 预览会以 `[too large]` 标注并在执行后单文件报告为「未恢复」,**不会**导致整次 undo 失败,其余文件照常恢复。若项目里有此类大文件且不希望被追踪,请把它们加进源仓库的 ignore 规则。
-
-### 清理已膨胀的快照数据
-
-如果某个工作区在旧版本下已经生成过巨大快照,先停止 DSH Host 进程,再执行:
-
-```powershell
-node packages\dsh-tauri-turnrewind-ts\purge-workspace.mjs "C:\Users\<user>\Desktop\test" # release 数据目录 ~/.dsh
-node packages\dsh-tauri-turnrewind-ts\purge-workspace.mjs "C:\Users\<user>\Desktop\test" --home "$env:USERPROFILE\.dsh.dev" # debug
-```
-
-(需先 `pnpm --filter dsh-tauri-turnrewind build` 产出 `dist/`——CLI 从构建产物导入引擎。)
-
-该命令删除该工作区对应的私有快照仓库(`$DSH_HOME/snapshots/<hash>.git`)及其全部账本记录(turns / operations / notices / plans / workspaces),其他工作区的数据不受影响。workspace 被运行中的 Host 占用时命令会拒绝执行(workspace lock),请先停止对应 Host 进程。
-
-注意:这个 CLI 只在两种场景需要——①账本损坏前的彻底清理,②命令行批量操作。**解除恢复围栏的日常路径已产品化**:在「打开恢复面板」里选「清除 rewind 数据并解锁」即可(同一 purge 逻辑、同一把 workspace 锁,占用时在 UI 内报 409),见「当前状态」的恢复面板条目。
-
-## 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` 的文件清单里核对实际被追踪的范围。插件仍是实验原型,不应把它当作秘密信息保护工具。
-
-辅助提示:会话首次追踪一个工作区时,插件会对未被 ignore 的疑似秘密文件发一次性 `[Turn rewind privacy notice]`(见「工作区资格」的敏感文件提醒)——它是提醒而非保护。
-
-### 已禁用:redo(功能冻结)
-
-`/undo --redo` 已在解析层禁用:任何包含 `--redo` 的输入都会得到「temporarily disabled」错误,不会触发快照校验或文件恢复。
-
-禁用原因(2026-09-03 审查报告 P0-4):redo 的执行段此前未接入 operation 记录与失败回滚,执行中任一文件恢复失败会留下「部分 redo」状态,无 `needs-recovery` 围栏。
-
-底层加固已经完成并保留(未开放):redo 现在与 undo 共用同一套机制——`createOperation` 登记 applying operation → 单路径失败计入 `notRestored` 明细 → `completeRedoTransaction` 在单事务内结算旧 undo operation / turn / 新 operation / notice,事务失败时 redo operation 落 `needs-recovery` 由启动围栏拦截。重新开放只需移除 `applyUndo` 中的 redo 冻结闸门(`parsed.redo` 分支)并恢复对应测试。
-
-## Debug 安装
-
-TS 版插件位于 `packages/dsh-tauri-turnrewind-ts`,构建产物在 `dist/`。在当前 checkout 中执行:
-
-```powershell
-pnpm install
-pnpm --filter dsh-tauri-turnrewind build
-pnpm --filter dsh-tauri-turnrewind test
-```
-
-插件通过 `pnpm add` / `dsh plugin add` 安装(debug 桌面端启动时会自动以 `link:` 方式安装全部内部插件)。修改 Host 代码后需要重新 `pnpm --filter dsh-tauri-turnrewind build` 并重启 DSH debug Host 进程;修改 Client 代码后同理(client bundle 在 Host 启动时发现)。
-
-**发布分发**:仓库根的 `pnpm build`(prebuild → `build:plugins`)会把本插件的 `dist/` 部署进 `src-tauri/resources/node_modules/`,安装包启动时按 `internal-plugins.json` 自动预装并激活——终端用户无需 `pnpm`/构建/任何配置。
-
-## 测试
-
-运行插件 lint 与测试:
-
-```powershell
-pnpm --filter dsh-tauri-turnrewind exec eslint src test
-pnpm --filter dsh-tauri-turnrewind typecheck
-pnpm --filter dsh-tauri-turnrewind test
-```
-
-当前 25 个测试文件、130 个测试,覆盖:Git 快照(增删改恢复、中文路径、CRLF、路径逃逸、工作区根拒绝、absent 路径上的非空目录拒绝与空目录移除、symlink 路径拒绝与快照 symlink 策略、ignore 委托、alternates 复用与自愈)、原子 bak-swap 恢复与崩溃清扫、Git 状态零污染(HEAD/branch/index/status/refs/stash 不变)、linked worktree 隔离、oversized blob 单文件报告、容量治理(保留条数过期、超限两阶段重建、不可达 loose object 回收)、账本生命周期(含 needs-recovery 围栏与跨连接 notice 单次消费、legacy schema 迁移重放、quick_check 拒载与 .bak 还原、恢复面板明细与 acknowledge 终态)、`/undo --doctor` 报告、pending plan 原子 claim 与预览绑定漂移校验、interrupted turn、barrier 时序、跨进程 workspace 锁、undo 入口与 redo 冻结、client 纯函数(输出解析/plan 状态判定/会话归属/通道 latest-owner-wins 语义/模态 Escape 与焦点陷阱)、敏感文件扫描过滤与提醒去重。
-
-## 当前限制
-
-这是实验性版本,正式启用前仍需要:
-
-- 接入受控的宿主 sandbox/Tauri bridge;
-- 完成真实 DSH lifecycle integration tests;
-- 容量治理为两级粗粒度策略(保留条数过期 + 超限整仓重建 + 不可达 loose object 回收),尚未做按 turn 的细粒度 ref 清理;
-- 实现父对话递归 undo;
-- 实现消息旁 Undo 按钮;
-- 明确重命名与特殊文件(submodule、设备文件)策略(symlink 与 mode/权限位已落地:mode 进快照状态、POSIX 下恢复可执行位,Windows 按 git filemode=false 约定统一 100644);
-- 设置面(retention / TTL / 逐 workspace 开关)尚未提供,调优走 `TURNREWIND_RETAIN_TURNS` / `TURNREWIND_MAX_SNAPSHOT_MB` 环境变量;
-- 重新开放 redo:移除解析层禁用分支、恢复端到端 redo 测试(底层加固已完成,见「已禁用:redo」)。
-
-### 符号链接策略(P1-3)
-
-- 工作区内指向外部的 symlink 路径:从不遍历、从不写入(`TURNREWIND_SYMLINK_UNSUPPORTED`);
-- 快照中记录的 symlink 条目(git mode `120000`):`stateAt` 报告为 `unsupported`,预览卡与 dry-run 标注 `[unsupported]` 并单独列出;undo 执行时跳过该路径并计入「未恢复」清单,绝不把 link target 文本伪装成普通文件写回;`restorePath` 内有同规则双保险;
-- turn 把 symlink 替换为普通文件(或反向)时,类型变化按 modified 处理;含 symlink 的 undo 结果中该文件始终出现在「未恢复」明细与 notice 里,需要用户手工重建。
diff --git a/archiving/dsh-tauri-turnrewind-ts/cordis.patch.yml b/archiving/dsh-tauri-turnrewind-ts/cordis.patch.yml
deleted file mode 100644
index c9db8a21..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/cordis.patch.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-# Mount row for dsh-tauri-turnrewind: installs the /undo command, the undo
-# card, and the in-app recovery panel into a DSH profile.
-- insert:
- - id: turnrewind
- name: dsh-tauri-turnrewind
diff --git a/archiving/dsh-tauri-turnrewind-ts/package.json b/archiving/dsh-tauri-turnrewind-ts/package.json
deleted file mode 100644
index f79afa9b..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/package.json
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "name": "dsh-tauri-turnrewind",
- "type": "module",
- "version": "0.3.1",
- "description": "Local turn-aware workspace undo for DeepSeek Harness",
- "author": "yingtianlan",
- "license": "MIT",
- "keywords": [
- "dsh",
- "plugin",
- "dsh-plugin",
- "tauri",
- "deepseek-harness",
- "undo",
- "snapshot"
- ],
- "sideEffects": false,
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
- },
- "./client": {
- "default": "./dist/client.cjs"
- },
- "./cordis.patch.yml": "./cordis.patch.yml",
- "./package.json": "./package.json"
- },
- "main": "./dist/index.js",
- "module": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "files": [
- "README.md",
- "cordis.patch.yml",
- "dist",
- "purge-workspace.mjs"
- ],
- "dsh": {
- "runtime": "host",
- "bundle": {
- "patch": "./cordis.patch.yml"
- },
- "client": {
- "platform": "web",
- "inject": [
- "@deepseek-ai/dsh-client-runtime",
- "@deepseek-ai/dsh-client-locale",
- "dsh-tauri"
- ],
- "external": [
- "dsh-tauri/client"
- ]
- }
- },
- "engines": {
- "node": ">=22.15.0"
- },
- "scripts": {
- "build": "tsdown",
- "dev": "tsdown --watch",
- "prepublishOnly": "pnpm build",
- "start": "tsx src/index.ts",
- "test": "vitest run test --testTimeout=120000 --maxWorkers=1",
- "typecheck": "tsc"
- },
- "dependencies": {
- "dsh-tauri": "workspace:*",
- "pathe": "catalog:utils"
- },
- "devDependencies": {
-
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/purge-workspace.mjs b/archiving/dsh-tauri-turnrewind-ts/purge-workspace.mjs
deleted file mode 100644
index 83237a4e..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/purge-workspace.mjs
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env node
-/**
- * purge-workspace CLI(P2-8):删除指定 workspace 的全部 turnrewind 数据
- * (私有快照仓库 + 账本行)。引擎在 dist/index.js 构建产物中,本脚本只是
- * 薄封装——先 `pnpm --filter dsh-tauri-turnrewind build` 再运行。
- *
- * 用法:
- * node purge-workspace.mjs <workspace-dir> [--home <dsh-home>]
- * --home 缺省时依次读 DSH_HOME 环境变量、~/.dsh
- *
- * 运行前请先停止对应的 DSH Host 进程;workspace 被占用时本命令会拒绝执行。
- */
-
-import process from 'node:process'
-// eslint-disable-next-line antfu/no-import-dist -- 本 CLI 的引擎就在构建产物里
-import { purgeWorkspace, resolveRootDir, WorkspaceLockBusyError } from './dist/index.js'
-
-const [target, ...args] = process.argv.slice(2)
-if (!target) {
- console.error('Usage: node purge-workspace.mjs <workspace-dir> [--home <dsh-home>]')
- process.exit(1)
-}
-// P2-8: --home 必须带一个非空参数,且不允许其他未知参数;否则 resolveRootDir
-// 会回退到默认 ~/.dsh 而误删错误的数据根。
-const homeArg = args.length === 0
- ? undefined
- : args.length === 2 && args[0] === '--home' && args[1] !== ''
- ? args[1]
- : undefined
-if (args.length > 0 && homeArg === undefined) {
- console.error('Usage: node purge-workspace.mjs <workspace-dir> [--home <dsh-home>]')
- console.error('--home requires exactly one non-empty value and no other arguments.')
- process.exit(1)
-}
-const rootDir = resolveRootDir(homeArg)
-
-try {
- const summary = purgeWorkspace(rootDir, target)
- console.warn(`rootDir: ${summary.rootDir}`)
- console.warn(`repoDir: ${summary.repoDir} (${summary.repoExisted ? 'removed' : 'not present'})`)
- if (summary.ledger) {
- console.warn('ledger rows removed:')
- for (const [table, count] of Object.entries(summary.ledger))
- console.warn(` ${table}: ${count}`)
- }
-}
-catch (error) {
- if (error instanceof WorkspaceLockBusyError) {
- console.error(String(error))
- console.error('Stop the DSH Host process that owns this workspace, then retry.')
- process.exit(2)
- }
- throw error
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
deleted file mode 100644
index 231aa3f8..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/components/command-view.ts
+++ /dev/null
@@ -1,397 +0,0 @@
-/**
- * client/components/command-view.ts — /undo 命令卡片 React 组件。
- *
- * 渲染两阶段 undo 的预览卡:徽标(+x -y)、文件清单、点击展开红绿 diff、
- * 确认/取消按钮与 plan 状态轮询。卡片状态以账本为唯一事实来源——刷新页面后
- * 从 persisted plan status 重建,而不是内存态。
- */
-
-import type { CommandViewProps, LocaleKey, ParsedUndoFile, ParsedUndoOutput, Translate } from '../types'
-import React, { useEffect, useRef, useState } from 'react'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_HTTP_BASE, TURNREWIND_POLL_INTERVAL_MS } from '../constants'
-import { LOCALES } from '../locales'
-import { parseUndoOutput, resolvePlanStatus } from '../utils/parse'
-import { openRecoveryPanel } from '../utils/recovery-opener'
-import { resolveOwnerSessionId } from '../utils/session'
-
-// ------------------------------------------------------------------
-// 颜色:全部引用应用主题 token(带硬编码 fallback),随主题切换实时变化。
-// ------------------------------------------------------------------
-
-/** 连续轮询失败上限(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 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', {
- className: `${TURNREWIND_CLASS_PREFIX}-diffline ${TURNREWIND_CLASS_PREFIX}-diffline-${entry.kind}`,
- }, React.createElement('span', {
- className: `${TURNREWIND_CLASS_PREFIX}-diffline-sign`,
- }, diffSign(entry.kind)), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-diffline-text` }, entry.text))
-}
-
-function NumBadge({ additions, deletions }: { additions: number, deletions: number }): React.ReactElement | null {
- if (additions === 0 && deletions === 0)
- return null
- return React.createElement('span', {
- className: `${TURNREWIND_CLASS_PREFIX}-numbadge`,
- }, React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-numbadge-add` }, `+${additions}`), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-numbadge-del` }, `-${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', {
- className: `${TURNREWIND_CLASS_PREFIX}-panel`,
- }, React.createElement('div', {
- className: `${TURNREWIND_CLASS_PREFIX}-panel-file-header`,
- }, React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-panel-file-change` }, file.change), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-panel-file-path` }, file.path), React.createElement(NumBadge, { additions: file.additions, deletions: file.deletions })), React.createElement('div', { className: `${TURNREWIND_CLASS_PREFIX}-panel-diff` }, rows))
-}
-
-// ------------------------------------------------------------------
-// 提交通道:由 apply() 注入,插件 stop 时置空(effect 生命周期拥有)。
-// ------------------------------------------------------------------
-type SubmitLine = (line: string, ownerSessionId: string | null) => Promise<string | null>
-let submitLine: SubmitLine | null = null
-
-/**
- * 安装提交通道,返回撤销函数。HMR 交错防护(latest-owner-wins):通道归
- * 最新一次安装所有——旧实例的撤销在通道已被新实例接管后是 no-op,不会把
- * 新通道一起清掉;最新所有者自己撤销时才真正置空。
- */
-export function setSubmitLine(next: SubmitLine | null): () => void {
- submitLine = next
- return () => {
- if (submitLine === next)
- submitLine = null
- }
-}
-
-/** 测试/诊断观察口:当前生效的提交通道。 */
-export function peekSubmitLine(): SubmitLine | null {
- return submitLine
-}
-
-// ------------------------------------------------------------------
-// locale 通道:与提交通道同一注入模式。组件不直接依赖 locale 服务
-// (slot props 不携带它),由 apply() 按当前活跃语言注入取词函数;
-// 未注入时回退到 zh 字典——字典即文案的唯一来源,不另存一份硬编码。
-// ------------------------------------------------------------------
-let translator: Translate | null = null
-
-/** 安装 locale 取词通道(返回撤销函数,latest-owner-wins 语义同 setSubmitLine)。 */
-export function setCardTranslator(next: Translate | null): () => void {
- translator = next
- return () => {
- if (translator === next)
- translator = null
- }
-}
-
-/** 测试/诊断观察口:当前生效的取词函数。 */
-export function peekCardTranslator(): Translate | null {
- return translator
-}
-
-function tr(key: LocaleKey): string {
- return translator ? translator(key) : LOCALES.zh[key]
-}
-
-// ------------------------------------------------------------------
-// 命令卡片组件。props 类型集中在 client/types(P2-10)。
-// ------------------------------------------------------------------
-export type { CommandViewProps } from '../types'
-
-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
- // 无文件清单的输出(--doctor 报告、多行错误说明)走纯文本正文:
- // 否则这类卡片只剩第一行摘要,报告主体被整个吞掉。
- const plainLines = parsed.files.length === 0 && text.includes('\n') ? text.slice(text.indexOf('\n') + 1).split('\n') : []
- // 静态报告行:永不重排/增删;id 预计算,避免 JSX key 直接引用数组下标。
- const plainRows = plainLines.map((line, index) => ({ id: `${index}:${line}`, line }))
- const summary = parsed.summary || (state === 'error' ? tr('cardFailed') : state === 'running' ? tr('cardRunning') : tr('cardDone'))
-
- // 展开状态按命令持久化:用户折叠后刷新不重新展开。
- // 持久化 key 只用稳定且长度受限的节点标识(node.id / planId)——不回退到
- // 输出摘要(audit P2-8:摘要过长导致 key 膨胀且不稳定);两者皆缺时不持久化。
- const persistKey = (typeof node.id === 'string' && node.id) || parsed.planId
- const expandKey = persistKey ? `turnrewind.expanded.${persistKey}` : undefined
- const [expanded, setExpanded] = useState(() => {
- if (!expandKey)
- return hasDiff
- try {
- const stored = globalThis.localStorage.getItem(expandKey)
- if (stored === '0' || stored === '1')
- return stored === '1'
- }
- catch {}
- return hasDiff
- })
-
- function toggleExpanded(): void {
- setExpanded((v) => {
- const next = !v
- if (expandKey) {
- 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 httpFailure = !res.ok && res.status !== 404
- 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 ?? tr('cardAppliedFallback'))
- if (next.stop) {
- haltPolling()
- return
- }
- // 非 404 的 HTTP 错误(500/503 等)也计入失败预算,避免无限轮询;
- // 只有真实 pending 负载才清零失败计数。
- failures = (!httpFailure && 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])
-
- // 「真不存在」(旧数据被清理/工作区被 purge)与「用户主动取消」折叠为
- // 无边框细行:cancelled 是用户明确放弃,塌缩成一行「已取消」留痕即可;
- // expired 是留档视图,卡片保留文件清单与 diff 供随时回看。
- const collapsed = planStatus === 'gone' || planStatus === 'cancelled' || submitted === 'cancel'
- const showBody = expanded && !collapsed && (hasDiff || parsed.files.length > 0 || plainLines.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
- ? tr('confirmExecuting')
- : submitted === 'confirm' ? tr('confirmSubmitted') : tr('confirmExecute')
- // submitted === 'cancel' 的卡片已塌缩为细行,完整卡片里取消按钮不存在
- // 「已取消」态:提交中显示取消中,其余显示可点击的取消。
- const cancelLabel = submitting
- ? tr('cancelCancelling')
- : tr('cancelAction')
- // plan 提交即置 applying:提示行不等轮询返回就切到等待态。
- const pendingWait = submitting || submitted === 'confirm' || planStatus === 'applying'
- // P2-11 恢复面板可达性:/undo 错误里命中恢复围栏时,卡片直接给出
- // 「打开恢复面板」入口——弹窗种子逻辑会让历史提示不再重弹,如果只在
- // 弹窗里放入口,被围的用户可能永远到不了面板。
- const underRecovery = (state === 'error' && text.includes('TURNREWIND_RECOVERY_REQUIRED'))
- || Boolean(submitError?.includes('TURNREWIND_RECOVERY_REQUIRED'))
- const hint = submitError
- ? `${tr('confirmFailed')}${submitError}`
- : resultText || (planStatus === 'applied' || pendingWait
- ? tr('cardWaitingResult')
- : planStatus === 'expired'
- ? tr('planExpiredHint')
- : planStatus === 'gone'
- ? tr('planGoneHint')
- : planStatus === 'cancelled' || submitted === 'cancel'
- ? tr('cancelled')
- : underRecovery ? tr('recoveryHint') : tr('previewHint'))
- // 执行结果(成功/失败)靠左展示;「已提交,等待执行结果」与预览提示一样
- // 贴 footer 右缘——等执行结果落地(resultText/applied)再切到左侧。
- const hintLeft = Boolean(resultText || submitError || planStatus === 'applied')
- const hintCls = `${TURNREWIND_CLASS_PREFIX}-card-hint${submitError
- ? ` ${TURNREWIND_CLASS_PREFIX}-card-hint-error`
- : resultText || planStatus === 'applied' ? ` ${TURNREWIND_CLASS_PREFIX}-card-hint-ok` : ''}${hintLeft ? '' : ` ${TURNREWIND_CLASS_PREFIX}-card-hint-right`}`
- const showFooter = actionable || submitting || resultText !== null || submitError !== null || submitted !== null || planStatus === 'applied' || planStatus === 'expired' || planStatus === 'cancelled' || underRecovery
-
- // 取消/过期折叠为无边框细行。
- if (collapsed) {
- return React.createElement('div', {
- className: `${TURNREWIND_CLASS_PREFIX}-card`,
- }, React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-glyph` }, '▸'), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-name` }, node.name || 'undo'), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-dot` }, '·'), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-hint` }, hint))
- }
-
- const hintSpan = React.createElement('span', { className: hintCls }, hint)
- return React.createElement('div', {
- className: `${TURNREWIND_CLASS_PREFIX}-panel`,
- },
- // 可折叠标题行。
- React.createElement('button', {
- type: 'button',
- onClick: toggleExpanded,
- className: `${TURNREWIND_CLASS_PREFIX}-card-header`,
- }, React.createElement('span', {
- className: `${TURNREWIND_CLASS_PREFIX}-card-caret${expanded ? ` ${TURNREWIND_CLASS_PREFIX}-card-caret-open` : ''}`,
- }, '▸'), React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-name` }, node.name || 'undo'), React.createElement(NumBadge, { additions: totals.additions, deletions: totals.deletions }), React.createElement('span', {
- className: `${TURNREWIND_CLASS_PREFIX}-card-summary`,
- }, summary)),
- // 文件清单 / diff 内容;无结构化清单时(--doctor、多行错误)渲染纯文本。
- showBody
- ? React.createElement('div', {
- className: `${TURNREWIND_CLASS_PREFIX}-panel-body`,
- }, hasDiff
- ? withDiff.map(file => React.createElement(DiffBlock, { key: file.path, file }))
- : parsed.files.length > 0
- ? parsed.files.map(file => React.createElement('div', {
- key: file.path,
- className: `${TURNREWIND_CLASS_PREFIX}-panel-file`,
- }, React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-panel-file-change` }, file.change), React.createElement('span', null, file.path)))
- : plainRows.map(row => React.createElement('div', {
- key: row.id,
- className: `${TURNREWIND_CLASS_PREFIX}-panel-textline`,
- }, row.line === '' ? '\u00A0' : row.line)))
- : null,
- // 操作 footer:按钮在左;提交后结果贴左,预览提示靠右。
- // 恢复围栏态(错误输出含 TURNREWIND_RECOVERY_REQUIRED):footer 只放
- // 「打开恢复面板」入口,指向宿主注入的恢复面板。
- showFooter
- ? React.createElement('div', {
- className: `${TURNREWIND_CLASS_PREFIX}-card-actions`,
- }, underRecovery
- ? React.createElement('button', {
- type: 'button',
- onClick: () => { openRecoveryPanel() },
- className: `${TURNREWIND_CLASS_PREFIX}-card-confirm`,
- }, tr('recoveryOpen'))
- : null, (!underRecovery && (actionable || submitting))
- ? React.createElement('button', {
- type: 'button',
- onClick: () => { void submit('confirm') },
- disabled: submitting || submitted !== null,
- className: `${TURNREWIND_CLASS_PREFIX}-card-confirm${submitting ? ` ${TURNREWIND_CLASS_PREFIX}-card-busy` : ''}`,
- }, confirmLabel)
- : null, (!underRecovery && (actionable || submitting))
- ? React.createElement('button', {
- type: 'button',
- onClick: () => { void submit('cancel') },
- disabled: submitting || submitted !== null,
- className: `${TURNREWIND_CLASS_PREFIX}-card-cancel${submitting ? ` ${TURNREWIND_CLASS_PREFIX}-card-busy` : ''}`,
- }, cancelLabel)
- : null, hintLeft ? hintSpan : null, React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-card-spacer` }), hintLeft ? null : hintSpan)
- : null)
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/components/turn-undo.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/components/turn-undo.ts
deleted file mode 100644
index 5ae26735..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/components/turn-undo.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * client/components/turn-undo.ts — 助手消息动作条里的「撤销本轮」按钮。
- *
- * 只负责定位与提交:owner 只给 `messageId`,turn 号经会话快照反查
- * (selectTurnForMessage),再走官方命令通道执行 `/undo <turn-id>`——预览卡、
- * 冲突校验、plan 绑定等全部由既有命令链路承担,按钮本身不做任何恢复动作。
- */
-
-import type { TurnActionProps } from '../types'
-import React, { useState } from 'react'
-import { TURNREWIND_CLASS_PREFIX } from '../constants'
-import { selectTurnForMessage, turnIdFor, undoCommandLine } from '../utils/turn-action'
-import { turnActionChannel } from '../utils/turn-action-channel'
-
-/** 宿主没给 `useSession` 时的占位选择器:恒返回 null(不定位 → 按钮不渲染)。 */
-function absentSelector<T>(selector: (snapshot: never) => T): T | null {
- return selector(undefined as never)
-}
-
-/** 按钮前缀图标:环形箭头(与动作条里的既有图标同一观感)。 */
-function UndoIcon(): React.ReactElement {
- return React.createElement(
- 'svg',
- {
- 'className': `${TURNREWIND_CLASS_PREFIX}-turn-undo-icon`,
- 'viewBox': '0 0 16 16',
- 'width': '14',
- 'height': '14',
- 'fill': 'none',
- 'stroke': 'currentColor',
- 'strokeWidth': '1.4',
- 'strokeLinecap': 'round',
- 'strokeLinejoin': 'round',
- 'aria-hidden': 'true',
- },
- React.createElement('path', { d: 'M3.4 8a4.6 4.6 0 1 0 1.5-3.4' }),
- React.createElement('path', { d: 'M3 2.2v3.2h3.2' }),
- )
-}
-
-/**
- * 动作条槽位组件:无法定位会话/turn 或通道未装配时渲染 null(不占位)。
- *
- * `sessionId`/`useSession` 来自框架的会话标准 kit:`useSession` 把 owner 给的
- * messageId 反查成 turn 号(见 `selectTurnForMessage`)。它是 Hook,必须先无条件
- * 调用再判空早退。
- * @param props - 槽位 props(messageId + 标准 kit)。
- * @returns 撤销按钮,或 null。
- */
-export function TurnUndoAction(props: TurnActionProps): React.ReactElement | null {
- const channel = turnActionChannel()
- const [busy, setBusy] = useState(false)
- const [error, setError] = useState<string | null>(null)
-
- const messageId = typeof props.messageId === 'string' ? props.messageId : null
- // props.useSession 是框架标准 kit 注入的选择器 Hook。它必须**无条件**调用
- // (React Hooks 规则),所以宿主没给时用恒返回 null 的占位实现顶替,而不是
- // 条件调用——条件调用在 HMR/老宿主上会打乱 Hook 顺序。
- const sessionSelector = typeof props.useSession === 'function' ? props.useSession : absentSelector
- const turn = sessionSelector(snapshot => selectTurnForMessage(snapshot, messageId))
- const sessionId = typeof props.sessionId === 'string' && props.sessionId.length > 0
- ? props.sessionId
- : channel === null ? null : channel.sessionId()
- const turnId = turnIdFor(sessionId, turn)
-
- if (!channel || turnId === null)
- return null
-
- const label = channel.translate('turnUndoLabel')
- const caption = React.createElement(
- 'span',
- { className: `${TURNREWIND_CLASS_PREFIX}-turn-undo-text` },
- busy ? channel.translate('turnUndoBusy') : label,
- )
- const submit = (): void => {
- if (busy)
- return
- setBusy(true)
- setError(null)
- void channel.runCommand(undoCommandLine(turnId)).then((failure) => {
- setBusy(false)
- if (failure !== null)
- setError(`${channel.translate('turnUndoFailed')}${failure}`)
- })
- }
-
- return React.createElement(
- 'div',
- { className: `${TURNREWIND_CLASS_PREFIX}-turn-undo-row` },
- React.createElement(
- 'button',
- {
- 'type': 'button',
- 'className': `${TURNREWIND_CLASS_PREFIX}-turn-undo`,
- 'title': label,
- 'aria-label': label,
- 'disabled': busy,
- 'onClick': submit,
- },
- React.createElement(UndoIcon),
- caption,
- ),
- error === null
- ? null
- : React.createElement('span', { className: `${TURNREWIND_CLASS_PREFIX}-turn-undo-error` }, error),
- )
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/constants/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/constants/index.ts
deleted file mode 100644
index b70a9a3f..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/constants/index.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * client/constants/index.ts — 客户端共享常量。
- */
-
-/** 卡片轮询 plan 状态的间隔。 */
-export const TURNREWIND_POLL_INTERVAL_MS = 2000
-
-/** 轮询停止前的最长时长。 */
-export const TURNREWIND_POLL_STOP_MS = 120000
-
-/** 弹窗样式 style id。 */
-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'
-
-/**
- * 撤销按钮所在的槽位:助手消息动作条(每个完成的 turn 渲染一次)。
- *
- * **不能用 `conversation.chat.turnTail`**:那是 chain(选择器路由)槽位,框架
- * 每处只渲染**第一个** select 命中的注册(见 ui-renderer 的 chain 分支 `break`),
- * 而核心 `@deepseek-ai/dsh-client-ui-deliverables` 已经占了它——只要该 turn 产出过
- * 文件,它的 select 就命中,我们的注册永远轮不到,而「产出过文件」恰恰是最需要
- * 撤销的场景。`conversation.chat.assistant-actions` 是 list 槽位(追加、按 order
- * 排序、与 copy/branch/点赞同排),才是「给一条消息加动作」的正规座位。
- */
-export const TURN_UNDO_SLOT = 'conversation.chat.assistant-actions'
-
-/** 撤销按钮在动作条槽内的注册 id(list 槽位内唯一)。 */
-export const TURN_UNDO_ID = 'turnrewind-undo'
-
-/** 动作条内的排列顺序(核心 copy/branch 与反馈按钮在前)。 */
-export const TURN_UNDO_ORDER = 20
-
-/** effect 标签(诊断/日志)。 */
-export const TURN_UNDO_EFFECT = 'turnrewind turn action'
-
-/** locale 命名空间(不可用弹窗双语)。 */
-export const TURNREWIND_LOCALE_NS = 'dsh-tauri-turnrewind'
-
-/** 同源 HTTP 路由前缀——唯一来源是 shared/constants,此处仅别名转发。 */
-export { TURNREWIND_API_PREFIX as TURNREWIND_HTTP_BASE } from '../../shared/constants'
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/index.ts
deleted file mode 100644
index 18af03e9..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/index.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-/**
- * dsh-tauri-turnrewind 客户端插件体(browser half):两阶段 undo 卡片与不可用弹窗。
- *
- * 目录规划:constants/ types/ utils/(纯函数)locales/(双语)register/
- * (卡片/弹窗注册)/ components/(React 组件);与 node half(host/)经
- * /api/turnrewind/* 通信。
- */
-
-import type { ClientContext } from 'dsh-tauri/client'
-import type { LocaleKey } from './locales'
-import { compat, createLifecycleController } from 'dsh-tauri/client'
-import { setCardTranslator, setSubmitLine } from './components/command-view'
-import { TURN_UNDO_EFFECT, TURNREWIND_HTTP_BASE, TURNREWIND_LOCALE_NS, TURNREWIND_POLL_INTERVAL_MS, TURNREWIND_POLL_STOP_MS } from './constants'
-import { LOCALES } from './locales'
-import { registerCommandView } from './register/command-view'
-import { disposeDialog, listNotices, showDialog } from './register/dialog'
-import { disposeRecoveryDialog, openRecoveryDialog } from './register/recovery'
-import { registerTurnUndo } from './register/turn-action'
-import { mountCommandViewStyles, mountDialogStyles, mountRecoveryStyles, mountTurnUndoStyles } from './styles'
-import { createHeadsUpTracker, resolveSessionsService } from './utils/heads-up'
-import { parseUndoOutput, resolvePlanStatus } from './utils/parse'
-import { setRecoveryOpener } from './utils/recovery-opener'
-import { resolveOwnerSessionId } from './utils/session'
-import { resolveCommandRunner } from './utils/turn-action'
-import { setTurnActionChannel } from './utils/turn-action-channel'
-
-export { TURNREWIND_API_PREFIX } from '../shared/constants'
-export type { LocaleKey, ParsedUndoFile, ParsedUndoOutput, PlanStatusResolution } from './types'
-export { parseUndoOutput, resolveOwnerSessionId, resolvePlanStatus }
-
-/** 插件显示名(诊断元数据)。 */
-export const name = 'dsh-tauri-turnrewind'
-
-/**
- * 需要的客户端服务:slots(卡片点位)、sessions(状态轮询/弹窗)、locale(双语)、
- * remote + remote.commands(在消息动作条的撤销按钮里执行 `/undo` 命令)。
- *
- * `remote` 与 `remote.commands` 都是**必须列出的 inject 键**(核心
- * dsh-client-ui-plan / dsh-client-ui-commands 同款):cordis 的 context 代理对
- * 未 inject 的服务属性访问会直接抛,只 inject `remote` 而读 `ctx.remote.commands`
- * 同样会抛——漏声明会让按钮整块降级(首版就是漏了这两个键)。
- */
-export const inject = ['slots', 'sessions', 'locale', 'remote', 'remote.commands']
-
-/**
- * 插件体:安装 locale 与卡片/弹窗注册。
- * @param ctx - 客户端根上下文。
- */
-export function apply(ctx: ClientContext): void {
- const cx = compat(ctx)
- const locale = cx.locale
-
- // 样式挂载:css-render 对象树,apply 生命周期内挂载/卸载。
- ctx.effect(() => mountDialogStyles(), 'turnrewind dialog styles')
- ctx.effect(() => mountCommandViewStyles(), 'turnrewind command-view styles')
- ctx.effect(() => mountRecoveryStyles(), 'turnrewind recovery styles')
- ctx.effect(() => mountTurnUndoStyles(), 'turnrewind turn undo styles')
-
- const t = (key: LocaleKey): string => {
- const active = locale.getLocale().active
- const dict = LOCALES[(active as 'zh' | 'en') in LOCALES ? (active as 'zh' | 'en') : 'zh']
- return dict[key]
- }
-
- // 恢复面板入口:不可用弹窗在 reason 命中恢复围栏时展示「打开恢复面板」。
- ctx.effect(() => setRecoveryOpener(() => openRecoveryDialog(t)), 'turnrewind recovery opener')
-
- // ————————————————— 命令卡片 slot 注册 —————————————————
- // ctx 的类型是 ClientContext(结构上满足 SlotHost 但类型系统可能看不到
- // slots 属性——cordis 版本差异),运行时 guarantee slots 存在。
- ctx.effect(() => registerCommandView(ctx as unknown as Parameters<typeof registerCommandView>[0]), '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')
-
- // ————————————————— 卡片 locale 通道 —————————————————
- // 组件经 slot props 拿不到 locale 服务:由 apply 层把取词函数注入组件模块
- // (setSubmitLine/setCardTranslator 都是 latest-owner-wins,撤销函数直接
- // 作为 effect disposer——HMR 时旧实例的撤销不会清掉新实例的通道)。
- ctx.effect(() => setCardTranslator(t), 'turnrewind card translator')
-
- // ————————————————— ✓/✗ 提交通道 —————————————————
- // 直接 POST 到插件的同源 HTTP 路由(宿主页面本身由同一 Host 服务,无需额外
- // auth wiring)。返回错误字符串让卡片可以显示真实失败原因。
- ctx.effect(() => setSubmitLine(async (line, ownerSessionId) => {
- try {
- if (typeof ownerSessionId !== 'string' || ownerSessionId.length === 0)
- return t('sessionMissing')
- 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)
- }
- }), 'turnrewind submit line')
-
- // ————————————————— 不可用工作区弹窗 runner —————————————————
- // 通过 sessions.list 的投影值读取 Host 注入的 unsupported 提示。
- // 「单会话只报一次」:进入会话(或页面加载)时已存在的提示视为历史留档
- // ——它们已经以会话内消息的形式永久可见,不再重复弹窗(浏览器存储丢
- // 「已读」也不会重弹);只有页面存活期间新到达的提示才弹一次。
- // 会话服务解析优先 compat 代理(含运行时形状适配),原始 get 兜底,
- // 两路都校验形状——不符即告警而非静默失效。
- const sessions = resolveSessionsService([
- (cx as unknown as { sessions?: unknown }).sessions,
- (ctx as unknown as { get?: (name: string) => unknown }).get?.('sessions'),
- ])
- if (!sessions)
- console.warn('[turnrewind] sessions service unavailable; the unsupported heads-up dialog is disabled')
- const headsUp = createHeadsUpTracker()
-
- // ————————————————— 消息动作条「撤销本轮」按钮 —————————————————
- // 动作条 owner 只给 messageId,组件靠会话快照反查 turn 号后经官方命令通道
- // 执行 `/undo <turn-id>`——与手敲命令完全同一条链路(预览卡、冲突校验、plan
- // 绑定全部复用)。会话服务或命令通道缺失时整块跳过,老宿主优雅降级。
- // 从 sessions.list 快照里取当前会话 id:正常是 `current`;个别加载时序下它还是
- // undefined,则用 currentId 兜底;再不行且 byId 里只有一个会话,就用那一个。
- // (正常路径用不到它:组件优先用框架标准 kit 给的 props.sessionId。)
- const sessionIdFromState = (state: unknown): string | null => {
- const value = state as { current?: unknown, currentId?: unknown, byId?: Record<string, unknown> } | undefined
- for (const candidate of [value?.current, value?.currentId]) {
- if (typeof candidate === 'string' && candidate.length > 0)
- return candidate
- }
- const byId = value?.byId
- if (byId !== null && byId !== undefined && typeof byId === 'object') {
- const keys = Object.keys(byId)
- if (keys.length === 1)
- return keys[0]!
- }
- return null
- }
- const currentSessionId = (): string | null => {
- if (!sessions)
- return null
- return sessionIdFromState(sessions.list.getSnapshot())
- }
- const commandRunner = resolveCommandRunner(cx, t) ?? resolveCommandRunner(ctx, t)
- if (sessions && commandRunner) {
- ctx.effect(() => setTurnActionChannel({
- translate: t,
- sessionId: currentSessionId,
- runCommand: line => commandRunner(line, currentSessionId()),
- }), 'turnrewind turn action channel')
- ctx.effect(() => {
- try {
- return registerTurnUndo(ctx as unknown as Parameters<typeof registerTurnUndo>[0])
- }
- catch (error) {
- // 槽位注册失败(宿主槽位形态变化)只降级为「没有按钮」,绝不能让
- // apply 抛——那会让整个客户端插件报 Failed to load plugins。
- console.error('[turnrewind] undo action slot registration failed:', error)
- return () => {}
- }
- }, TURN_UNDO_EFFECT)
- }
- else {
- console.warn('[turnrewind] undo action button disabled: the host exposes no remote.commands.execute (or no sessions service)')
- }
-
- ctx.effect(() => {
- if (!sessions)
- return () => {}
- // 弹窗 runner 的全部资源(订阅/轮询 interval/停轮询 timeout/DOM 卸载)
- // 收敛进一个控制器:dispose 幂等、一次性清理,符合 AGENTS 的
- // Controller 化约定;checkOnce 用 isDisposed 守护 dispose 瞬间的在途回调。
- const controller = createLifecycleController()
-
- function checkOnce(): void {
- if (controller.isDisposed())
- 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 fresh = headsUp.observe(state.current, listNotices(summary?.projectionValues?.turnrewind))
- if (fresh.length === 0)
- return
- console.warn(`[turnrewind] unsupported heads-up visible: ${fresh.map(notice => notice.id).join(', ')}`)
- showDialog(t, fresh)
- }
-
- controller.add(sessions.list.subscribe(checkOnce))
- // 页面加载时投影帧可能在订阅建立前到达;短暂轮询保证时序不会吞掉提示,
- // 稳定后停掉轮询只留订阅驱动。
- controller.timeout(controller.interval(checkOnce, TURNREWIND_POLL_INTERVAL_MS), TURNREWIND_POLL_STOP_MS)
- controller.add(disposeDialog)
- controller.add(disposeRecoveryDialog)
- return () => controller.dispose()
- }, 'turnrewind dialog runner')
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/locales/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/locales/index.ts
deleted file mode 100644
index c7ba24a9..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/locales/index.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * client/locales/index.ts — 双语字典(undo 卡片 / 不可用弹窗)。
- */
-
-export type LocaleKey
- = | 'dialogTitle'
- | 'dialogIntro'
- | 'dialogReason'
- | 'dialogConfirm'
- | 'cardExecuting'
- | 'cardFailed'
- | 'cardDone'
- | 'cardRunning'
- | 'cardAppliedFallback'
- | 'cardWaitingResult'
- | 'confirmFailed'
- | 'confirmExecute'
- | 'confirmExecuting'
- | 'confirmSubmitted'
- | 'cancelAction'
- | 'cancelCancelling'
- | 'cancelled'
- | 'planExpiredHint'
- | 'planGoneHint'
- | 'previewHint'
- | 'recoveryHint'
- | 'sessionMissing'
- | 'recoveryTitle'
- | 'recoveryIntro'
- | 'recoveryOpen'
- | 'recoveryAcknowledge'
- | 'recoveryPurge'
- | 'recoveryClose'
- | 'recoveryActionFailed'
- | 'recoveryEmpty'
- | 'turnUndoLabel'
- | 'turnUndoBusy'
- | 'turnUndoFailed'
-
-const DICT_ZH: Record<LocaleKey, string> = {
- dialogTitle: 'Turn 撤销不可用',
- dialogIntro: '当前会话的工作区不支持文件撤销。回合会正常执行,但其文件修改不会被记录,因此无法用 /undo 回退。',
- dialogReason: '原因',
- dialogConfirm: '知道了',
- cardExecuting: '执行中',
- cardFailed: '失败',
- cardDone: '完成',
- cardRunning: '运行中',
- cardAppliedFallback: '已执行',
- cardWaitingResult: '已提交,等待执行结果…',
- confirmFailed: '执行确认失败:',
- confirmExecute: '✓ 执行',
- confirmExecuting: '执行中…',
- confirmSubmitted: '已提交执行确认',
- cancelAction: '✕ 取消',
- cancelCancelling: '取消中…',
- cancelled: '已取消',
- planExpiredHint: '该计划已过期,重新执行 /undo 可生成新预览',
- planGoneHint: '该计划不存在(可能已被清理或来自旧版本数据)',
- previewHint: '执行将恢复下方文件到本轮改动前',
- recoveryHint: '执行将恢复被打断的文件到本轮改动前',
- sessionMissing: '无法确定该卡片所属的会话,请刷新页面后重试',
- recoveryTitle: 'Turn 撤销恢复',
- recoveryIntro: '以下工作区有被中断的撤销操作,文件状态未知,已暂停新的撤销。请先自行检查工作区文件,然后选择保留历史解锁,或清除该工作区的 rewind 数据。',
- recoveryOpen: '打开恢复面板',
- recoveryAcknowledge: '已检查,保留历史并解锁',
- recoveryPurge: '清除 rewind 数据并解锁',
- recoveryClose: '关闭',
- recoveryActionFailed: '操作失败:',
- recoveryEmpty: '当前没有需要恢复的工作区。',
- turnUndoLabel: '撤销本轮',
- turnUndoBusy: '提交中…',
- turnUndoFailed: '撤销命令提交失败:',
-}
-
-const DICT_EN: Record<LocaleKey, string> = {
- dialogTitle: 'Turn Rewind Unavailable',
- dialogIntro: 'Undo is disabled for this session\'s workspace. Turns run normally, but their file changes are not recorded, so /undo cannot revert them.',
- dialogReason: 'Reason',
- dialogConfirm: 'Got it',
- cardExecuting: 'Executing',
- cardFailed: 'Failed',
- cardDone: 'Done',
- cardRunning: 'Running',
- cardAppliedFallback: 'Applied',
- cardWaitingResult: 'Submitted, waiting for the result…',
- confirmFailed: 'Confirm failed: ',
- confirmExecute: '✓ Apply',
- confirmExecuting: 'Applying…',
- confirmSubmitted: 'Apply confirmed',
- cancelAction: '✕ Cancel',
- cancelCancelling: 'Cancelling…',
- cancelled: 'Cancelled',
- planExpiredHint: 'This plan has expired; run /undo again for a fresh preview',
- planGoneHint: 'This plan no longer exists (it may have been purged or comes from older data)',
- previewHint: 'Applying restores the files below to their state before this turn',
- recoveryHint: 'Applying restores the interrupted files to their state before this turn',
- sessionMissing: 'Cannot determine the session this card belongs to; refresh the page and try again',
- recoveryTitle: 'Turn Rewind Recovery',
- recoveryIntro: 'These workspaces had an interrupted undo; the file state is unknown and new rewind work is paused. Inspect the workspace files yourself, then either keep the history acknowledged or clear the workspace\'s rewind data.',
- recoveryOpen: 'Open recovery panel',
- recoveryAcknowledge: 'Inspected — keep history and unlock',
- recoveryPurge: 'Clear rewind data and unlock',
- recoveryClose: 'Close',
- recoveryActionFailed: 'The action failed: ',
- recoveryEmpty: 'No workspaces need recovery right now.',
- turnUndoLabel: 'Undo this turn',
- turnUndoBusy: 'Submitting…',
- turnUndoFailed: 'Could not submit the undo command: ',
-}
-
-export const LOCALES = { zh: DICT_ZH, en: DICT_EN }
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts
deleted file mode 100644
index d8b64d09..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/register/command-view.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * client/register/command-view.ts — /undo 命令卡片(红绿 diff + 徽标 + 确认/取消)的 slot 注册。
- *
- * ctx 类型用结构化接口(client/types 的 SlotHost)而非 cordis Context:上游
- * cordis 版本的 Context 有更多必需属性,直接引用会因类型版本差异在 CI 上报 TS2345。
- */
-
-import type { SlotHost } from '../types'
-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: SlotHost): () => void {
- // `as never` 是结构性必需:cordis 的槽名类型联合只覆盖官方静态槽位,
- // 插件自定义槽名(conversation.chat.commandview)无法进入该联合。
- 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/archiving/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts
deleted file mode 100644
index b377452a..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/register/dialog.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * client/register/dialog.ts — 不可用工作区的模态弹窗(双语 + 主题 token)。
- *
- * 弹窗去重不在浏览器存储里做(localStorage 会因换端口/清存储而丢「已读」,
- * 导致历史提示反复重弹):调用方按「单会话一次」种子逻辑只对页面存活期间
- * 新到达的提示弹窗,历史提示以会话内消息形式永久留档、不再打扰。
- *
- * DOM 直挂(非 React 组件):弹窗只在 apply 生命周期内存在,stop/HMR 时整个
- * backdrop 子树移除(所有 listener 挂在子树节点上,不会泄漏)。
- */
-
-import type { LocaleKey } from '../locales'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_STYLE_ID } from '../constants'
-import { bindModalA11y } from '../utils/modal-a11y'
-import { openRecoveryPanel, setRecoveryOpener as setRecoveryOpenerChannel } from '../utils/recovery-opener'
-
-export interface UnsupportedNotice {
- id: string
- reason?: string
-}
-
-interface DialogElements {
- backdrop: HTMLDivElement
- title: HTMLDivElement
- intro: HTMLDivElement
- reasonLabel: HTMLDivElement
- reasonBox: HTMLDivElement
- recoveryButton: HTMLButtonElement
- button: HTMLButtonElement
- card: HTMLDivElement
-}
-
-let dialog: DialogElements | undefined
-let a11y: ReturnType<typeof bindModalA11y> | undefined
-
-// ------------------------------------------------------------------
-// 弹窗 DOM:所有颜色走 CSS variable(随主题实时切换),fallback 到硬编码值。
-// ------------------------------------------------------------------
-function ensureDialog(): DialogElements {
- if (dialog)
- return dialog
- // HMR 交错防护:模块实例各自持有 dialog 变量,旧实例的清理可能晚于新
- // 实例的安装——安装前先移除文档里残留的同款 backdrop,保证任何时刻
- // 至多一个弹窗层(类名前缀插件私有,不会误伤其他插件)。
- for (const stale of document.querySelectorAll(`.${TURNREWIND_CLASS_PREFIX}-dialog-backdrop`))
- stale.remove()
- const backdrop = document.createElement('div')
- backdrop.setAttribute('role', 'presentation')
- backdrop.className = `${TURNREWIND_CLASS_PREFIX}-dialog-backdrop`
- backdrop.dataset.visible = 'false'
-
- const card = document.createElement('div')
- card.setAttribute('role', 'dialog')
- card.setAttribute('aria-modal', 'true')
- card.className = `${TURNREWIND_CLASS_PREFIX}-dialog-card`
-
- const title = document.createElement('div')
- title.className = `${TURNREWIND_CLASS_PREFIX}-dialog-title`
-
- const intro = document.createElement('div')
- intro.className = `${TURNREWIND_CLASS_PREFIX}-dialog-intro`
-
- const reasonLabel = document.createElement('div')
- reasonLabel.className = `${TURNREWIND_CLASS_PREFIX}-dialog-reason-label`
-
- const reasonBox = document.createElement('div')
- reasonBox.className = `${TURNREWIND_CLASS_PREFIX}-dialog-reason`
-
- const actions = document.createElement('div')
- actions.className = `${TURNREWIND_CLASS_PREFIX}-dialog-actions`
- // 恢复面板入口:默认隐藏,showDialog 按 reason 决定是否展示。
- const recoveryButton = document.createElement('button')
- recoveryButton.type = 'button'
- recoveryButton.className = `${TURNREWIND_CLASS_PREFIX}-dialog-recovery`
- recoveryButton.dataset.visible = 'false'
- recoveryButton.addEventListener('click', () => {
- hide()
- openRecoveryPanel()
- })
- const button = document.createElement('button')
- button.type = 'button'
- button.className = `${TURNREWIND_CLASS_PREFIX}-dialog-button`
- actions.append(recoveryButton, button)
-
- card.append(title, intro, reasonLabel, reasonBox, actions)
- backdrop.appendChild(card)
- document.body.appendChild(backdrop)
-
- function hide(): void {
- backdrop.dataset.visible = 'false'
- a11y?.restoreFocus()
- }
- button.addEventListener('click', hide)
- backdrop.addEventListener('click', (event) => {
- if (event.target === backdrop)
- hide()
- })
-
- const elements: DialogElements = { backdrop, title, intro, reasonLabel, reasonBox, recoveryButton, button, card }
- a11y = bindModalA11y(
- () => dialog?.card ?? null,
- () => dialog?.backdrop.dataset.visible === 'true',
- () => {
- backdrop.dataset.visible = 'false'
- },
- )
- dialog = elements
- return dialog
-}
-
-/** 插件 stop/HMR 时整个 backdrop 子树移除——listener 全部随之释放。 */
-export function disposeDialog(): void {
- a11y?.release()
- a11y = undefined
- if (!dialog)
- return
- dialog.backdrop.remove()
- dialog = undefined
-}
-
-/** 注入恢复面板入口(apply() 装配层调用):latest-owner-wins,返回撤销函数。 */
-export function setRecoveryOpener(next: (() => void) | null): () => void {
- return setRecoveryOpenerChannel(next)
-}
-
-/** 用当前活跃语言填充并显示弹窗;reason 命中恢复围栏时附「恢复面板」入口。 */
-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')
- const underRecovery = notices.some(notice => notice.reason?.includes('TURNREWIND_RECOVERY_REQUIRED'))
- el.recoveryButton.dataset.visible = underRecovery ? 'true' : 'false'
- if (underRecovery)
- el.recoveryButton.textContent = t('recoveryOpen')
- el.backdrop.dataset.visible = 'true'
- a11y?.takeFocus()
-}
-
-/**
- * 从会话投影中提取 unsupported 提示(不去重)。去重由调用方的
- * 「单会话一次」种子逻辑承担:进入会话时已存在的提示视为历史留档
- * (会话内消息永久可见),只有页面存活期间新到达的提示才弹窗。
- */
-export function listNotices(value: unknown): UnsupportedNotice[] {
- return (Array.isArray((value as { notices?: unknown[] })?.notices)
- ? (value as { notices: unknown[] }).notices
- : []).filter((notice): notice is UnsupportedNotice =>
- notice != null && typeof (notice as UnsupportedNotice).id === 'string')
-}
-
-/** style id 导出(供测试断言/未来的 css-render 迁移使用)。 */
-export { TURNREWIND_STYLE_ID }
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/register/recovery.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/register/recovery.ts
deleted file mode 100644
index 9726e2ce..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/register/recovery.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
- * client/register/recovery.ts — 恢复面板:被围 workspace 的检查与解锁。
- *
- * 数据与动作经 /api/turnrewind/recovery(GET)与 /recovery/resolve(POST):
- * 两个解锁动作由宿主路由承担——acknowledge(用户确认已人工检查,保留历史)
- * 与 purge(清除该工作区的 rewind 数据)。本模块只负责 DOM 呈现与调用;
- * 「打开恢复面板」入口由不可用弹窗在 reason 命中 TURNREWIND_RECOVERY_REQUIRED
- * 时提供(apply() 注入回调,避免模块互相依赖)。
- */
-
-import type { RecoveryWorkspaceInfo, Translate } from '../types'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_HTTP_BASE } from '../constants'
-import { bindModalA11y } from '../utils/modal-a11y'
-
-interface RecoveryElements {
- backdrop: HTMLDivElement
- card: HTMLDivElement
- title: HTMLDivElement
- intro: HTMLDivElement
- list: HTMLDivElement
- error: HTMLDivElement
- closeButton: HTMLButtonElement
-}
-
-let recovery: RecoveryElements | undefined
-let a11y: ReturnType<typeof bindModalA11y> | undefined
-
-function ensureRecoveryDialog(): RecoveryElements {
- if (recovery)
- return recovery
- // HMR 交错防护:安装前清残留 backdrop(与 dialog.ts 同规则,类名独立)。
- for (const stale of document.querySelectorAll(`.${TURNREWIND_CLASS_PREFIX}-recovery-backdrop`))
- stale.remove()
- const backdrop = document.createElement('div')
- backdrop.setAttribute('role', 'presentation')
- backdrop.className = `${TURNREWIND_CLASS_PREFIX}-recovery-backdrop`
- backdrop.dataset.visible = 'false'
-
- const card = document.createElement('div')
- card.setAttribute('role', 'dialog')
- card.setAttribute('aria-modal', 'true')
- card.className = `${TURNREWIND_CLASS_PREFIX}-recovery-card`
-
- const title = document.createElement('div')
- title.className = `${TURNREWIND_CLASS_PREFIX}-recovery-title`
-
- const intro = document.createElement('div')
- intro.className = `${TURNREWIND_CLASS_PREFIX}-recovery-intro`
-
- const list = document.createElement('div')
- list.className = `${TURNREWIND_CLASS_PREFIX}-recovery-list`
-
- const error = document.createElement('div')
- error.className = `${TURNREWIND_CLASS_PREFIX}-recovery-error`
- error.dataset.visible = 'false'
-
- const actions = document.createElement('div')
- actions.className = `${TURNREWIND_CLASS_PREFIX}-recovery-actions`
- const closeButton = document.createElement('button')
- closeButton.type = 'button'
- closeButton.className = `${TURNREWIND_CLASS_PREFIX}-recovery-btn`
- actions.appendChild(closeButton)
-
- card.append(title, intro, list, error, actions)
- backdrop.appendChild(card)
- document.body.appendChild(backdrop)
-
- function hide(): void {
- backdrop.dataset.visible = 'false'
- a11y?.restoreFocus()
- }
- closeButton.addEventListener('click', hide)
- backdrop.addEventListener('click', (event) => {
- if (event.target === backdrop)
- hide()
- })
-
- recovery = { backdrop, card, title, intro, list, error, closeButton }
- a11y = bindModalA11y(
- () => recovery?.card ?? null,
- () => recovery?.backdrop.dataset.visible === 'true',
- hide,
- )
- return recovery
-}
-
-/** 插件 stop/HMR 时整个子树与 a11y listener 一并移除。 */
-export function disposeRecoveryDialog(): void {
- a11y?.release()
- a11y = undefined
- if (!recovery)
- return
- recovery.backdrop.remove()
- recovery = undefined
-}
-
-function actionButton(label: string, cls: string, onClick: () => void): HTMLButtonElement {
- const button = document.createElement('button')
- button.type = 'button'
- button.className = `${TURNREWIND_CLASS_PREFIX}-recovery-btn${cls}`
- button.textContent = label
- button.addEventListener('click', onClick)
- return button
-}
-
-async function resolveWorkspace(workspaceKey: string, mode: 'acknowledge' | 'purge'): Promise<string | null> {
- const res = await fetch(`${TURNREWIND_HTTP_BASE}/recovery/resolve`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ workspaceKey, mode }),
- })
- const payload = await res.json().catch(() => ({}) as Record<string, unknown>)
- if (!res.ok)
- return (payload as { error?: string }).error ?? `HTTP ${res.status}`
- return null
-}
-
-function renderWorkspaces(t: Translate, container: HTMLDivElement, workspaces: RecoveryWorkspaceInfo[]): void {
- container.textContent = ''
- if (workspaces.length === 0) {
- const empty = document.createElement('div')
- empty.className = `${TURNREWIND_CLASS_PREFIX}-recovery-empty`
- empty.textContent = t('recoveryEmpty')
- container.appendChild(empty)
- return
- }
- for (const workspace of workspaces) {
- const row = document.createElement('div')
- row.className = `${TURNREWIND_CLASS_PREFIX}-recovery-workspace`
-
- const path = document.createElement('div')
- path.className = `${TURNREWIND_CLASS_PREFIX}-recovery-path`
- path.textContent = workspace.workspace_path ?? workspace.workspace_key
- row.appendChild(path)
-
- for (const operation of workspace.operations) {
- const op = document.createElement('div')
- op.className = `${TURNREWIND_CLASS_PREFIX}-recovery-op`
- op.textContent = `${operation.kind} → ${operation.target_turn_id}${operation.error ? `: ${operation.error}` : ''}`
- row.appendChild(op)
- }
-
- const actions = document.createElement('div')
- actions.className = `${TURNREWIND_CLASS_PREFIX}-recovery-actions`
- const run = (mode: 'acknowledge' | 'purge'): void => {
- const buttons = [...actions.querySelectorAll('button')] as HTMLButtonElement[]
- const setDisabled = (value: boolean): void => {
- for (const button of buttons)
- button.disabled = value
- }
- setDisabled(true)
- void resolveWorkspace(workspace.workspace_key, mode)
- .then((failure) => {
- if (failure) {
- showActionError(t, failure)
- setDisabled(false)
- return
- }
- return load(t, container)
- })
- .catch((error: unknown) => {
- showActionError(t, String((error as Error)?.message ?? error))
- setDisabled(false)
- })
- }
- actions.appendChild(actionButton(t('recoveryAcknowledge'), '', () => run('acknowledge')))
- actions.appendChild(actionButton(t('recoveryPurge'), ` ${TURNREWIND_CLASS_PREFIX}-recovery-btn-danger`, () => run('purge')))
- row.appendChild(actions)
- container.appendChild(row)
- }
-}
-
-function showActionError(t: Translate, message: string): void {
- if (!recovery)
- return
- recovery.error.textContent = `${t('recoveryActionFailed')}${message}`
- recovery.error.dataset.visible = 'true'
-}
-
-async function load(t: Translate, container: HTMLDivElement): Promise<void> {
- const res = await fetch(`${TURNREWIND_HTTP_BASE}/recovery`)
- const payload = await res.json().catch(() => ({}) as Record<string, unknown>)
- if (!res.ok) {
- showActionError(t, (payload as { error?: string }).error ?? `HTTP ${res.status}`)
- return
- }
- const workspaces = Array.isArray((payload as { workspaces?: unknown }).workspaces)
- ? (payload as { workspaces: RecoveryWorkspaceInfo[] }).workspaces
- : []
- renderWorkspaces(t, container, workspaces)
-}
-
-/** 打开恢复面板并拉取当前围栏状态;动作完成后自动刷新列表。 */
-export function openRecoveryDialog(t: Translate): void {
- const el = ensureRecoveryDialog()
- el.title.textContent = t('recoveryTitle')
- el.intro.textContent = t('recoveryIntro')
- el.closeButton.textContent = t('recoveryClose')
- el.error.dataset.visible = 'false'
- el.backdrop.dataset.visible = 'true'
- a11y?.takeFocus()
- void load(t, el.list).catch((error: unknown) => {
- showActionError(t, String((error as Error)?.message ?? error))
- })
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/register/turn-action.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/register/turn-action.ts
deleted file mode 100644
index b917e656..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/register/turn-action.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * client/register/turn-action.ts — 把「撤销本轮」按钮注册进助手消息动作条。
- *
- * 槽位是 list 型(追加、按 order 排序、与 copy/branch/点赞同排),注册形态是
- * ctx.slots.register({ name, id, order, locale }, Component)
- * ——owner 只传 `{ messageId }`,turn 号由组件自己从会话快照反查。
- *
- * 历史教训(别再改回 `conversation.chat.turnTail`):那是**选择器路由的 chain
- * 槽位**,框架每处只渲染第一个 select 命中的注册;核心 ui-deliverables 已经占了
- * 它,且只要该 turn 产出过文件就恒命中——正是最需要撤销的场景,我们的注册会被
- * 永久挤掉(线上表现为「只有没产出文件的 turn 才有按钮」)。
- *
- * ctx 类型用结构化接口而非 cordis Context(版本差异,与 command-view 同因)。
- */
-
-import type { SlotHost } from '../types'
-import { TurnUndoAction } from '../components/turn-undo'
-import { TURN_UNDO_ID, TURN_UNDO_ORDER, TURN_UNDO_SLOT, TURNREWIND_LOCALE_NS } from '../constants'
-
-/** 注册动作条槽位;effect 卸载时释放 inject 句柄。 */
-export function registerTurnUndo(ctx: SlotHost): () => void {
- return ctx.slots.inject(
- TURN_UNDO_SLOT as never,
- () =>
- ctx.slots.register(
- {
- name: TURN_UNDO_SLOT,
- id: TURN_UNDO_ID,
- order: TURN_UNDO_ORDER,
- locale: TURNREWIND_LOCALE_NS,
- },
- TurnUndoAction,
- ),
- )
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/command-view.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/styles/command-view.ts
deleted file mode 100644
index 876e2c35..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/command-view.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-/**
- * client/styles/command-view.ts — /undo 卡片样式(css-render 树)。
- *
- * 规则:颜色走主题 token;状态类(成功/失败/运行中)由组件切换 class 而非
- * 直接改 style;diff 行语义类(add/del/hunk/meta/text)集中在此。
- * 挂载语义为 latest-wins(HMR 交错防护,见 styles/index.ts 文件头)。
- */
-
-import { CssRender } from 'dsh-tauri/client'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_STYLE_ID } from '../constants'
-
-const P = TURNREWIND_CLASS_PREFIX
-
-/**
- * 构建 undo 卡片样式节点。独立导出供测试渲染断言:css-render 不会给数字
- * 自动补 px,这里所有尺寸必须是带单位字符串(曾因裸数字导致 gap /
- * border-radius / font-size 全部失效)。
- */
-export function buildCommandViewStyleNodes(cssr: ReturnType<typeof CssRender>) {
- return cssr.c([
- // 折叠态:无边框原生风格行
- // 注意:css-render 不会给数字自动补 px,所有尺寸必须写成带单位字符串,
- // 否则生成非法声明被浏览器丢弃(gap/border-radius/font-size 曾因此全部失效)。
- cssr.c(`.${P}-card`, {
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- padding: '2px 12px 2px 4px',
- margin: '2px 0 2px 4px',
- fontSize: '13px',
- }),
- cssr.c(`.${P}-card-header`, {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- width: '100%',
- textAlign: 'left',
- background: 'transparent',
- border: 'none',
- cursor: 'pointer',
- padding: '8px 12px',
- color: 'var(--dsw-alias-label-primary, #cccccc)',
- fontSize: '13px',
- }),
- cssr.c(`.${P}-card-caret`, {
- transform: 'rotate(0deg)',
- transition: 'transform .12s',
- display: 'inline-block',
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- }),
- cssr.c(`.${P}-card-caret-open`, {
- transform: 'rotate(90deg)',
- }),
- cssr.c(`.${P}-card-summary`, {
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- flex: 1,
- minWidth: 0,
- }),
- cssr.c(`.${P}-panel-body`, {
- borderTop: '1px solid var(--dsw-alias-border-l2, #30363d)',
- padding: '6px 10px 10px',
- }),
- cssr.c(`.${P}-card-spacer`, {
- flex: 1,
- }),
- cssr.c(`.${P}-card-busy`, {
- cursor: 'wait',
- opacity: 0.75,
- }),
- cssr.c(`.${P}-card-glyph`, {
- color: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
- }),
- cssr.c(`.${P}-card-name`, {
- fontWeight: 500,
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- }),
- cssr.c(`.${P}-card-dot`, {
- color: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
- }),
- cssr.c(`.${P}-card-hint`, {
- // 高对比:亮色主题黑、暗色主题白(label-primary 随主题切换)。
- color: 'var(--dsw-alias-label-primary, #333333)',
- fontSize: '11.5px',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- flex: 1,
- }),
- // 预览提示与 spacer 各占一半 flex,靠 text-align 贴右边。
- cssr.c(`.${P}-card-hint-right`, {
- textAlign: 'right',
- }),
- cssr.c(`.${P}-card-hint-error`, {
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
- }),
- cssr.c(`.${P}-card-hint-ok`, {
- color: 'var(--dsw-alias-state-success-primary, #3fb950)',
- }),
- // 展开态容器:diff 面板(圆角对齐 DSH 原生嵌入卡片档位:.dpte-card 10px)
- cssr.c(`.${P}-panel`, {
- marginTop: '8px',
- border: '1px solid var(--dsw-alias-border-l2, #30363d)',
- borderRadius: '10px',
- overflow: 'hidden',
- background: 'var(--dsw-alias-bg-layer-2, #161b22)',
- }),
- cssr.c(`.${P}-panel-file`, {
- display: 'flex',
- gap: '8px',
- padding: '2px 0',
- fontFamily: 'var(--ds-font-family-code, monospace)',
- fontSize: '12px',
- }),
- // 纯文本正文(--doctor 报告、多行错误说明):等宽 + 保留缩进与换行。
- cssr.c(`.${P}-panel-textline`, {
- fontFamily: 'var(--ds-font-family-code, monospace)',
- fontSize: '12px',
- lineHeight: '1.5',
- whiteSpace: 'pre-wrap',
- wordBreak: 'break-all',
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- }),
- cssr.c(`.${P}-panel-file-change`, {
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- width: '64px',
- flex: 'none',
- }),
- cssr.c(`.${P}-panel-file-path`, {
- flex: 1,
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- }),
- cssr.c(`.${P}-panel-diff`, {
- maxHeight: '260px',
- overflowY: 'auto',
- padding: '3px 0',
- borderTop: '1px solid var(--dsw-alias-border-l2, #30363d)',
- }),
- cssr.c(`.${P}-panel-file-header`, {
- padding: '6px 10px 10px',
- }),
- // 数字徽标
- cssr.c(`.${P}-numbadge`, {
- display: 'inline-flex',
- gap: '6px',
- flex: 'none',
- fontFamily: 'var(--ds-font-family-code, monospace)',
- fontSize: '11px',
- }),
- cssr.c(`.${P}-numbadge-add`, {
- color: 'var(--dsw-alias-state-success-primary, #3fb950)',
- }),
- cssr.c(`.${P}-numbadge-del`, {
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
- }),
- // diff 行
- cssr.c(`.${P}-diffline`, {
- display: 'flex',
- fontFamily: 'var(--ds-font-family-code, monospace)',
- fontSize: '12px',
- lineHeight: 1.5,
- whiteSpace: 'pre-wrap',
- }),
- cssr.c(`.${P}-diffline-sign`, {
- width: '14px',
- flex: 'none',
- textAlign: 'center',
- }),
- cssr.c(`.${P}-diffline-text`, {
- flex: 1,
- }),
- cssr.c(`.${P}-diffline-add`, {
- background: 'rgba(63, 185, 80, 0.38)',
- color: 'var(--dsw-alias-state-success-primary, #8ff0a4)',
- }),
- cssr.c(`.${P}-diffline-del`, {
- background: 'rgba(248, 81, 73, 0.26)',
- color: 'var(--dsw-alias-state-error-primary, #ffb3ab)',
- }),
- cssr.c(`.${P}-diffline-hunk`, {
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- }),
- cssr.c(`.${P}-diffline-meta`, {
- color: 'var(--dsw-alias-label-dimmed, #8b8b8b)',
- }),
- cssr.c(`.${P}-diffline-text-line`, {
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- }),
- // 卡内确认按钮组
- cssr.c(`.${P}-card-actions`, {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- padding: '6px 12px 10px',
- borderTop: '1px solid var(--dsw-alias-border-l2, #30363d)',
- }),
- cssr.c(`.${P}-card-confirm`, {
- background: 'var(--dsw-alias-button-primary-fill, #2ea043)',
- color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
- border: 'none',
- borderRadius: '6px',
- padding: '4px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- }),
- cssr.c(`.${P}-card-cancel`, {
- background: 'transparent',
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- border: '1px solid var(--dsw-alias-border-l2, #30363d)',
- borderRadius: '6px',
- padding: '4px 14px',
- fontSize: '12px',
- cursor: 'pointer',
- }),
- cssr.c(`.${P}-card-result`, {
- padding: '6px 12px 10px',
- color: 'var(--dsw-alias-label-secondary, #cccccc)',
- fontSize: '12px',
- }),
- ])
-}
-
-/** 挂载 undo 卡片样式(latest-wins,见文件头),返回 disposer。 */
-export function mountCommandViewStyles(): () => void {
- const styleId = `${TURNREWIND_STYLE_ID}-command-view`
- if (typeof document === 'undefined')
- return () => {}
- document.getElementById(styleId)?.remove()
- const style = buildCommandViewStyleNodes(CssRender())
- style.mount({ id: styleId, head: true })
- return () => style.unmount({ id: styleId })
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/styles/index.ts
deleted file mode 100644
index 75aa32f7..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/index.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * client/styles/index.ts — css-render 样式树(dialog + command card)。
- *
- * 按 AGENTS.plugins.md 约定:样式对象树由 css-render 生成,style id / class
- * 使用插件前缀;挂载/卸载由 apply() 的 effect 管理。
- *
- * HMR 交错防护(latest-wins):同 id 样式已存在时先移除再挂载,新安装取得
- * 所有权;旧实例的 unmount 只认它自己 capture 的元素,落空为 no-op。类名
- * 前缀插件私有——AGENTS「不得夺取所有权」防的是跨插件/跨生命周期抢占,
- * 同插件重入(HMR)恰恰需要最新实例接管,否则旧 disposer 会拆掉新实例
- * 依赖的样式。
- *
- * 命名空间:dialog 节点统一使用 `-dialog-*` 前缀,与 command-view 树的
- * `-card-*` / `-panel-*` / `-diffline-*` 类零重叠——两棵树同时挂载时
- * CSS 规则互不污染。
- */
-
-import { CssRender } from 'dsh-tauri/client'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_STYLE_ID } from '../constants'
-
-/** 挂载不可用弹窗样式,返回 disposer。 */
-export function buildDialogStyleNodes(cssr: ReturnType<typeof CssRender>) {
- const p = TURNREWIND_CLASS_PREFIX
- return cssr.c([
- cssr.c(`.${p}-dialog-backdrop`, {
- 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))',
- }),
- cssr.c(`.${p}-dialog-backdrop[data-visible='true']`, {
- display: 'flex',
- }),
- cssr.c(`.${p}-dialog-card`, {
- 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)',
- }),
- cssr.c(`.${p}-dialog-title`, {
- fontSize: '15px',
- fontWeight: '600',
- marginBottom: '10px',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- }),
- cssr.c(`.${p}-dialog-intro`, {
- color: 'var(--dsw-alias-label-secondary, #333333)',
- }),
- cssr.c(`.${p}-dialog-reason-label`, {
- marginTop: '12px',
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- fontSize: '12px',
- }),
- cssr.c(`.${p}-dialog-reason`, {
- 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',
- }),
- cssr.c(`.${p}-dialog-actions`, {
- marginTop: '16px',
- textAlign: 'right',
- }),
- cssr.c(`.${p}-dialog-button`, {
- 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',
- }),
- cssr.c(`.${p}-dialog-button:hover`, {
- background: 'var(--dsw-alias-button-primary-hover, #4338ca)',
- }),
- // 恢复面板入口(默认 display:none,data-visible 控制展示)。
- cssr.c(`.${p}-dialog-recovery`, {
- display: 'none',
- background: 'transparent',
- color: 'var(--dsw-alias-label-primary, #111111)',
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- borderRadius: '8px',
- padding: '6px 14px',
- fontSize: '13px',
- cursor: 'pointer',
- }),
- cssr.c(`.${p}-dialog-recovery[data-visible='true']`, {
- display: 'inline-block',
- }),
- ])
-}
-
-/** 挂载不可用弹窗样式(latest-wins,见文件头),返回 disposer。 */
-export function mountDialogStyles(): () => void {
- const styleId = `${TURNREWIND_STYLE_ID}-dialog`
- if (typeof document === 'undefined')
- return () => {}
- document.getElementById(styleId)?.remove()
- const style = buildDialogStyleNodes(CssRender())
- style.mount({ id: styleId, head: true })
- return () => style.unmount({ id: styleId })
-}
-
-/** 构建恢复面板样式节点(独立导出供测试断言)。 */
-export function buildRecoveryStyleNodes(cssr: ReturnType<typeof CssRender>) {
- const p = TURNREWIND_CLASS_PREFIX
- return cssr.c([
- cssr.c(`.${p}-recovery-backdrop`, {
- 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))',
- }),
- cssr.c(`.${p}-recovery-backdrop[data-visible='true']`, {
- display: 'flex',
- }),
- cssr.c(`.${p}-recovery-card`, {
- maxWidth: '620px',
- width: 'calc(100vw - 48px)',
- boxSizing: 'border-box',
- maxHeight: '80vh',
- overflowY: 'auto',
- 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)',
- }),
- cssr.c(`.${p}-recovery-title`, {
- fontSize: '15px',
- fontWeight: '600',
- marginBottom: '10px',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- }),
- cssr.c(`.${p}-recovery-intro`, {
- color: 'var(--dsw-alias-label-secondary, #333333)',
- marginBottom: '12px',
- }),
- cssr.c(`.${p}-recovery-empty`, {
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- }),
- cssr.c(`.${p}-recovery-workspace`, {
- border: '1px solid var(--dsw-alias-border-l2, #e5e5e5)',
- borderRadius: '8px',
- padding: '10px 12px',
- marginBottom: '10px',
- }),
- cssr.c(`.${p}-recovery-path`, {
- fontFamily: 'monospace',
- fontSize: '12px',
- wordBreak: 'break-all',
- marginBottom: '6px',
- }),
- cssr.c(`.${p}-recovery-op`, {
- color: 'var(--dsw-alias-label-secondary, #333333)',
- fontSize: '12px',
- wordBreak: 'break-all',
- marginBottom: '4px',
- }),
- cssr.c(`.${p}-recovery-error`, {
- display: 'none',
- marginTop: '10px',
- padding: '8px 10px',
- borderRadius: '8px',
- background: 'var(--dsw-alias-state-error-bg, #fdecef)',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- wordBreak: 'break-all',
- whiteSpace: 'pre-wrap',
- }),
- cssr.c(`.${p}-recovery-error[data-visible='true']`, {
- display: 'block',
- }),
- cssr.c(`.${p}-recovery-actions`, {
- marginTop: '10px',
- display: 'flex',
- gap: '8px',
- justifyContent: 'flex-end',
- }),
- cssr.c(`.${p}-recovery-btn`, {
- background: 'var(--dsw-alias-button-primary-fill, #4f46e5)',
- color: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
- border: 'none',
- borderRadius: '8px',
- padding: '6px 14px',
- fontSize: '13px',
- cursor: 'pointer',
- }),
- cssr.c(`.${p}-recovery-btn:disabled`, {
- opacity: 0.6,
- cursor: 'default',
- }),
- cssr.c(`.${p}-recovery-btn-danger`, {
- background: 'var(--dsw-alias-state-error-primary, #d03050)',
- }),
- ])
-}
-
-/** 挂载恢复面板样式(latest-wins,见文件头),返回 disposer。 */
-export function mountRecoveryStyles(): () => void {
- const styleId = `${TURNREWIND_STYLE_ID}-recovery`
- if (typeof document === 'undefined')
- return () => {}
- document.getElementById(styleId)?.remove()
- const style = buildRecoveryStyleNodes(CssRender())
- style.mount({ id: styleId, head: true })
- return () => style.unmount({ id: styleId })
-}
-
-export { mountCommandViewStyles } from './command-view'
-export { buildTurnUndoStyleNodes, mountTurnUndoStyles } from './turn-undo'
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/turn-undo.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/styles/turn-undo.ts
deleted file mode 100644
index 1607d3fa..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/styles/turn-undo.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * client/styles/turn-undo.ts — 助手动作条「撤销本轮」按钮样式(css-render 树)。
- *
- * 按钮住在核心的消息动作条里(copy/branch/点赞同排),所以尺寸与观感对齐那一行
- * 的既有图标按钮:28px 高、圆角、hover 用交互底色;颜色走主题 token,尺寸一律
- * 带单位(css-render 不给裸数字补 px)。
- */
-
-import { CssRender } from 'dsh-tauri/client'
-import { TURNREWIND_CLASS_PREFIX, TURNREWIND_STYLE_ID } from '../constants'
-
-const P = TURNREWIND_CLASS_PREFIX
-
-/** 构建动作条按钮样式节点(独立导出供测试渲染断言)。 */
-export function buildTurnUndoStyleNodes(cssr: ReturnType<typeof CssRender>) {
- return cssr.c([
- cssr.c(`.${P}-turn-undo-row`, {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '6px',
- }),
- cssr.c(`.${P}-turn-undo`, {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '4px',
- height: '28px',
- padding: '0 10px',
- fontSize: '13px',
- lineHeight: '28px',
- background: 'transparent',
- color: 'var(--dsw-alias-label-tertiary, #8b8b8b)',
- border: 'none',
- borderRadius: '14px',
- cursor: 'pointer',
- whiteSpace: 'nowrap',
- }),
- cssr.c(`.${P}-turn-undo:hover:not(:disabled)`, {
- background: 'var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.12))',
- color: 'var(--dsw-alias-label-secondary, #4b4b4b)',
- }),
- cssr.c(`.${P}-turn-undo:disabled`, {
- cursor: 'default',
- opacity: 0.5,
- }),
- cssr.c(`.${P}-turn-undo-icon`, {
- flex: 'none',
- }),
- cssr.c(`.${P}-turn-undo-text`, {
- flex: 'none',
- }),
- cssr.c(`.${P}-turn-undo-error`, {
- fontSize: '12px',
- color: 'var(--dsw-alias-state-error-primary, #d03050)',
- }),
- ])
-}
-
-/** 挂载动作条按钮样式(latest-wins,见 styles/index.ts 文件头)。 */
-export function mountTurnUndoStyles(): () => void {
- const styleId = `${TURNREWIND_STYLE_ID}-turn-undo`
- if (typeof document === 'undefined')
- return () => {}
- document.getElementById(styleId)?.remove()
- const style = buildTurnUndoStyleNodes(CssRender())
- style.mount({ id: styleId, head: true })
- return () => style.unmount({ id: styleId })
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/types/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/types/index.ts
deleted file mode 100644
index 379b09b3..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/types/index.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * client/types/index.ts — 客户端共享类型。
- */
-
-import type { LocaleKey } from '../locales'
-
-export type { LocaleKey } from '../locales'
-
-/** 卡片里单个文件条目(解析 /undo 预览输出得到)。 */
-export interface ParsedUndoFile {
- path: string
- change: 'modified' | 'created' | 'deleted' | 'conflict'
- additions: number
- deletions: number
- diff: string[]
- conflict: boolean
-}
-
-/** /undo 输出的解析结果(summary / 文件清单 / diff 分隔 / plan id)。 */
-export interface ParsedUndoOutput {
- summary: string
- files: ParsedUndoFile[]
- dividers: string[]
- planId: string | undefined
-}
-
-/** plan 状态轮询结果。 */
-export interface PlanStatusResolution {
- status: 'pending' | 'applied' | 'cancelled' | 'expired' | 'gone' | 'error' | null
- stop: boolean
- resultText: string | null
-}
-
-/** /undo 命令卡片槽位组件的 props(P2-10:集中到 client/types)。 */
-export interface CommandViewProps {
- node?: { id?: string, name?: string, sessionId?: string, outcome?: { kind?: string, text?: string } }
- sessionId?: string
-}
-
-/** locale 取词函数:apply 装配层按当前活跃语言注入,组件层消费。 */
-export type Translate = (key: LocaleKey) => string
-
-/**
- * 槽位宿主:结构化接口而非 cordis Context——上游 cordis 版本的 Context 有
- * 更多必需属性,直接引用会因类型版本差异在 CI 上报 TS2345。
- *
- * `register` 的 options 覆盖两类槽位形态:keyed(commandview 用 `key`)与
- * list(动作条用 `id` + `order`,可选 `locale`/`inject`)。
- */
-export interface SlotHost {
- slots: {
- inject: (slot: string, factory: () => () => void) => () => void
- register: (options: {
- name: string
- id?: string
- key?: string
- order?: number
- locale?: string
- inject?: unknown
- }, component: unknown) => () => void
- }
-}
-
-/** 会话快照上的选择器钩子(框架标准 kit;会话作用域槽位组件都会拿到)。 */
-export type SessionSelectorHook = <T>(selector: (snapshot: never) => T) => T
-
-/**
- * `conversation.chat.assistant-actions` 的槽位 props:owner 只给这一条消息的
- * 身份,turn 号由组件自己从会话快照反查(见 utils/turn-action 的
- * `selectTurnForMessage`)。`sessionId`/`useSession` 来自框架标准 kit。
- */
-export interface TurnActionProps {
- /** 该动作条所属的已定稿助手消息 id。 */
- messageId?: unknown
- /** 当前会话 id(框架标准 kit)。 */
- sessionId?: unknown
- /** 会话快照选择器钩子(框架标准 kit)。 */
- useSession?: SessionSelectorHook
- /** locale 取词(注册时声明了 locale 命名空间才会注入)。 */
- t?: Translate
-}
-
-/** turn 尾部按钮的装配通道(apply 注入,register 侧组件消费)。 */
-export interface TurnActionChannel {
- translate: Translate
- /** 当前活跃会话 id;未选中会话时返回 null。 */
- sessionId: () => string | null
- /** 执行一条命令(错误时返回文案,成功返回 null)。 */
- runCommand: (line: string) => Promise<string | null>
-}
-
-/** 恢复面板行(host GET /api/turnrewind/recovery 的 workspaces 条目)。 */
-export interface RecoveryWorkspaceInfo {
- workspace_key: string
- workspace_path: string | null
- operations: {
- operation_id: string
- kind: string
- target_turn_id: string
- requested_at: string
- settled_at: string | null
- error: string | null
- }[]
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/heads-up.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/heads-up.ts
deleted file mode 100644
index 25e44520..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/heads-up.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * client/utils/heads-up.ts — 不可用工作区弹窗的「单会话一次」去重状态机。
- *
- * 纯函数:不依赖 DOM/localStorage。种子语义——首次观察到某个会话时,其
- * 投影里已存在的提示视为历史留档(会话内消息永久可见,不弹窗);只有
- * 同一会话存活期间新到达的提示才上报一次。会话切换会重新播种。
- */
-
-export interface HeadsUpNotice {
- id: string
- reason?: string
-}
-
-export interface HeadsUpTracker {
- observe: (currentSession: unknown, notices: HeadsUpNotice[]) => HeadsUpNotice[]
-}
-
-export function createHeadsUpTracker(): HeadsUpTracker {
- const knownIds = new Set<string>()
- let seededSession: unknown = null
- return {
- observe(currentSession, notices) {
- // 首次观察到当前会话(页面加载/切换会话):现存提示全部视为已留档历史。
- if (seededSession !== currentSession) {
- seededSession = currentSession
- for (const notice of notices)
- knownIds.add(notice.id)
- return []
- }
- const fresh = notices.filter(notice => !knownIds.has(notice.id))
- for (const notice of fresh)
- knownIds.add(notice.id)
- return fresh
- },
- }
-}
-
-/**
- * 解析会话服务:优先走 compat 代理(其内部已按运行时形状做 get/属性双路
- * 读取),失败时回退原始 get('sessions')。两路都要求 list.getSnapshot/
- * subscribe 形状完整——形状不符宁可返回 undefined 并让调用方告警,也不
- * 静默让弹窗链路失效(审计报告 P2-8)。
- */
-export interface SessionsLike {
- list: {
- getSnapshot: () => unknown
- subscribe: (fn: () => void) => () => void
- }
-}
-
-export function resolveSessionsService(candidates: Array<unknown>): SessionsLike | undefined {
- for (const candidate of candidates) {
- const sessions = candidate as SessionsLike | undefined | null
- if (sessions && typeof sessions.list?.getSnapshot === 'function' && typeof sessions.list?.subscribe === 'function')
- return sessions
- }
- return undefined
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/modal-a11y.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/modal-a11y.ts
deleted file mode 100644
index 2f5a09bc..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/modal-a11y.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * client/utils/modal-a11y.ts — 模态弹窗的最小可访问性绑定(P2-6)。
- *
- * Escape 关闭 + Tab 焦点陷阱 + 显示时聚焦卡内首个可交互元素。不可用弹窗与
- * 恢复面板两个 DOM 模态共用;document 级 listener 由 release() 移除,
- * 插件 dispose 时调用。
- */
-
-const FOCUSABLE_SELECTOR = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
-
-export interface ModalA11yBinding {
- /** 挂到 document keydown 上(bindModalA11y 内部已挂,暴露仅为测试/调试)。 */
- onKeydown: (event: KeyboardEvent) => void
- /** 弹窗显示时调用:记住先前焦点并聚焦卡内首个可交互元素。 */
- takeFocus: () => void
- /** 弹窗关闭时调用:把焦点还给打开弹窗前的元素。 */
- restoreFocus: () => void
- /** 永久释放(插件 dispose):移除 listener,不再移动焦点。 */
- release: () => void
-}
-
-export function bindModalA11y(getCard: () => HTMLElement | null, isVisible: () => boolean, hide: () => void): ModalA11yBinding {
- let previous: HTMLElement | null = null
-
- const onKeydown = (event: KeyboardEvent): void => {
- if (!isVisible())
- return
- if (event.key === 'Escape') {
- event.preventDefault()
- hide()
- return
- }
- if (event.key !== 'Tab')
- return
- const card = getCard()
- if (!card)
- return
- const focusables = [...card.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)]
- if (focusables.length === 0)
- return
- const active = document.activeElement
- if (!(active instanceof HTMLElement) || !card.contains(active)) {
- // 焦点落在卡外(例如刚点击了 backdrop 里的空白处):拉回第一个。
- event.preventDefault()
- focusables[0]!.focus()
- return
- }
- const first = focusables[0]!
- const last = focusables[focusables.length - 1]!
- if (event.shiftKey && active === first) {
- event.preventDefault()
- last.focus()
- }
- else if (!event.shiftKey && active === last) {
- event.preventDefault()
- first.focus()
- }
- }
- document.addEventListener('keydown', onKeydown)
-
- return {
- onKeydown,
- takeFocus() {
- previous = document.activeElement instanceof HTMLElement ? document.activeElement : null
- const card = getCard()
- const target = card?.querySelector<HTMLElement>(FOCUSABLE_SELECTOR) ?? card
- target?.focus()
- },
- restoreFocus() {
- previous?.focus()
- previous = null
- },
- release() {
- document.removeEventListener('keydown', onKeydown)
- // 关闭路径应调用 restoreFocus();release 只负责 teardown,不把焦点
- // 挪到可能已移除的卡片上。
- previous = null
- },
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
deleted file mode 100644
index b633af49..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/parse.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * client/utils/parse.ts — /undo 输出解析(纯函数)。
- *
- * 含空格路径、[conflict]/[too large] 标记与 diff 归属;解析失败不抛错,
- * 卡片渲染降级为纯文本。
- */
-
-import type { ParsedUndoFile, ParsedUndoOutput } from '../types'
-
-export function parseUndoOutput(raw: string | undefined): ParsedUndoOutput {
- const lines = (raw ?? '').split('\n')
- const result: ParsedUndoOutput = { summary: lines[0] ?? '', files: [], dividers: [], planId: undefined }
- let current: ParsedUndoFile | null = 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) {
- // Host aligns `change.padEnd(8)`: `created`/`deleted` therefore leave
- // extra separator spaces before the path. Trim only the formatting
- // prefix so `my notes.txt` matches its diff separator instead of
- // falling into the synthetic conflict fallback.
- let path = listed[2]!.trimStart()
- let conflict = false
- // padEnd makes `created`/`deleted` rows carry two spaces before a flag
- // while `modified` rows carry one — accept any run of whitespace so the
- // flag strips reliably for every change kind.
- if (/\s+\[conflict\]$/.test(path)) {
- conflict = true
- path = path.replace(/\s+\[conflict\]$/, '')
- }
- if (/\s+\[too large\]$/.test(path))
- path = path.replace(/\s+\[too large\]$/, '')
- if (/\s+\[unsupported\]$/.test(path))
- path = path.replace(/\s+\[unsupported\]$/, '')
- result.files.push({ path, change: listed[1] as ParsedUndoFile['change'], 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) ?? null
- if (!current) {
- current = { path, change: 'conflict', additions: 0, deletions: 0, diff: [], conflict: true }
- 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
-}
-
-/** plan 状态轮询的结局判定(expired/gone/applied/cancelled/error 终态;非 404 失败继续轮询)。 */
-export function resolvePlanStatus(res: { ok: boolean, status: number }, payload: { status?: string, resultText?: string | null } | null): { status: 'pending' | 'applied' | 'cancelled' | 'expired' | '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' : 'pending', stop: res.status === 404, resultText: null }
- const status = payload?.status
- if (status === 'gone')
- return { status: 'gone', stop: true, resultText: null }
- // expired 是终态但不是 gone:plan 行已留档,卡片保留留档视图、仅不可执行。
- if (status === 'expired')
- return { status: 'expired', stop: true, resultText: payload?.resultText ?? null }
- if (status === 'applied' || status === 'cancelled' || status === 'error')
- return { status, stop: true, resultText: payload?.resultText ?? null }
- return { status: 'pending', stop: false, resultText: null }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/recovery-opener.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/recovery-opener.ts
deleted file mode 100644
index 67073a33..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/recovery-opener.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * client/utils/recovery-opener.ts — 恢复面板入口的单例通道。
- *
- * dialog(不可用弹窗)与 command-view(/undo 错误卡片)都需要打开恢复
- * 面板;面板实例在 register/recovery.ts,入口经此模块中转,避免组件与
- * register 模块互相依赖。latest-owner-wins:apply() 装配层 set,stop/HMR
- * 时 disposer 置空。
- */
-
-let opener: (() => void) | null = null
-
-export function setRecoveryOpener(next: (() => void) | null): () => void {
- opener = next
- return () => {
- if (opener === next)
- opener = null
- }
-}
-
-/** 打开恢复面板;入口未装配(opener 为空)时返回 false 供调用方降级提示。 */
-export function openRecoveryPanel(): boolean {
- if (!opener)
- return false
- opener()
- return true
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/session.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/session.ts
deleted file mode 100644
index 3bac6a1c..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/session.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * client/utils/session.ts — 卡片宿主会话解析(纯函数)。
- */
-
-export function resolveOwnerSessionId(props: { sessionId?: unknown, node?: { sessionId?: unknown } } | undefined): string | null {
- const candidates = [props?.sessionId, props?.node?.sessionId]
- for (const candidate of candidates) {
- if (typeof candidate === 'string' && candidate.length > 0)
- return candidate
- }
- return null
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action-channel.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action-channel.ts
deleted file mode 100644
index 9b23109b..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action-channel.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/**
- * client/utils/turn-action-channel.ts — turn 尾部撤销按钮的装配通道。
- *
- * 槽位组件由 register/ 注册、依赖(取词、当前会话、命令执行)由 apply() 层
- * 注入,两者不互相 import。latest-owner-wins:HMR 时旧实例的 disposer 不会
- * 清掉新实例的通道(与 setSubmitLine / setCardTranslator 同一模式)。
- */
-
-import type { TurnActionChannel } from '../types'
-
-let channel: TurnActionChannel | null = null
-
-export function setTurnActionChannel(next: TurnActionChannel | null): () => void {
- channel = next
- return () => {
- if (channel === next)
- channel = null
- }
-}
-
-/** 读取当前通道;未装配时按钮不渲染。 */
-export function turnActionChannel(): TurnActionChannel | null {
- return channel
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action.ts b/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action.ts
deleted file mode 100644
index 10d78f5b..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/client/utils/turn-action.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * client/utils/turn-action.ts — 撤销按钮的纯函数与命令通道解析。
- *
- * 按钮坐在 `conversation.chat.assistant-actions` 里,owner 只给消息 id,所以
- * turn 号要从会话快照(`snapshot.chat`)反查:账本的 turn id 与宿主一致,形如
- * `<sessionId>:<turn>`,因此按钮能精确定位被点击的那一轮,而不是只撤最新一轮。
- */
-
-import type { Translate } from '../types'
-
-/** 把槽位 turn 号与宿主会话 id 拼成账本 turn id;任一不合法即返回 null。 */
-export function turnIdFor(sessionId: string | null | undefined, turn: unknown): string | null {
- if (typeof sessionId !== 'string' || sessionId.length === 0)
- return null
- const value = typeof turn === 'number'
- ? turn
- : typeof turn === 'string' && /^\d+$/u.test(turn) ? Number(turn) : Number.NaN
- if (!Number.isInteger(value) || value < 0)
- return null
- return `${sessionId}:${value}`
-}
-
-/** 按钮要执行的命令:与手敲 `/undo <turn-id>` 完全同一条路径。 */
-export function undoCommandLine(turnId: string): string {
- return `/undo ${turnId}`
-}
-
-/**
- * 一个 chat 节点承载的 messageId → turn 号映射。
- *
- * 兼容两类载荷(都是同一个 turn 的不同渲染单元):
- * - view 节点:`data` 里带载荷——turn-tail 用 `data.closing.finalNode.messageId`,
- * assistant 用 `data.finalNode.messageId`(或扁平 `data.messageId`),配 `data.turn`;
- * - 旧版扁平节点(`chat.legacy.nodes`):`{ kind:'assistant', messageId, turn }`
- * 直接挂在节点上,没有 `data` 包一层。
- * @returns 命中该消息时返回它的 turn 号,否则 null。
- */
-export function turnForMessageNode(node: unknown, messageId: string): number | null {
- if (node === null || typeof node !== 'object')
- return null
- const record = node as Record<string, unknown>
- const data = record.data
- const payload = (data !== null && typeof data === 'object' ? data : record) as {
- turn?: unknown
- messageId?: unknown
- closing?: { finalNode?: { messageId?: unknown } }
- finalNode?: { messageId?: unknown }
- }
- if (typeof payload.turn !== 'number' || !Number.isInteger(payload.turn))
- return null
- const ids = [payload.messageId, payload.closing?.finalNode?.messageId, payload.finalNode?.messageId]
- return ids.includes(messageId) ? payload.turn : null
-}
-
-/**
- * 在会话快照里反查某条助手消息所属的 turn 号。
- *
- * 只读公开快照形状(`chat.order` + `chat.nodes` 的稳定 keyed reader),并用
- * `chat.legacy.nodes` 与直接 `.values()` 兜底不同宿主版本;任何形状不符都返回
- * null(按钮不渲染),绝不抛。
- */
-export function selectTurnForMessage(snapshot: unknown, messageId: unknown): number | null {
- if (typeof messageId !== 'string' || messageId.length === 0)
- return null
- const chat = (snapshot as { chat?: unknown } | null | undefined)?.chat as {
- order?: unknown
- nodes?: { get?: unknown, values?: unknown }
- legacy?: { nodes?: unknown }
- } | undefined
- if (chat === null || typeof chat !== 'object')
- return null
-
- const candidates: unknown[] = []
- const order = chat.order
- const nodes = chat.nodes
- if (Array.isArray(order) && typeof nodes?.get === 'function') {
- for (const key of order)
- candidates.push((nodes.get as (key: unknown) => unknown).call(nodes, key))
- }
- else if (typeof nodes?.values === 'function') {
- const values = (nodes.values as () => unknown).call(nodes)
- if (Array.isArray(values))
- candidates.push(...values)
- }
- const legacy = chat.legacy?.nodes
- if (Array.isArray(legacy))
- candidates.push(...legacy)
-
- for (const node of candidates) {
- const turn = turnForMessageNode(node, messageId)
- if (turn !== null)
- return turn
- }
- return null
-}
-
-/** 命令执行函数:返回错误文案(供按钮显示),成功返回 null。 */
-export type CommandRunner = (line: string, sessionId: string | null) => Promise<string | null>
-
-/**
- * 解析宿主的 `ctx.remote.commands.execute(sessionId, line, images)`。
- * 这是「解析并执行已知命令、不发送给模型」的官方通道——按钮复用它,就能让
- * 既有 `/undo` 命令链路(预览卡、冲突校验、plan 绑定)原样生效。
- * 宿主未暴露该能力时返回 null,调用方据此不注册槽位(老版本宿主优雅降级)。
- */
-export function resolveCommandRunner(ctx: unknown, translate: Translate): CommandRunner | null {
- let commands: { execute?: unknown } | undefined
- try {
- commands = (ctx as { remote?: { commands?: { execute?: unknown } } } | undefined)?.remote?.commands
- }
- catch {
- // 未在 inject 里声明 `remote`、或该服务尚未就绪时,cordis 的 context 代理对属性
- // 访问会直接抛。这里吞掉并降级为「不注册槽位」——按钮不出现,好过整个客户端插件
- // apply 失败(界面会报 Failed to load plugins)。
- return null
- }
- const execute = commands?.execute
- if (typeof execute !== 'function' || commands === undefined)
- return null
- const call = execute as (sessionId: string, line: string, images: string[]) => Promise<unknown>
- return async (line, sessionId) => {
- if (typeof sessionId !== 'string' || sessionId.length === 0)
- return translate('sessionMissing')
- try {
- await call.call(commands, sessionId, line, [])
- return null
- }
- catch (error) {
- return String((error as Error)?.message ?? error)
- }
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/apply.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/apply.ts
deleted file mode 100644
index d6496264..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/apply.ts
+++ /dev/null
@@ -1,790 +0,0 @@
-/**
- * host/apply.ts — 插件装配(turn 生命周期 / 路由 / 命令 / 投影)。
- *
- * 装配顺序与 reasons:
- * 1. 投影先注册——会话列表帧到达前弹窗链路已就绪;
- * 2. HTTP 路由注册在 effect 内,卸载统一释放;
- * 3. pre-step waterfall 是执行 barrier:before 快照(或明确 skip/失败)
- * settle 之前,任何模型请求与工具调用不得运行;
- * 4. turn/end 落 FIFO 会话链结算 after 快照;
- * 5. 重启清扫挂在 runtime 首建(原子替换 crash 窗口的复活点)。
- */
-
-import type { Ledger } from './service/ledger'
-import type { WorkspaceRuntime } from './service/undo'
-import { createHash } from 'node:crypto'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { join, resolve } from 'pathe'
-import { TURNREWIND_API_PREFIX } from '../shared/constants'
-import { MAX_ENDED_TURNS } from './constants'
-import { jsonRoute } from './routes'
-import { createDialogProjection } from './service/dialog-projection'
-import { collectDoctorReport } from './service/doctor'
-import {
- captureSnapshot,
- createSnapshotStore,
- gitAvailable,
- restoreCrashedSwaps,
- snapshotDiff,
-} from './service/git-snapshot'
-import {
- acknowledgeRecovery,
- claimPendingPlan,
- claimRewindNotices,
- failTurn,
- getLatestSnapshotRef,
- getPendingPlanRow,
- getPendingPlanStatus,
- getTurn,
- hasNeedsRecoveryWorkspace,
- hasSensitiveNotice,
- insertTurn,
- listRecoveryWorkspaces,
- markPendingPlanApplied,
- markPendingPlanCancelled,
- openLedger,
- pruneConsumedNotices,
- queueSensitiveNotice,
- recordSkippedTurn,
- registerWorkspace,
- releasePendingPlanClaim,
- settleInterruptedTurn,
- settleNoopTurn,
- settleTurn,
- skipTurn,
-} from './service/ledger'
-import { purgeWorkspace } from './service/maintenance'
-import { planDrift } from './service/planner'
-import { enforceRetention } from './service/retention'
-import { findUnignoredSensitiveFiles } from './service/sensitive'
-import { applyUndo, buildPlanEntries, executeUndoRestore, parseUndoInput, turnRefsExist, workspaceForAgent, workspaceHasActiveTurn, workspaceIssue, workspaceKeyFor } from './service/undo'
-import { acquireWorkspaceLockSync, withWorkspaceLock, WorkspaceLockBusyError } from './service/workspace-lock'
-
-/** 插件名(诊断元数据,与 shared/constants 的 TURNREWIND_PLUGIN_NAME 一致)。 */
-export const name = 'dsh-tauri-turnrewind'
-
-/**
- * 需要的宿主服务:
- * commands /undo 人类命令
- * sessionProjections 不可用弹窗的会话投影
- * webServer /api/turnrewind/*(卡内 ✓/✗ 与状态轮询)
- */
-export const inject = ['commands', 'sessionProjections', 'webServer'] as const
-
-function rootDir(): string {
- return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
-}
-
-export interface HostApplyContext {
- commands: { register: (command: unknown) => () => void }
- sessionProjections: { register: (projection: unknown) => () => void }
- webServer: { register: (route: unknown) => () => void }
- on: (event: string, listener: (...args: any[]) => void) => void
- effect: (factory: () => (() => void) | void, label?: string) => () => void
- logger?: { warn?: (message: string) => void, error?: (message: string) => void }
-}
-
-interface ActiveEntry {
- runtime: WorkspaceRuntime
- sessionId: string
- workspaceKey: string
- turnId: string
- beforeRef: string
- baseline: Deferred
- baselineReady: boolean
- startedAt: string
- turn: number
-}
-
-interface Deferred {
- promise: Promise<{ ok: boolean, reason?: string }>
- resolve: (value: { ok: boolean, reason?: string }) => void
-}
-
-function createDeferred(): Deferred {
- let resolve!: (value: { ok: boolean, reason?: string }) => void
- const promise = new Promise<{ ok: boolean, reason?: string }>((resolvePromise) => {
- resolve = resolvePromise
- })
- return { promise, resolve }
-}
-
-function settleDeferred(deferred: Deferred, value: { ok: boolean, reason?: string }): void {
- deferred.resolve(value)
-}
-
-/** turn 前后快照 ref:turnId 的 sha256 前 32 位 + 阶段后缀,稳定且不进用户 refs 命名空间。 */
-export function turnSnapshotRef(turnId: string, phase: string): string {
- const digest = createHash('sha256').update(turnId).digest('hex').slice(0, 32)
- return `refs/turnrewind/turn-${digest}-${phase}`
-}
-
-function activeKey(sessionId: string, turn: number): string {
- return `${sessionId}:${turn}`
-}
-
-export function waitForTurnBaseline(activeTurns: Map<string, ActiveEntry>, sessionId: string, turn: number, signal?: AbortSignal): Promise<{ ok: boolean, reason?: string } | undefined> {
- const entry = activeTurns.get(activeKey(sessionId, turn))
- if (!entry?.baseline)
- return Promise.resolve(undefined)
- if (!signal)
- return entry.baseline.promise
- signal.throwIfAborted()
- return new Promise((resolvePromise, rejectPromise) => {
- const onAbort = (): void => {
- // Propagate the abort reason exactly like the JS version: the pre-step
- // waterfall relies on the rejection to short-circuit the model step.
- // (reject directly - throwing inside an event listener would not
- // settle this promise, leaving the barrier awaiting forever.)
- rejectPromise(signal.reason ?? new Error('aborted'))
- }
- signal.addEventListener('abort', onAbort, { once: true })
- entry.baseline.promise.then((value) => {
- signal.removeEventListener('abort', onAbort)
- resolvePromise(value)
- })
- })
-}
-
-// ————————————————— 会话 FIFO / 结算 —————————————————
-
-async function settleActiveTurn(ledger: Ledger, active: Map<string, ActiveEntry>, key: string, reason?: string): Promise<void> {
- const current = active.get(key)
- if (!current || current.runtime.disposed)
- return
- try {
- // 跨进程互斥(P1-1):after 快照 + 账本结算与另一个 Host 进程 /
- // purge 脚本对同一 workspace 的写操作互斥。忙等 5s 后放弃并 failTurn。
- await withWorkspaceLock(current.runtime.store.rootDir, current.runtime.workspaceDir, async () => {
- const afterRef = turnSnapshotRef(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
- }, { waitMs: 5000 })
- }
- catch (error) {
- if (!current.runtime.disposed)
- failTurn(ledger, current.turnId, error)
- }
- finally {
- active.delete(key)
- }
-}
-
-async function settleSessionTurns(ledger: Ledger, active: Map<string, ActiveEntry>, sessionId: string, exceptKey: string, reason?: string): Promise<void> {
- for (const [key, entry] of [...active.entries()]) {
- if (key === exceptKey || !key.startsWith(`${sessionId}:`) || !entry.baselineReady)
- continue
- await settleActiveTurn(ledger, active, key, reason)
- }
-}
-
-// ————————————————— apply 主体 —————————————————
-
-export function apply(ctx: HostApplyContext): void {
- // 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)
- // P2-11: 日志统一走 ctx.logger(宿主注入的结构化日志),console 仅兜底。
- const log = {
- warn: (message: string): void => {
- if (ctx.logger?.warn)
- ctx.logger.warn(message)
- else
- console.warn(message)
- },
- error: (message: string): void => {
- if (ctx.logger?.error)
- ctx.logger.error(message)
- else
- console.error(message)
- },
- }
- // P1-6:needs-recovery 围栏改为实时查库(hasNeedsRecoveryWorkspace),
- // 运行期落围栏的 workspace 立即被拦截,不再依赖启动时加载的内存快照。
- // One-shot at startup: consumed notices older than a week have no readers
- // left (their dedup window is long gone) and would otherwise accumulate
- // without bound on long-lived installs.
- pruneConsumedNotices(ledger)
- const active = new Map<string, ActiveEntry>()
- const untrackedTurns = new Set<string>()
- const workspaceStores = new Map<string, WorkspaceRuntime>()
- 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')
-
- // Per-session FIFO chain: baseline capture, settle and undo bookkeeping for
- // one session never interleave. Git runs asynchronously, so ordering is
- // enforced here instead of by the event loop blocking.
- const sessionChains = new Map<string, Promise<void>>()
- const endedTurns = new Map<string, boolean>()
-
- function enqueueTurnTask(sessionId: string, task: () => Promise<void>): Promise<void> {
- 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: string): boolean {
- 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: { session?: { header?: { cwd?: string } } }): WorkspaceRuntime | undefined {
- 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)
- log.warn(`turnrewind: resurrected ${path} in ${workspaceDir} from a crashed restore swap`)
- // 容量治理(P2-4):workspace 首次触碰是安全点(无活动 turn、无 undo)。
- // 超出保留条数的 turn 标记过期;仓库超限整仓重建(下次 capture 自愈基线)。
- // 重建/回收是破坏性写,与另一 Host 进程的 capture 互斥:拿一次性跨进程
- // 锁执行;忙(另一进程正在捕获/恢复/清理)则本轮跳过,绝不让治理与
- // 捕获并发写同一仓库——治理是内务,不能阻塞或破坏 turn 追踪。
- try {
- const retentionLock = acquireWorkspaceLockSync(dataRoot, workspaceDir)
- try {
- const retention = enforceRetention(ledger, store)
- if (retention.expiredByCount > 0)
- log.warn(`turnrewind: retention expired ${retention.expiredByCount} turn(s) in ${workspaceDir} (kept the most recent ones)`)
- if (retention.rebuilt)
- log.warn(`turnrewind: snapshot repository for ${workspaceDir} rebuilt by retention (${retention.repoSizeMb.toFixed(1)} MB over the cap; ${retention.expiredByRebuild} turn(s) archived)`)
- }
- finally {
- retentionLock.release()
- }
- }
- catch (error) {
- if (error instanceof WorkspaceLockBusyError)
- log.warn(`turnrewind: workspace busy; snapshot retention skipped this time for ${workspaceDir}`)
- else
- log.error(`turnrewind: snapshot retention failed for ${workspaceDir}: ${String(error)}`)
- }
- runtime = {
- db: ledger,
- store,
- workspaceKey,
- workspaceDir,
- parentRef: latest,
- undoing: false,
- disposed: false,
- }
- workspaceStores.set(workspaceKey, runtime)
- }
- return runtime
- }
-
- function recordSkipped(turnId: string, sessionId: string, workspaceKey: string, startedAt: string, reason: string, notify = true): void {
- untrackedTurns.add(turnId)
- try {
- if (notify) {
- recordSkippedTurn(ledger, { turnId, sessionId, workspaceKey, startedAt }, reason)
- }
- else {
- skipTurn(ledger, { turnId, sessionId, workspaceKey, startedAt }, reason)
- }
- }
- catch (error) {
- log.error(`turnrewind: failed to record skipped turn ${turnId}: ${String(error)}`)
- }
- log.error(`turnrewind: skipped turn ${turnId}: ${reason}`)
- }
-
- function reserveTurnBaseline(agent: { session: { id: string, header?: { cwd?: string } } }, turn: number): ActiveEntry | undefined {
- 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 (hasNeedsRecoveryWorkspace(ledger, 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
- }
- for (const entry of active.values()) {
- if (entry.workspaceKey === workspaceKey && entry.sessionId !== 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 = turnSnapshotRef(key, 'before')
- const baseline = createDeferred()
- const entry: ActiveEntry = {
- runtime,
- sessionId,
- workspaceKey: runtime.workspaceKey,
- turnId: key,
- beforeRef,
- baseline,
- baselineReady: false,
- startedAt,
- turn,
- }
- active.set(key, entry)
-
- const baselineTask = async (): Promise<void> => {
- 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
- }
- // 跨进程互斥(P1-1):before 快照 + turn 入账与另一个进程对同一
- // workspace 的写操作互斥;忙等 5s 后按显式 skip 释放 barrier。
- await withWorkspaceLock(dataRoot, runtime.workspaceDir, async () => {
- if (disposed || runtime.disposed)
- return
- await captureSnapshot(runtime.store, beforeRef, `turnrewind before ${key}`, runtime.parentRef)
- if (disposed || runtime.disposed)
- return
- insertTurn(ledger, {
- turnId: key,
- sessionId,
- workspaceKey: runtime.workspaceKey,
- startedAt,
- beforeRef,
- })
- entry.baselineReady = true
- }, { waitMs: 5000 })
- if (disposed || runtime.disposed) {
- settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })
- return
- }
- // 敏感文件一次性提醒(P2-5 隐私面):不持锁(扫描 + check-ignore 是
- // 纯读),每会话+工作区只扫一次——已有提醒的会话直接跳过扫描。
- if (!disposed && !runtime.disposed && !hasSensitiveNotice(ledger, sessionId, runtime.workspaceKey)) {
- try {
- const sensitive = await findUnignoredSensitiveFiles(runtime.workspaceDir)
- if (sensitive.length > 0)
- queueSensitiveNotice(ledger, sessionId, runtime.workspaceKey, sensitive)
- }
- catch (scanError) {
- log.warn(`turnrewind: sensitive-file scan failed (ignored): ${String(scanError)}`)
- }
- }
- settleDeferred(baseline, { ok: true })
- }
- catch (error) {
- active.delete(key)
- const reason = error instanceof WorkspaceLockBusyError
- ? error.message
- : `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)
- log.error(`turnrewind: failed to start turn ${key}: ${String(error)}`)
- }
- }
- void enqueueTurnTask(sessionId, baselineTask).catch((error: unknown) => {
- // 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)
- log.error(`turnrewind: baseline queue failed for ${key}: ${String(error)}`)
- })
- return entry
- }
-
- // 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).
- // P1-3: planId 必须是 UUID 形态、session 长度受限且无控制字符——
- // 防止任意字符串进入日志与 SQLite 语义。
- const PLAN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
- const validPlanId = (value: string): boolean => PLAN_ID_RE.test(value)
- const validSessionId = (value: string): boolean =>
- value.length >= 1 && value.length <= 200 && [...value].every(ch => ch.charCodeAt(0) > 31)
- ctx.effect(() => {
- function confirmRoute(body: Record<string, unknown>): Promise<[number, unknown]> | [number, unknown] {
- const planId = String(body.planId ?? '')
- const sessionId = String(body.sessionId ?? '')
- if (planId === '' || sessionId === '')
- return [400, { error: 'planId and sessionId are required' }]
- if (!validPlanId(planId) || !validSessionId(sessionId))
- return [400, { error: 'planId or sessionId is malformed' }]
- const previewRow = getPendingPlanRow(ledger, planId)
- if (previewRow === undefined)
- return [404, { error: 'plan not found — run /undo again' }]
- if (previewRow.session_id !== sessionId)
- return [403, { error: 'the plan belongs to another session' }]
- // 过期 plan 已转 expired 留档:明确告知过期(可查看,不可执行)。
- if (previewRow.status === 'expired')
- return [409, { error: 'this plan has expired — run /undo again to preview a fresh plan' }]
- 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' }]
- // P1-6:实时围栏——预览后落 needs-recovery 的 workspace 立即拒绝执行。
- if (hasNeedsRecoveryWorkspace(ledger, previewRow.workspace_key))
- return [409, { error: 'TURNREWIND_RECOVERY_REQUIRED: the workspace needs recovery (a previous operation was interrupted) — open the recovery panel to resolve' }]
- 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 (): Promise<[number, unknown]> => {
- 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\'s snapshot data no longer exists — run /undo again' }]
- const paths = await snapshotDiff(planRuntime.store, target.before_ref, target.after_ref)
- // 计划漂移校验(P1-2):与命令路径同一规则——确认时的快照 ref 与
- // 重算 diff 必须与预览一致,否则拒绝并要求重新预览。
- const drift = planDrift(row, target, paths)
- if (drift)
- return [409, { error: `${drift} — run /undo again to refresh the plan` }]
- if (paths.length === 0) {
- markPendingPlanApplied(ledger, planId, sessionId, 'No file changes were recorded for this turn.')
- committed = 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` }]
- let message: string
- try {
- message = await executeUndoRestore(planRuntime, {
- sessionId,
- workspaceKey: row.workspace_key,
- target,
- paths,
- entries,
- skipConflicts: false,
- })
- }
- catch (error) {
- // 另一个进程正持有该 workspace 的锁(P1-1):计划仍未消费,
- // 以 409 告知客户端稍后重试。
- if (error instanceof WorkspaceLockBusyError)
- return [409, { error: `${(error as Error).message} — retry shortly` }]
- throw error
- }
- markPendingPlanApplied(ledger, planId, sessionId, message)
- committed = true
- return [200, { ok: true, message }]
- }
- finally {
- if (!committed)
- releasePendingPlanClaim(ledger, planId)
- planRuntime.undoing = false
- }
- })()
- }
-
- function cancelRoute(body: Record<string, unknown>): [number, unknown] {
- const planId = String(body.planId ?? '')
- const sessionId = String(body.sessionId ?? '')
- if (planId === '' || sessionId === '')
- return [400, { error: 'planId and sessionId are required' }]
- if (!validPlanId(planId) || !validSessionId(sessionId))
- return [400, { error: 'planId or sessionId is malformed' }]
- // 非 pending 行返回精确错误而不是 200 假成功:假成功会让客户端先塌缩成
- // 「已取消」,刷新后又被轮询纠正成别的状态——状态必须一次说清。
- const row = getPendingPlanRow(ledger, planId)
- if (row === undefined)
- return [404, { error: 'plan not found — run /undo again' }]
- if (row.session_id !== sessionId)
- return [403, { error: 'the plan belongs to another session' }]
- if (row.status === 'cancelled')
- return [200, { ok: true, message: 'Pending undo cancelled.' }]
- if (row.status === 'expired')
- return [409, { error: 'this plan has expired — run /undo again to preview a fresh plan' }]
- if (row.status === 'applied')
- return [409, { error: 'this plan was already applied' }]
- if (row.status === 'applying')
- return [409, { error: 'this plan is being applied — wait for it to finish' }]
- const removed = markPendingPlanCancelled(ledger, planId, sessionId)
- if (!removed)
- return [409, { error: 'this plan was already applied or cancelled — run /undo again' }]
- return [200, { ok: true, message: 'Pending undo cancelled.' }]
- }
-
- // ——— 恢复面板路由:被围 workspace 的查询与解锁(acknowledge | purge) ———
-
- function recoveryRoute(): [number, unknown] {
- return [200, { workspaces: listRecoveryWorkspaces(ledger) }]
- }
-
- function recoveryResolveRoute(body: Record<string, unknown>): [number, unknown] {
- const workspaceKey = String(body.workspaceKey ?? '')
- const mode = String(body.mode ?? '')
- if ((mode !== 'acknowledge' && mode !== 'purge') || workspaceKey === '' || workspaceKey.length > 500)
- return [400, { error: 'workspaceKey and mode (acknowledge|purge) are required' }]
- const fenced = listRecoveryWorkspaces(ledger).find(workspace => workspace.workspace_key === workspaceKey)
- if (fenced === undefined)
- return [404, { error: 'this workspace is not under recovery' }]
- if (mode === 'acknowledge') {
- const acknowledged = acknowledgeRecovery(ledger, workspaceKey)
- return [200, { ok: true, acknowledged }]
- }
- try {
- // purgeWorkspace 自带跨进程锁,workspace 被占用时拒绝。传 workspace_key
- // 而非客户端输入的路径:它正是 purge 哈希与账本行使用的规范输入。
- const summary = purgeWorkspace(dataRoot, workspaceKey)
- return [200, { ok: true, purged: summary }]
- }
- catch (error) {
- if (error instanceof WorkspaceLockBusyError)
- return [409, { error: `${(error as Error).message} — stop the host process using this workspace first` }]
- throw error
- }
- }
-
- function statusRoute(_body: Record<string, unknown>, req: { url?: string }): [number, unknown] {
- 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' }]
- if (!validPlanId(planId) || !validSessionId(sessionId))
- return [400, { error: 'planId or sessionId is malformed' }]
- 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(`${TURNREWIND_API_PREFIX}/confirm`, confirmRoute, { mutate: true }),
- jsonRoute(`${TURNREWIND_API_PREFIX}/cancel`, cancelRoute, { mutate: true }),
- jsonRoute(`${TURNREWIND_API_PREFIX}/status`, statusRoute, { methods: ['GET'] }),
- jsonRoute(`${TURNREWIND_API_PREFIX}/recovery`, recoveryRoute, { methods: ['GET'] }),
- jsonRoute(`${TURNREWIND_API_PREFIX}/recovery/resolve`, recoveryResolveRoute, { mutate: true }),
- ]
- const disposers = routes.map(route => ctx.webServer.register(route))
- return () => disposers.map(dispose => dispose())
- }, 'turnrewind routes')
-
- ctx.on('agent/pre-step', async ({ agent, turn, signal }: { agent: { session: { id: string, header?: { cwd?: string } } }, turn: number, signal: AbortSignal }, next: () => Promise<{ kind: string, messages?: unknown[] }>) => {
- // `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))
- log.error(`turnrewind: no baseline reservation for ${key}; turn is explicitly untracked`)
- const decision = await next()
- if (decision.kind === 'reject' || signal.aborted || disposed)
- return decision
- // 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
- const { createNoticeMessage } = await import('./service/undo')
- return {
- ...decision,
- messages: [...(decision.messages ?? []), ...notices.map(notice => createNoticeMessage(notice))],
- }
- })
-
- ctx.on('agent/inbox/claimed', (payload: { agent: { session: { id: string, header?: { cwd?: string } } }, turn: number }) => {
- if (!disposed)
- reserveTurnBaseline(payload.agent, payload.turn)
- })
-
- ctx.on('session/event', (session: { id: string }, event: { type?: string, data?: { turn?: number, reason?: { kind?: string } } }) => {
- 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'
- void 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: { agent: { session: { id: string } }, turn: number, error: unknown }) => {
- // Keep the active record until turn/end or the idle fallback. In particular,
- // model switching can emit an error before the final partial writes finish.
- log.error(`turnrewind: observed agent error for ${activeKey(payload.agent.session.id, payload.turn)}: ${String(payload.error)}`)
- })
- ctx.on('agent/status', ({ agent, status }: { agent: { session: { id: string } }, status: string }) => {
- if (disposed || status !== 'idle')
- return
- const sessionId = agent.session.id
- for (const key of [...active.keys()]) {
- if (key.startsWith(`${sessionId}:`))
- void 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] | --doctor' },
- handler: (invocation: { rawInput: string, agent: { session: { id: string, header?: { cwd?: string } } } }) => {
- const parsed = parseUndoInput(invocation.rawInput)
- // --doctor 在工作区资格判定之前短路:诊断恰恰要在「undo 不可用」时给出
- // 原因,不能被资格检查挡掉。
- if (!('error' in parsed) && parsed.doctor)
- return collectDoctorReport(ledger, dataRoot, invocation.agent).then(text => ({ kind: 'success' as const, text }))
- 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 (hasNeedsRecoveryWorkspace(ledger, workspaceIdentity))
- return { kind: 'error', text: 'TURNREWIND_RECOVERY_REQUIRED: a previous undo or redo was interrupted. Open the recovery panel (from the "Turn rewind unavailable" notice) to inspect the workspace, keep the history acknowledged, or clear its rewind data.' }
- 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, { rawInput: invocation.rawInput, agent: invocation.agent }, {
- workspaceForAgent,
- workspaceIssue,
- workspaceKeyFor,
- })
- },
- }), 'turnrewind command')
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/constants/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
deleted file mode 100644
index 88f6d6c9..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/constants/index.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * host/constants/index.ts — 宿主侧私有常量。
- */
-
-/** 单文件快照/恢复上限(64 MiB;blob 超限单文件报告,不炸整体 undo)。 */
-export const MAX_FILE_BYTES = 64 * 1024 * 1024
-
-/** git 子进程输出上限。 */
-export const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
-
-/** 异步 git 子进程墙钟预算(SIGKILL 兜底)。 */
-export const GIT_SUBPROCESS_TIMEOUT_MS = 5 * 60 * 1000
-
-/** 可用性探测预算(探测喂给 pre-step barrier,挂起即卡 turn)。 */
-export const GIT_PROBE_TIMEOUT_MS = 30 * 1000
-
-/** 可用性探测失败后的重试间隔。 */
-export const GIT_PROBE_RETRY_MS = 5 * 60 * 1000
-
-/** 同步 rev-parse 的预算(本地元数据查询,慢于此即视为卡死)。 */
-export const SYNC_GIT_TIMEOUT_MS = 15 * 1000
-
-/** 快照 refs 允许的前缀(拒绝其他 refs 命名空间与路径穿越)。 */
-export const SNAPSHOT_REF_PREFIX = 'refs/turnrewind/'
-
-/** Git symlink 条目的 mode 值(P1-3:stateAt/restore 据此拒绝,而非伪装成文件)。 */
-export const GIT_SYMLINK_MODE = '120000'
-
-/** 原子替换的 bak 后缀。 */
-export const BAK_SUFFIX = '.turnrewind-restore.bak'
-
-/** 快照排除规则(git pathspec;ignore 语义委托源仓库)。 */
-export const SNAPSHOT_PATHSPECS: string[] = [
- ':(exclude,glob).git/**',
- ':(exclude,glob)**/.git/**',
- ':(exclude,glob).turnrewind/**',
- ':(exclude,glob)**/.turnrewind/**',
- ':(exclude,glob)**/*.turnrewind-*.tmp',
- ':(exclude,glob)**/*.turnrewind-restore.bak',
-]
-
-/** pending plan 存活时长(只影响未执行的预览;settled 结果行永久保留可追溯)。 */
-export const PENDING_PLAN_TTL_MS = 5 * 60 * 1000
-
-/** endedTurns 内存上界。 */
-export const MAX_ENDED_TURNS = 500
-
-/** HTTP 路由 body 上限。 */
-export const MAX_ROUTE_BODY_BYTES = 16 * 1024
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/routes/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/routes/index.ts
deleted file mode 100644
index eaec8c63..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/routes/index.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * host/routes/index.ts — 同源 HTTP 路由(/api/turnrewind/*)。
- *
- * ✓/✗ 按钮经此驱动两阶段确认:confirm(POST,loopback-only)原子 claim 后执行;
- * cancel(POST);status(GET)供卡片轮询 plan 结局。与 worktree 插件的
- * jsonRoute 模式一致:方法严格限制、body 上限、变更仅回环。
- *
- * P1-3 加固:响应一次性 guard(异常客户端不会触发重复响应/崩溃)、
- * body 超限立即 413 并断开、mutate 路由校验 JSON Content-Type、
- * 统一 nosniff/no-store 响应头、处理超时兜底(长 undo 由 status 轮询
- * 恢复,响应中断不影响服务端继续执行)。
- */
-
-import { Buffer } from 'node:buffer'
-import { MAX_ROUTE_BODY_BYTES } from '../constants'
-
-export interface RouteRequest {
- method?: string
- url?: string
- socket?: { remoteAddress?: string }
- headers?: Record<string, string | string[] | undefined>
- on: (event: string, listener: (...args: any[]) => void) => void
- destroy?: (error?: Error) => void
- setHeader?: (name: string, value: string) => void
-}
-
-export interface RouteResponse {
- writeHead: (code: number, headers: Record<string, string>) => void
- setHeader: (name: string, value: string) => void
- end: (body?: string) => void
-}
-
-export type RouteHandler = (body: Record<string, unknown>, req: RouteRequest) => Promise<[number, unknown]> | [number, unknown]
-
-export interface WebRoute {
- kind: 'exact'
- path: string
- handler: (req: RouteRequest, res: RouteResponse) => void
-}
-
-export interface JsonRouteOptions {
- mutate?: boolean
- /** 允许的 HTTP 方法(大写)。缺省不限制;mutate 路由隐式限定 POST。 */
- methods?: string[]
- /**
- * 处理超时(ms)。默认 120s;超时后返回 504,服务端逻辑继续执行,
- * 客户端经 status 轮询恢复结果。
- */
- timeoutMs?: number
-}
-
-export function jsonRoute(path: string, handler: RouteHandler, { mutate = false, methods = [], timeoutMs = 120000 }: JsonRouteOptions = {}): WebRoute {
- const allowed = new Set(methods.map(m => m.toUpperCase()))
- if (mutate)
- allowed.add('POST')
- return {
- kind: 'exact',
- path,
- handler(req: RouteRequest, res: RouteResponse) {
- // P1-3: 一次性响应 guard——'error'/'end' 与超时竞争时绝不二次写出。
- let responded = false
- const send = (code: number, payload: unknown): void => {
- if (responded)
- return
- responded = true
- const body = JSON.stringify(payload)
- res.writeHead(code, {
- 'content-type': 'application/json; charset=utf-8',
- 'x-content-type-options': 'nosniff',
- 'cache-control': 'no-store',
- })
- res.end(body)
- }
- const timeoutPayload = { error: 'request timed out; the operation may still complete — poll /api/turnrewind/status' }
- const timeout = setTimeout(send, timeoutMs, 504, timeoutPayload)
- const finish = (): void => {
- clearTimeout(timeout)
- }
- if (mutate && req.method !== 'POST') {
- res.setHeader('allow', 'POST')
- finish()
- send(405, { error: 'mutation routes require POST' })
- return
- }
- if (allowed.size > 0 && !allowed.has((req.method ?? '').toUpperCase())) {
- res.setHeader('allow', [...allowed].join(', '))
- finish()
- send(405, { error: 'method not allowed' })
- return
- }
- const parts: Buffer[] = []
- let totalBytes = 0
- let tooLarge = false
- req.on('data', (chunk: Buffer | string) => {
- if (tooLarge)
- return
- const value = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk
- totalBytes += value.length
- if (totalBytes > MAX_ROUTE_BODY_BYTES) {
- tooLarge = true
- // P1-3: 超限立即响应并断开,不再消费剩余流。
- finish()
- send(413, { error: 'request body too large' })
- req.destroy?.(new Error('body too large'))
- return
- }
- parts.push(value)
- })
- req.on('error', () => {
- finish()
- send(400, { error: 'request stream failed' })
- })
- req.on('end', () => {
- void (async () => {
- if (tooLarge)
- return finish()
- // P1-3: mutate 路由要求 JSON Content-Type(缺省视为不符)。
- 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' })
- const contentType = req.headers?.['content-type']
- const type = Array.isArray(contentType) ? contentType[0] : contentType
- if (!type || !type.toLowerCase().includes('application/json'))
- return send(415, { error: 'content-type must be application/json' })
- }
- try {
- const parsed = JSON.parse(Buffer.concat(parts).toString('utf8') || '{}') as Record<string, unknown>
- const [code, payload] = await handler(parsed, req)
- finish()
- send(code, payload)
- }
- catch (error) {
- finish()
- send(500, { error: String((error as Error)?.message ?? error) })
- }
- })()
- })
- },
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/dialog-projection.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/dialog-projection.ts
deleted file mode 100644
index b337dabe..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/dialog-projection.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * host/service/dialog-projection.ts — `turnrewind` 会话投影。
- *
- * 把插件注入的 unsupported-workspace heads-up 消息折叠进会话列表快照,客户端半
- * 据此弹窗。纯函数、单测覆盖;index.ts 的注册是唯一 effect。
- */
-
-export const UNSUPPORTED_MARKER = '[Turn rewind unavailable]'
-
-const MAX_TRACKED_NOTICES = 20
-
-export interface UnsupportedNotice {
- id: string
- reason: string
-}
-
-export interface ProjectionState {
- notices: UnsupportedNotice[]
-}
-
-/** 提取一条 user/message 事件里的 heads-up 负载(按插件 source 匹配,文本标记兜底)。 */
-export function extractUnsupportedNotice(event: unknown): UnsupportedNotice | undefined {
- const candidate = event as { type?: string, data?: { content?: unknown, id?: unknown, source?: { plugin?: string, form?: string } } } | undefined
- if (candidate?.type !== 'user/message')
- return undefined
- const message = candidate.data
- const text = Array.isArray(message?.content)
- ? (message.content as { type?: string, text?: string }[]).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: unknown): ProjectionState {
- if (typeof value !== 'object' || value === null || !Array.isArray((value as ProjectionState).notices))
- throw new Error('TURNREWIND_PROJECTION_SHAPE: expected { notices: Array<{ id, reason }> }')
- return value as ProjectionState
-}
-
-/**
- * Build the `turnrewind` projection unit. Registered on `ctx.sessionProjections`;
- * the registry requires `.parse` validators — hand-rolled ones keep this plugin
- * dependency-free.
- */
-export function createDialogProjection() {
- return {
- key: 'turnrewind',
- stateVersion: 1,
- stateSchema: { parse: parseNoticesValue },
- init: (): ProjectionState => ({ notices: [] }),
- apply(state: ProjectionState, event: unknown): ProjectionState {
- 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: ProjectionState) => ({ notices: state.notices }),
- },
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts
deleted file mode 100644
index 4e82c754..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * host/service/doctor.ts — /undo --doctor 只读诊断。
- *
- * 生产化运维面:undo 出问题时一条命令自查——git 可用性、工作区资格、账本
- * 规模与恢复围栏、快照仓库健康(refs / alternates)、最近 turn 状态、备份
- * 新旧。全部 best-effort:单节失败不炸整份报告,节内以 error 行呈现。
- */
-
-import type { SnapshotStore } from '../types'
-import type { Ledger } from './ledger'
-import { existsSync, statSync } from 'node:fs'
-import { join } from 'pathe'
-import { SNAPSHOT_REF_PREFIX } from '../constants'
-import { createSnapshotStore, gitAvailable, runGitText } from './git-snapshot'
-import { getLatestTurnSummary, listRecoveryWorkspaces } from './ledger'
-import { workspaceForSession, workspaceIssue, workspaceKeyFor } from './undo'
-
-async function describeSnapshotRepo(store: SnapshotStore): Promise<string> {
- const repoDir = store.repoDir
- if (!existsSync(join(repoDir, 'HEAD')))
- return `${repoDir} — not created yet (no turn captured for this workspace)`
- let refCount = 0
- try {
- const refs = await runGitText(repoDir, store.workspaceDir, ['for-each-ref', '--format=%(refname)', SNAPSHOT_REF_PREFIX])
- refCount = refs.split('\n').filter(Boolean).length
- }
- catch (error) {
- return `${repoDir} — error listing refs: ${String((error as Error).message ?? error)}`
- }
- const alternates = join(repoDir, 'objects', 'info', 'alternates')
- const storage = existsSync(alternates) ? 'borrows source objects (alternates)' : 'self-contained'
- return `${repoDir} — ${refCount} snapshot ref(s), ${storage}`
-}
-
-function describeBackup(dataRoot: string): string {
- const backupPath = join(dataRoot, 'ledger.sqlite.bak')
- const stat = statSync(backupPath, { throwIfNoEntry: false })
- if (!stat)
- return `${backupPath} — missing (written on the first host open)`
- const ageHours = Math.round((Date.now() - stat.mtimeMs) / 3600000)
- return `${backupPath} — ${ageHours}h old`
-}
-
-/**
- * 汇总一份诊断报告(纯文本,多行)。入参只依赖账本与数据根,agent 仅用于
- * 会话归属与工作区定位;任何一节失败都降级为该节的 error 行。
- */
-export async function collectDoctorReport(db: Ledger, dataRoot: string, agent: { session: { id: string, header?: { cwd?: string } } }): Promise<string> {
- const lines: string[] = ['Turn rewind doctor']
-
- // 1) git 可用性(探测带进程级缓存)。
- try {
- const available = await gitAvailable()
- lines.push(`git: ${available ? 'available' : 'NOT FOUND on PATH (turns run, undo is disabled)'}`)
- }
- catch (error) {
- lines.push(`git: error — ${String((error as Error).message ?? error)}`)
- }
-
- // 2) 会话工作区资格。
- const workspaceDir = workspaceForSession(agent?.session)
- if (workspaceDir) {
- lines.push(`workspace: ${workspaceDir} (git worktree, eligible)`)
- }
- else {
- const cwd = agent?.session?.header?.cwd
- const issue = typeof cwd === 'string' && cwd.length > 0 ? workspaceIssue(cwd) : undefined
- lines.push(`workspace: NOT ELIGIBLE${issue ? ` — ${issue}` : ' (session has no cwd)'}`)
- }
-
- // 3) 账本规模与恢复围栏。
- try {
- const counts = {
- turns: Number(db.prepare('SELECT COUNT(*) AS n FROM turns').get()?.n ?? 0),
- operations: Number(db.prepare('SELECT COUNT(*) AS n FROM operations').get()?.n ?? 0),
- pendingNotices: Number(db.prepare('SELECT COUNT(*) AS n FROM rewind_notices WHERE status = \'pending\'').get()?.n ?? 0),
- pendingPlans: Number(db.prepare('SELECT COUNT(*) AS n FROM pending_plans WHERE status = \'pending\'').get()?.n ?? 0),
- }
- lines.push(`ledger: healthy (opened with quick_check) — ${counts.turns} turn(s), ${counts.operations} operation(s), ${counts.pendingNotices} pending notice(s), ${counts.pendingPlans} pending plan(s)`)
- const fenced = listRecoveryWorkspaces(db)
- if (fenced.length === 0) {
- lines.push('recovery fence: none')
- }
- else {
- lines.push(`recovery fence: ${fenced.length} workspace(s) BLOCKED — open the recovery panel to resolve`)
- for (const workspace of fenced)
- lines.push(` - ${workspace.workspace_path ?? workspace.workspace_key}: ${workspace.operations.map(op => `${op.kind} → ${op.target_turn_id}`).join('; ')}`)
- }
- }
- catch (error) {
- lines.push(`ledger: error — ${String((error as Error).message ?? error)}`)
- }
-
- // 4) 本会话最近一个 turn 的状态。
- try {
- const cwd = agent?.session?.header?.cwd
- const key = workspaceDir ? workspaceKeyFor(workspaceDir) : (typeof cwd === 'string' && cwd.length > 0 ? workspaceKeyFor(cwd) : undefined)
- const latest = key ? getLatestTurnSummary(db, agent.session.id, key) : undefined
- lines.push(`latest turn in this session: ${latest ? `${latest.turn_id} is ${latest.status} (reversible=${latest.reversible})` : 'none recorded'}`)
- }
- catch (error) {
- lines.push(`latest turn: error — ${String((error as Error).message ?? error)}`)
- }
-
- // 5) 快照仓库健康(工作区未定时跳过)。
- if (workspaceDir) {
- try {
- const store = createSnapshotStore(dataRoot, workspaceDir)
- lines.push(`snapshot repo: ${await describeSnapshotRepo(store)}`)
- }
- catch (error) {
- lines.push(`snapshot repo: error — ${String((error as Error).message ?? error)}`)
- }
- }
-
- // 6) 备份。
- try {
- lines.push(`ledger backup: ${describeBackup(dataRoot)}`)
- }
- catch (error) {
- lines.push(`ledger backup: error — ${String((error as Error).message ?? error)}`)
- }
-
- // 首行是标题不加符号;其余顶层行统一加「- 」,缩进子行保留原缩进。
- return lines.map((line, index) => index === 0 || line.startsWith(' ') ? line : `- ${line}`).join('\n')
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
deleted file mode 100644
index c132a849..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
+++ /dev/null
@@ -1,936 +0,0 @@
-/**
- * host/service/git-snapshot.ts — 私有快照仓库与路径恢复(git-dir 模式核心)。
- *
- * 模型(OpenCode 式):每个 Git worktree 一个私有 snapshot repo(DSH_HOME/snapshots/
- * <hash>.git),通过 objects/info/alternates 借用源仓库对象;capture 用临时
- * GIT_INDEX_FILE 与源 ignore 语义;undo 只重写工作区文件,绝不触碰用户 HEAD/
- * branch/index/stash(git-state.test 钉死)。
- *
- * 安全边界:路径逃逸/symlink 拒绝、恢复前尺寸检查、外部击杀 reject(不 resolve
- * 半截输出)、超限 blob 单文件报告(tooLarge),以及 alternates 失效自愈
- * (rev-list --missing=print 检测 → 自包含重建)。
- */
-
-import type {
- DiskState,
- PathChange,
- PathState,
- RestoreResult,
- Snapshot,
- SnapshotStore,
- WorkspaceProbe,
-} from '../types'
-import { Buffer } from 'node:buffer'
-import { spawn } from 'node:child_process'
-import { createHash, randomUUID } from 'node:crypto'
-import {
- chmodSync,
- copyFileSync,
- existsSync,
- lstatSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- realpathSync,
- renameSync,
- rmdirSync,
- rmSync,
- writeFileSync,
-} from 'node:fs'
-import { readFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import process from 'node:process'
-import { basename, dirname, join, relative, resolve, sep } from 'pathe'
-import {
- BAK_SUFFIX,
- GIT_PROBE_RETRY_MS,
- GIT_PROBE_TIMEOUT_MS,
- GIT_SUBPROCESS_TIMEOUT_MS,
- GIT_SYMLINK_MODE,
- MAX_FILE_BYTES,
- MAX_OUTPUT_BYTES,
- SNAPSHOT_PATHSPECS,
- SNAPSHOT_REF_PREFIX,
-} from '../constants'
-import { gitUnavailableReason, gitWorkspace } from './git-workspace'
-
-/** 退出判定:只有干净退出(code 0、无信号)才可 resolve。 */
-export function gitExitIsClean(code: number | null, signal: NodeJS.Signals | null): boolean {
- const noSignal = signal === null || signal === undefined
- return code === 0 && noSignal
-}
-
-/**
- * 异步执行一条 git 命令(不阻塞事件循环)。SIGKILL 预算防卡死;外部击杀
- * (close(null, signal) 且非自身超时)reject——resolve 半截输出会把残缺 index
- * 提交成 turn 快照。
- */
-export function runGit(
- repoDir: string,
- workspaceDir: string,
- args: string[],
- extraEnv: Record<string, string> = {},
- maxBytes: number = MAX_OUTPUT_BYTES,
-): Promise<Buffer> {
- 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: Buffer[] = []
- const errors: Buffer[] = []
- let total = 0
- let settled = false
- let timeout: ReturnType<typeof setTimeout>
- const fail = (error: Error): void => {
- 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: Buffer) => {
- 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: Buffer) => {
- 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)
- })
- })
-}
-
-/** 导出给 doctor 等只读诊断使用(与 runGit 同一击杀/超时语义)。 */
-export async function runGitText(repoDir: string, workspaceDir: string, args: string[], extraEnv: Record<string, string> = {}): Promise<string> {
- const output = await runGit(repoDir, workspaceDir, args, extraEnv)
- return output.toString('utf8')
-}
-
-/** 带管道输入的 git 执行(hash-object -w --stdin 等);同样的击杀/超时语义。 */
-function runGitStdin(repoDir: string, workspaceDir: string, args: string[], input: Buffer | string): Promise<Buffer> {
- 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: Buffer[] = []
- const errors: Buffer[] = []
- let settled = false
- let timeout: NodeJS.Timeout
- const fail = (error: Error): void => {
- 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: Buffer) => chunks.push(chunk))
- child.stderr.on('data', (chunk: Buffer) => 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 (our own timeout
- // settled above). fail() owns the settled flag so the promise settles.
- 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)
- })
-}
-
-let gitProbeResult: Promise<boolean> | undefined
-let gitProbeFailedAt = 0
-
-/**
- * PATH 上是否有可用的 git。成功探测进程级缓存;失败探测按 GIT_PROBE_RETRY_MS
- * 过期重试(进程内装好 git/修好 PATH 无需重启 Host)。探测喂给 pre-step barrier,
- * 无预算挂起的 `git --version` 会永远卡住 turn。
- */
-export function gitAvailable(): Promise<boolean> {
- const failedRecently = gitProbeResult !== undefined && gitProbeFailedAt > 0 && Date.now() - gitProbeFailedAt > GIT_PROBE_RETRY_MS
- if (failedRecently) {
- gitProbeResult = undefined
- gitProbeFailedAt = 0
- }
- gitProbeResult ??= new Promise<boolean>((resolvePromise) => {
- const child = spawn('git', ['--version'])
- let settled = false
- let probeTimeout: NodeJS.Timeout
- const settle = (value: boolean): void => {
- if (settled)
- return
- settled = true
- clearTimeout(probeTimeout)
- resolvePromise(value)
- }
- const markFailure = (): void => {
- 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: SnapshotStore): Promise<void> {
- 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<void>((resolvePromise, rejectPromise) => {
- const child = spawn('git', ['init', '--bare', repoDir])
- const errors: Buffer[] = []
- 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: Buffer) => errors.push(chunk))
- child.on('error', (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 errorCode = signal ? 'TURNREWIND_GIT_FAILED' : 'TURNREWIND_GIT_INIT'
- rejectPromise(new Error(`${errorCode}: ${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: string): string {
- if (typeof ref !== 'string' || !ref.startsWith(SNAPSHOT_REF_PREFIX) || ref.includes('..') || ref.includes(String.fromCharCode(92)) || ref.includes('//'))
- throw new Error(`TURNREWIND_REF_UNSUPPORTED: ${String(ref)}`)
- return ref
-}
-
-/**
- * P2-11: 所有插值进 git 参数的 commit/reffed 参数统一过校验——只接受
- * `refs/turnrewind/*` ref 名或 40 位 SHA(gitRef/captureSnapshot 的返回
- * 形态)。ledger 之外的取值在这里被拦下,而不是散落到各 git 子进程。
- */
-function assertCommitRef(commit: string): string {
- if (typeof commit !== 'string' || !(commit.startsWith(SNAPSHOT_REF_PREFIX) || /^[0-9a-f]{40}$/.test(commit)))
- throw new Error(`TURNREWIND_REF_UNSUPPORTED: ${String(commit)}`)
- return commit
-}
-
-export async function gitRef(repoDir: string, workspaceDir: string, ref: string): Promise<string | undefined> {
- try {
- const output = await runGitText(repoDir, workspaceDir, ['rev-parse', '--verify', normalizeSnapshotRef(ref)])
- return output.trim()
- }
- catch {
- return undefined
- }
-}
-
-function assertSafePath(workspaceDir: string, path: string): string {
- const root = resolve(workspaceDir)
- const target = resolve(root, path)
- if (target !== root && !target.startsWith(`${root}${sep}`))
- throw new Error(`TURNREWIND_PATH_ESCAPE: ${path}`)
- // Defense in depth: the workspace root itself is never a restorable path.
- // A path that normalizes to the root would make a restore delete the whole
- // workspace instead of one file.
- if (target === root)
- throw new Error(`TURNREWIND_PATH_ESCAPE: ${path} (workspace root cannot be restored)`)
-
- 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 as NodeJS.ErrnoException)?.code === 'ENOENT' || (error as NodeJS.ErrnoException)?.code === 'ENOTDIR')
- continue
- throw error
- }
- }
- return target
-}
-
-/** Windows 路径分隔符(源码里避免裸控制字符,与 guard.ts 同一写法)。 */
-const WINDOWS_PATH_SEPARATOR = String.fromCharCode(92)
-
-/**
- * Detect whether the volume holding `dir` folds case. macOS APFS is
- * case-insensitive by default but can be formatted case-sensitive; on such
- * volumes `Repo` and `repo` are distinct directories and must not collapse
- * into one workspace key (the ledger/lock/snapshot domain would collide and
- * a purge could delete the other workspace's state). The probe is cached per
- * directory; unresolvable/synthetic paths fall back to the platform default
- * so tests can keep passing without a real filesystem.
- */
-const caseSensitivityCache = new Map<string, boolean>()
-
-function isCaseInsensitiveDir(dir: string, platform: string): boolean {
- const cached = caseSensitivityCache.get(dir)
- if (cached !== undefined)
- return cached
- let result: boolean
- try {
- const base = basename(dir)
- const parent = dirname(dir)
- const index = base.search(/[A-Za-z]/u)
- if (index === -1) {
- result = platform === 'darwin'
- }
- else {
- const character = base[index]!
- const toggled = character === character.toLowerCase() ? character.toUpperCase() : character.toLowerCase()
- const variant = join(parent, `${base.slice(0, index)}${toggled}${base.slice(index + 1)}`)
- const originalStat = lstatSync(dir)
- if (existsSync(variant)) {
- const variantStat = lstatSync(variant)
- result = originalStat.dev === variantStat.dev && originalStat.ino === variantStat.ino
- }
- else {
- result = false
- }
- }
- }
- catch {
- result = platform === 'darwin'
- }
- caseSensitivityCache.set(dir, result)
- return result
-}
-
-/**
- * Canonical workspace identity shared by the ledger key, the snapshot repo
- * hash, workspace locks and maintenance purges. `resolve()` alone is not an
- * identity: the same directory is reachable under different spellings —
- * macOS /var → /private/var (os.tmpdir lives behind that symlink) and
- * Windows 8.3 short names (CI runners export TEMP as
- * C:\Users\RUNNER~1\... while the on-disk name is runneradmin) — and one
- * workspace must not split into two snapshot domains. realpathSync folds
- * every spelling of an existing path onto its on-disk form, the same
- * canonical spelling gitWorkspace reports for the worktree, so keys written
- * from a raw cwd and keys computed from the probed worktree always agree;
- * case-insensitive platforms (Windows NTFS, macOS APFS default) then fold
- * casing so one directory cannot spawn two snapshot domains, and Linux
- * stays byte-exact. Unresolvable paths (missing or unreadable) keep the
- * resolved spelling so the key stays deterministic instead of throwing; a
- * later call once the directory exists canonicalizes. `platform` remains
- * injectable for tests.
- */
-export function workspaceKey(workspaceDir: string, platform: string = process.platform): string {
- const normalized = resolve(workspaceDir)
- // realpathSync.native wants native separators: pathe emits forward slashes
- // (and can mangle bare drive roots), so rebuild the Windows form first.
- // `.native` (not plain realpathSync) is load-bearing on Windows: libuv's
- // JS-path realpath keeps 8.3 short names as-is (TEMP=C:\Users\RUNNER~1\...)
- // while `realpathSync.native` (GetFinalPathNameByHandle) expands them to
- // the on-disk long name — verified against a short-spelled git worktree
- // where the two spellings must fold onto ONE key or every look-up splits.
- let canonical = normalized
- try {
- const native = platform === 'win32' ? normalized.replaceAll('/', WINDOWS_PATH_SEPARATOR) : normalized
- canonical = resolve(realpathSync.native(native))
- }
- catch {
- // Missing or unreadable path: the resolved spelling is the best
- // available key and stays stable across calls.
- }
- if (platform === 'win32')
- return canonical.toLowerCase()
- if (platform === 'darwin')
- return isCaseInsensitiveDir(canonical, platform) ? canonical.toLowerCase() : canonical
- return canonical
-}
-
-export function workspaceHash(workspaceDir: string): string {
- 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: string, workspaceDir: string): SnapshotStore {
- 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 {
- rootDir,
- 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: string): WorkspaceProbe {
- 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: SnapshotStore, refName: string, message: string, parentRef?: string): Promise<Snapshot> {
- 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: SnapshotStore, commit: string): Promise<boolean> {
- 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 as Error).message}`)
- return false
- }
-}
-
-async function captureInto(store: SnapshotStore, refName: string, message: string, parentRef?: string): Promise<Snapshot> {
- const { repoDir, workspaceDir, sourceIndexPath } = store
- await ensureRepository(store)
- let parent: string | undefined
- 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: SnapshotStore, beforeCommit: string, afterCommit: string): Promise<string[]> {
- assertCommitRef(beforeCommit)
- assertCommitRef(afterCommit)
- const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--name-only', '-z', '--no-renames', beforeCommit, afterCommit])
- return [...new Set(output.toString('utf8').split('\0').filter(Boolean))]
-}
-
-const DEFAULT_MAX_DIFF_LINES = 120
-
-function truncateDiff(text: string, maxLines: number = DEFAULT_MAX_DIFF_LINES): string {
- const lines = text.replace(/\n$/u, '').split('\n')
- if (lines.length <= maxLines || lines[0] === '')
- return lines[0] === '' ? '' : lines.join('\n')
- return `${lines.slice(0, maxLines).join('\n')}\n… (${lines.length - maxLines} more line(s) truncated)`
-}
-
-/** Classify how one path changed between two snapshots: created, deleted, or modified. */
-export async function classifyPathChange(store: SnapshotStore, beforeCommit: string, afterCommit: string, path: string): Promise<PathChange> {
- const before = await stateAt(store, beforeCommit, path)
- const after = await stateAt(store, afterCommit, path)
- if (before.kind === 'absent' && (after.kind === 'file' || after.kind === 'unsupported'))
- return 'created'
- if ((before.kind === 'file' || before.kind === 'tooLarge' || before.kind === 'unsupported') && after.kind === 'absent')
- return 'deleted'
- return 'modified'
-}
-
-/** Unified diff of one path between two snapshot commits, truncated to maxLines. */
-export async function snapshotFileDiff(store: SnapshotStore, fromCommit: string, toCommit: string, path: string, maxLines?: number): Promise<string> {
- assertCommitRef(fromCommit)
- assertCommitRef(toCommit)
- // --ignore-cr-at-eol 与冲突检测的 CRLF 规范化同语义:换行符翻转不画成
- // 幽灵增删(同一行删一遍又加一遍),预览只呈现内容变化。
- const output = await runGit(store.repoDir, store.workspaceDir, ['diff', '--no-renames', '--ignore-cr-at-eol', 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: SnapshotStore): Promise<string> {
- 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: SnapshotStore, commit: string, path: string): Promise<string> {
- if (!await commitEntryInfo(store, commit, path))
- return ensureEmptyBlob(store)
- return (await runGit(store.repoDir, store.workspaceDir, ['rev-parse', `${commit}:${path}`])).toString('utf8').trim()
-}
-
-async function hashDiskFile(store: SnapshotStore, workspaceDir: string, path: string): Promise<string | undefined> {
- 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'], await readFile(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: SnapshotStore, commit: string, path: string, maxLines?: number): Promise<string> {
- assertCommitRef(commit)
- const from = await blobFor(store, commit, path)
- const to = await hashDiskFile(store, store.workspaceDir, path)
- if (to === undefined)
- 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',
- '--ignore-cr-at-eol',
- '--src-prefix=snapshot/',
- '--dst-prefix=disk/',
- from,
- to,
- ])
- return truncateDiff(output.toString('utf8'), maxLines)
-}
-
-/**
- * 一次 `ls-tree -l` 读取条目的 mode、type 与 size:stateAt/restorePath/blobFor
- * 共用,避免同一路径多次子进程调用。size 为 undefined 表示未知(submodule)。
- */
-interface CommitEntryInfo {
- mode: string
- type: string
- size: number | undefined
-}
-
-async function commitEntryInfo(store: SnapshotStore, commit: string, path: string): Promise<CommitEntryInfo | undefined> {
- 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 meta = line.slice(0, tab).split(' ')
- const size = Number(meta.at(-1))
- return {
- mode: meta[0] ?? '100644',
- type: meta[1] ?? 'blob',
- size: Number.isFinite(size) && meta.at(-1) !== '-' ? size : undefined,
- }
- }
- }
- return undefined
-}
-
-async function commitBytes(store: SnapshotStore, commit: string, path: string): Promise<Buffer> {
- 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: Buffer): string {
- let comparable: Uint8Array = 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: SnapshotStore, commit: string, path: string): Promise<PathState> {
- // stateAt only inspects the private snapshot repo (commit:path revisions),
- // never the filesystem.
- // P1-3: a symlink entry ('120000') must not masquerade as a regular file —
- // its blob is just the link target text. Report it as unsupported so the
- // plan flags it and restore refuses, instead of writing wrong content.
- // P2-11: gitlink/submodule 条目(type 'commit')同样 unsupported——blob 是
- // commit hash,写回会是错误内容。
- assertCommitRef(commit)
- const info = await commitEntryInfo(store, commit, path)
- if (!info)
- return { kind: 'absent', digest: null }
- if (info.mode === GIT_SYMLINK_MODE || info.type === 'commit')
- return { kind: 'unsupported', digest: null }
- // Oversized blobs are reported instead of thrown: the caller can mark the
- // entry and continue, so one huge file never aborts a whole undo preview.
- if ((info.size ?? 0) > MAX_FILE_BYTES)
- return { kind: 'tooLarge', digest: null }
- const bytes = await commitBytes(store, commit, path)
- return { kind: 'file', digest: digest(bytes), mode: info.mode }
-}
-
-export async function currentState(workspaceDir: string, path: string): Promise<DiskState> {
- 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 }
- // Windows 无法可靠识别可执行位(git core.filemode=false),统一按 100644 报告;
- // POSIX 取真实权限位,使 mode 差异能进入冲突可视与恢复路径。文件读取走异步,
- // 大文件的冲突检测不再阻塞事件循环。
- const mode = process.platform === 'win32'
- ? '100644'
- : `100${(info.mode & 0o777).toString(8).padStart(3, '0')}`
- return { kind: 'file', digest: digest(await readFile(target)), mode }
-}
-
-/**
- * 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: string, attempts: number = 5): void {
- for (let attempt = 0; ; attempt += 1) {
- try {
- rmSync(target, { force: true })
- return
- }
- catch (error) {
- const code = (error as NodeJS.ErrnoException)?.code
- const retryable = code === 'EBUSY' || code === 'EPERM' || code === 'EACCES'
- if (retryable && attempt < attempts) {
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30)
- continue
- }
- throw error
- }
- }
-}
-
-/**
- * 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 complete 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.
- */
-export async function restorePath(store: SnapshotStore, commit: string, path: string): Promise<RestoreResult> {
- assertCommitRef(commit)
- let target = assertSafePath(store.workspaceDir, path)
- const entry = await commitEntryInfo(store, commit, path)
- // P1-5: the git subprocess above opens a TOCTOU window — an external
- // process can swap a parent directory for a symlink/junction in that gap.
- // Re-validate the full component chain immediately before any filesystem
- // mutation; the walk is a handful of lstats, cheap per restored path.
- target = assertSafePath(store.workspaceDir, path)
- if (!entry) {
- if (existsSync(target)) {
- const info = lstatSync(target)
- if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path}`)
- if (info.isDirectory()) {
- // The turn replaced a file with a directory, or the user built a
- // directory at this path after the snapshot. Recursively deleting it
- // can destroy unrelated files that the turn never touched (files
- // ignored by git are not even in the snapshot). Refuse loudly; only
- // an EMPTY directory is removed, since it holds nothing to lose.
- const contents = readdirSync(target)
- if (contents.length > 0)
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is now a non-empty directory; undo will not recursively delete it (remove it manually if intended)`)
- assertSafePath(store.workspaceDir, path)
- // rmdirSync only succeeds on an empty directory: rmSync without
- // recursive throws ERR_FS_EISDIR, and with recursive a file planted
- // between readdir and the delete would be destroyed with the tree.
- rmdirSync(target)
- }
- else {
- assertSafePath(store.workspaceDir, path)
- rmSync(target, { force: true })
- }
- }
- return { path, result: 'removed' }
- }
-
- // P1-3/P2-11: symlink 与 gitlink/submodule 条目绝不能以普通文件形式写回
- // (前者内容是 link target,后者是 commit hash)。单路径稳定错误码,
- // undo 循环计入未恢复清单而不是破坏工作区类型。
- if (entry.mode === GIT_SYMLINK_MODE || entry.type === 'commit')
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a symlink or submodule in the snapshot; undo cannot restore it (recreate it manually if intended)`)
-
- // Restoring an oversized blob would require materializing it through the
- // same output-limited channel. Fail this one path with a stable code so the
- // undo loop can report it as not restored instead of dying mid-plan.
- if ((entry.size ?? 0) > 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)
- // P1-5: second re-validation after the second async subprocess gap.
- target = assertSafePath(store.workspaceDir, path)
- mkdirSync(dirname(target), { recursive: true })
- const temp = `${target}.turnrewind-${randomUUID()}.tmp`
- writeFileSync(temp, bytes, { flag: 'wx' })
- // P1-4: restore the snapshot's git mode (executable bit). Windows chmod
- // only toggles the read-only bit, so this is safe cross-platform.
- chmodSync(temp, entry.mode === '100755' ? 0o755 : 0o644)
- let bak: string | undefined
- try {
- if (existsSync(target)) {
- const info = lstatSync(target)
- // A directory (even an empty one) at the target is refused: restoring a
- // file over it must never recurse into unrelated content, with or
- // without --force. The user removes the directory manually instead.
- if (info.isDirectory())
- throw new Error(`TURNREWIND_UNSUPPORTED_TARGET: ${path} is a directory; undo will not delete it to restore a file`)
- 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 })
- assertSafePath(store.workspaceDir, path)
- renameSync(target, bak)
- }
- try {
- // P1-5: last re-validation before the rename places new content — the
- // window between this check and the rename is the narrowest we can get
- // without an fd-based or sandboxed filesystem API.
- assertSafePath(store.workspaceDir, path)
- 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 as 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: string): string[] {
- const root = resolve(workspaceDir)
- const resurrected: string[] = []
- const visit = (dir: string): void => {
- let entries: import('node:fs').Dirent[]
- try {
- entries = readdirSync(dir, { withFileTypes: true })
- }
- catch {
- return
- }
- for (const entry of entries) {
- const full = join(dir, entry.name)
- // P2-11: Windows junction 的 Dirent 可能报 isDirectory()——递归进
- // junction 会越过 workspace 边界。目录在进入前先 lstat 排除 reparse
- // point(symlink/junction 均命中 isSymbolicLink)。
- if (entry.isDirectory() && entry.name !== '.git' && !entry.name.endsWith(BAK_SUFFIX)) {
- if (lstatSync(full, { throwIfNoEntry: false })?.isSymbolicLink())
- continue
- visit(full)
- }
- if (entry.isFile() && entry.name.endsWith(BAK_SUFFIX)) {
- const target = full.slice(0, -BAK_SUFFIX.length)
- // Windows antivirus/indexers hold brief handles on freshly 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 code = (error as NodeJS.ErrnoException)?.code
- const retryable = code === 'EBUSY' || code === 'EPERM' || 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
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts
deleted file mode 100644
index 4b001685..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/git-workspace.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-/**
- * host/service/git-workspace.ts — 解析真实 Git worktree 的元数据(只读)。
- *
- * spawnSync 只跑本地 rev-parse 元数据查询(SYNC_GIT_TIMEOUT_MS 预算);git 缺失
- * (ENOENT)与非 worktree 目录分别报告,调用方据此给出 TURNREWIND_GIT_UNAVAILABLE
- * 或 TURNREWIND_GIT_REQUIRED 的准确原因。宿主路径处理使用 pathe。
- */
-
-import type { GitWorkspaceInfo } from '../types'
-import { Buffer } from 'node:buffer'
-import { spawn, spawnSync } from 'node:child_process'
-import { existsSync, realpathSync } from 'node:fs'
-import process from 'node:process'
-import { resolve } from 'pathe'
-import { SYNC_GIT_TIMEOUT_MS } from '../constants'
-
-const MAX_OUTPUT_BYTES = 1024 * 1024
-
-interface GitSyncResult {
- ok: boolean
- stdout?: string
- stderr?: string
- status?: number
- error?: NodeJS.ErrnoException
-}
-
-let gitExecutableMissing = false
-
-/** git 不在 PATH 时报告真实原因(否则会把正常 worktree 误报为非 worktree)。 */
-export function gitUnavailableReason(): string | undefined {
- return gitExecutableMissing
- ? 'TURNREWIND_GIT_UNAVAILABLE: the git executable was not found on PATH; file undo is disabled'
- : undefined
-}
-
-function runGitSync(workspaceDir: string, args: string[]): GitSyncResult {
- 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: undefined }
- return { ok: true, stdout: String(result.stdout ?? '').trim() }
-}
-
-/**
- * 解析 canonical Git worktree 与其元数据,不改变任何 Git 状态。
- * 非 worktree 返回 undefined;git 缺失置 gitUnavailableReason 的标志。
- */
-// 进程级解析缓存:同一 cwd 的 rev-parse 结果在短时间内不变,而 turn 领取、
-// pre-step、命令处理都会重复触发解析。TTL 兼顾正确性(新分支/worktree 切换后
-// 元数据仍会刷新)与事件循环友好(冷缓存时一轮同步调用 <100ms)。
-const WORKSPACE_CACHE_TTL_MS = 60 * 1000
-const workspaceCache = new Map<string, { at: number, info: GitWorkspaceInfo | undefined, gitMissing: boolean }>()
-
-/**
- * 单次 rev-parse 同时解析全部元数据:原先每次冷解析要 6 个 spawnSync,
- * 现在合并为 1 个子进程,输出行序与参数顺序一致。
- */
-const REV_PARSE_ARGS = [
- 'rev-parse',
- '--is-inside-work-tree',
- '--show-toplevel',
- '--git-dir',
- '--git-common-dir',
- '--git-path',
- 'index',
- '--git-path',
- 'info/exclude',
-]
-
-/**
- * realpathSync 安全包装:路径不存在时原样返回。macOS 上 /var → /private/var 的
- * symlink 在这里归一。用 `.native` 而非 plain realpathSync 是 Windows 的硬要求:
- * libuv 的 JS-path 实现不会展开 8.3 短名(TEMP=C:\Users\RUNNER~1\... 原样保留),
- * 而 `.native`(GetFinalPathNameByHandle)展开为磁盘上的长名——git 的
- * --show-toplevel 输出的正是长名。若这里不展开,工作区以短名/长名两次调用
- * gitWorkspace → 相对 .git 解析出不同字符串 → ensureRepository 的 gitDir 恒等
- * 检查永远失败(TURNREWIND_GIT_REPOSITORY)。pathe resolve 统一正斜杠。
- */
-function safeRealpath(p: string): string {
- try {
- return resolve(realpathSync.native(p))
- }
- catch {
- return resolve(p)
- }
-}
-
-function resolveInfo(requestedDir: string, stdout: string): GitWorkspaceInfo | undefined {
- const lines = stdout.split(/\r?\n/u).filter(line => line.trim() !== '')
- if (lines.length < 6 || lines[0] !== 'true')
- return undefined
- // P2-11: macOS 上 /var → /private/var 的 symlink 会让两次调用(一次用
- // mkdtemp 路径、一次用 realpath 后的 store.workspaceDir)产生不同字符串
- // 的 gitDir —— ensureRepository 的恒等检查会永远失败。所有绝对路径统一
- // 通过 safeRealpath(realpathSync.native,展开 symlink 与 Windows 8.3 短名)
- // 归一化差异,保证同一 workspace 的两次调用产生完全一致的路径。--git-dir
- // 等 relative path 以 requestedDir(git 运行的 CWD)为 base 解析。
- const workspaceRoot = safeRealpath(resolve(requestedDir, lines[1]!))
- const resolvedGitDir = safeRealpath(resolve(requestedDir, lines[2]!))
- const resolvedCommonDir = safeRealpath(resolve(requestedDir, lines[3]!))
- const resolvedIndex = resolve(requestedDir, lines[4]!)
- const resolvedInfoExclude = resolve(requestedDir, lines[5]!)
- if (!existsSync(workspaceRoot) || !existsSync(resolvedGitDir) || !existsSync(resolvedCommonDir))
- return undefined
- return {
- workspaceDir: workspaceRoot,
- requestedDir,
- gitDir: resolvedGitDir,
- commonDir: resolvedCommonDir,
- indexPath: resolvedIndex,
- infoExcludePath: resolvedInfoExclude,
- }
-}
-
-function evictOldest(): void {
- if (workspaceCache.size <= 64)
- return
- const oldest = [...workspaceCache.entries()].sort((a, b) => a[1].at - b[1].at)[0]
- workspaceCache.delete(oldest[0])
-}
-
-/** 后台刷新(stale-while-revalidate 的异步半边):结果直接落缓存。 */
-const refreshInflight = new Map<string, Promise<void>>()
-
-function refreshWorkspaceAsync(requestedDir: string): void {
- if (refreshInflight.has(requestedDir))
- return
- const task = new Promise<{ info: GitWorkspaceInfo | undefined, gitMissing: boolean }>((resolvePromise) => {
- const child = spawn('git', ['-c', 'core.quotepath=false', ...REV_PARSE_ARGS], {
- cwd: requestedDir,
- env: { ...process.env },
- })
- const chunks: Buffer[] = []
- let settled = false
- const timeout = setTimeout(() => {
- if (settled)
- return
- settled = true
- child.kill('SIGKILL')
- resolvePromise({ info: undefined, gitMissing: false })
- }, SYNC_GIT_TIMEOUT_MS)
- child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))
- child.on('error', (error: NodeJS.ErrnoException) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- if (error.code === 'ENOENT')
- gitExecutableMissing = true
- resolvePromise({ info: undefined, gitMissing: error.code === 'ENOENT' })
- })
- child.on('close', (code) => {
- if (settled)
- return
- settled = true
- clearTimeout(timeout)
- resolvePromise({ info: code === 0
- ? resolveInfo(requestedDir, Buffer.concat(chunks).toString('utf8'))
- : undefined, gitMissing: false })
- })
- }).then((result) => {
- refreshInflight.delete(requestedDir)
- // git 缺失结果不落缓存,理由同上:PATH 修复后应能立即重新探测。
- if (!result.gitMissing)
- workspaceCache.set(requestedDir, { at: Date.now(), info: result.info, gitMissing: false })
- }).catch(() => {
- refreshInflight.delete(requestedDir)
- })
- refreshInflight.set(requestedDir, task)
-}
-
-export function gitWorkspace(workspaceDir: string): GitWorkspaceInfo | undefined {
- const requestedDir = resolve(workspaceDir)
- gitExecutableMissing = false
- const cached = workspaceCache.get(requestedDir)
- if (cached && Date.now() - cached.at < WORKSPACE_CACHE_TTL_MS)
- return cached.info
- if (cached) {
- // stale-while-revalidate:先回缓存值(元数据短暂陈旧可接受——turn 领取
- // 路径对同步返回有硬约束),后台异步刷新,不再每个 turn 反复阻塞事件循环。
- refreshWorkspaceAsync(requestedDir)
- return cached.info
- }
- // 冷未命中:一次同步 rev-parse。
- const result = runGitSync(requestedDir, REV_PARSE_ARGS)
- if (result.error?.code === 'ENOENT') {
- // ENOENT 不缓存:git 可能在运行中被安装/PATH 被修复,缓存会让后续调用
- // 一直误报 unavailable;每次都重新探测(spawn ENOENT 本身极快)。
- gitExecutableMissing = true
- return undefined
- }
- const info = result.ok ? resolveInfo(requestedDir, result.stdout ?? '') : undefined
- workspaceCache.set(requestedDir, { at: Date.now(), info, gitMissing: false })
- evictOldest()
- return info
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/guard.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/guard.ts
deleted file mode 100644
index abc44ee0..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/guard.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * host/service/guard.ts — 系统目录工作区拒绝(家目录/祖先/盘根)。
- *
- * Git 目录模式不再做全目录预算扫描:Git ignore 语义决定快照面,本守卫只保留
- * 「绝不可快照」的系统目录判定。pathe 输出正斜杠而宿主 cwd 可能带反斜杠,
- * 比较前统一归一化分隔符;pathe 对「已绝对的盘根」(resolve('C:/') → '/C:')
- * 有怪输出,normalize 前先把裸盘符恢复成盘根形态。
- */
-
-import { realpathSync } from 'node:fs'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { parse, resolve } from 'pathe'
-
-const BACKSLASH = String.fromCharCode(92)
-
-function normalizeDir(path: string): string {
- const raw = resolve(path)
- // pathe resolve('C:/') 产 '/C:'(丢失盘根语义);恢复为 'C:/'。
- const corrected = process.platform === 'win32' && /^\/[a-z]:$/i.test(raw)
- ? `${raw.slice(1)}/`
- : raw
- try {
- // realpathSync.native 与 git-workspace/workspaceKey 同一归一化口径:
- // 展开 macOS /var → /private/var 与 Windows 8.3 短名(plain realpathSync
- // 不会展开短名),保证系统目录判定不接受「换个拼写绕过」的路径。
- const fsPath = process.platform === 'win32'
- ? corrected.replaceAll('/', BACKSLASH)
- : corrected
- return realpathSync.native(fsPath)
- }
- catch {
- // Missing or unreadable paths still need a deterministic comparison key.
- return corrected
- }
-}
-
-function foldCase(path: string): string {
- const folded = process.platform === 'win32' ? path.toLowerCase() : path
- return folded.replaceAll(BACKSLASH, '/')
-}
-
-export function isSystemSensitiveWorkspace(workspaceDir: string): boolean {
- const workspace = foldCase(normalizeDir(workspaceDir))
- // P2-11: UNC 共享(//server/share/...)——分享根(仅 server/share 两段)
- // 是一整台机器的导出面,快照范围不可控,直接拒绝;更深的子目录允许。
- if (workspace.startsWith('//')) {
- const segments = workspace.split('/').filter(Boolean)
- if (segments.length <= 2)
- return true
- }
- const home = foldCase(normalizeDir(homedir()))
- if (workspace === home)
- return 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}/`))
- return true
- const root = foldCase(parse(workspace).root)
- return root === workspace
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
deleted file mode 100644
index 50ecd8c8..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
+++ /dev/null
@@ -1,878 +0,0 @@
-/**
- * host/service/ledger.ts — SQLite 账本(turns / operations / notices / pending plans)。
- *
- * WAL 模式;所有多写点变更走单事务(BEGIN/COMMIT)。turn 生命周期、undo 计划、
- * 一次性提示与恢复围栏(needs-recovery)的持久状态都住在这里。
- */
-
-import { createHash, randomUUID } from 'node:crypto'
-import { mkdirSync, renameSync, rmSync, statSync } from 'node:fs'
-import { DatabaseSync } from 'node:sqlite'
-import { dirname, join } from 'pathe'
-import { PENDING_PLAN_TTL_MS } from '../constants'
-
-/** 账本备份间隔(24h):ledger.sqlite.bak 是损坏时的唯一自愈来源。 */
-const LEDGER_BACKUP_INTERVAL_MS = 24 * 60 * 60 * 1000
-
-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 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,
- 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,
- turns_json TEXT NOT NULL DEFAULT '[]',
- paths_json TEXT NOT NULL DEFAULT '[]',
- status TEXT NOT NULL DEFAULT 'pending',
- created_at TEXT NOT NULL,
- claimed_at TEXT,
- kind TEXT NOT NULL DEFAULT 'rewind',
- reason TEXT
- );
- 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
- );
- CREATE INDEX IF NOT EXISTS turns_session_idx ON turns(session_id, started_at);
- CREATE INDEX IF NOT EXISTS turns_workspace_idx ON turns(workspace_key, settled_at);
- CREATE INDEX IF NOT EXISTS operations_target_idx ON operations(target_turn_id);
- CREATE INDEX IF NOT EXISTS rewind_notices_session_idx ON rewind_notices(session_id, status, created_at);
-`
-
-export interface TurnRow {
- turn_id: string
- session_id: string
- parent_turn_id: string | null
- workspace_key: string
- status: string
- started_at: string
- settled_at: string | null
- before_ref: string | null
- after_ref: string | null
- reversible: number
- error: string | null
-}
-
-export interface OperationRow {
- operation_id: string
- kind: string
- target_turn_id: string
- requested_at: string
- settled_at: string | null
- outcome: string | null
- before_ref: string | null
- after_ref: string | null
- error: string | null
-}
-
-export interface NoticeRow {
- notice_id: string
- session_id: string
- workspace_key: string
- target_turn_id: string | null
- turns_json: string
- paths_json: string
- status: string
- created_at: string
- claimed_at: string | null
- kind: string
- reason: string | null
-}
-
-export interface PendingPlanRow {
- plan_id: string
- session_id: string
- workspace_key: string
- turn_id: string
- paths_json: string
- status: string
- result_text: string | null
- created_at: string
- expires_at: string
- /** 预览时的快照绑定(P1-2);旧格式行为 NULL,confirm 时跳过严格校验。 */
- before_ref: string | null
- after_ref: string | null
- paths_digest: string | null
-}
-
-export type Ledger = DatabaseSync
-
-/**
- * 滚动备份:VACUUM INTO 输出一致性快照(WAL 下亦然),写 .pending 后原子
- * 改名,失败不阻断打开(openLedger 无 logger 注入,console.warn 兜底一行)。
- * 独立导出:测试可强制补拍(TTL 内的二次备份默认跳过)。
- */
-export function backupLedger(db: Ledger, dbPath: string, { force = false }: { force?: boolean } = {}): void {
- const backupPath = `${dbPath}.bak`
- try {
- const stat = statSync(backupPath, { throwIfNoEntry: false })
- if (!force && stat && Date.now() - stat.mtimeMs < LEDGER_BACKUP_INTERVAL_MS)
- return
- const pending = `${backupPath}.pending`
- rmSync(pending, { force: true })
- db.exec(`VACUUM INTO '${pending.replaceAll('\'', '\'\'')}'`)
- rmSync(backupPath, { force: true })
- renameSync(pending, backupPath)
- }
- catch (error) {
- console.warn(`turnrewind: ledger backup failed (continuing): ${String(error)}`)
- }
-}
-
-export function openLedger(rootDir: string): Ledger {
- const path = join(rootDir, 'ledger.sqlite')
- mkdirSync(dirname(path), { recursive: true })
- const db = new DatabaseSync(path)
- // P1-7: 并发写遇 SQLITE_BUSY 时等待而非立即抛错——瞬时锁冲突不应被
- // 上层误判为状态漂移并触发永久围栏。
- db.exec('PRAGMA busy_timeout = 5000')
- // 生产保险:损坏账本宁可显式拒绝加载(undo 不可用、turn 照常执行),
- // 也不要在半 corrupt 的库上继续写入扩大损伤。恢复路径:用 ledger.sqlite.bak
- // 还原,或清空数据目录重建。拒绝前必须关闭句柄(否则 Windows 上文件被锁,
- // 用户连还原备份都做不到)。
- let check: { quick_check?: string } | undefined
- try {
- check = db.prepare('PRAGMA quick_check(1)').get() as { quick_check?: string } | undefined
- }
- catch (error) {
- db.close()
- throw new Error(`TURNREWIND_LEDGER_CORRUPT: ${path}: ${(error as Error).message}`)
- }
- if (check?.quick_check !== 'ok') {
- db.close()
- throw new Error(`TURNREWIND_LEDGER_CORRUPT: ${path}: ${check?.quick_check ?? 'unreadable'} — restore ledger.sqlite.bak or clear the data dir`)
- }
- db.exec(SCHEMA)
- // Older local prototypes may already have the table; add new columns idempotently.
- for (const migration of [
- 'ALTER TABLE operations ADD COLUMN after_ref TEXT',
- 'ALTER TABLE rewind_notices ADD COLUMN turns_json TEXT NOT NULL DEFAULT \'[]\'',
- 'ALTER TABLE rewind_notices ADD COLUMN kind TEXT NOT NULL DEFAULT \'rewind\'',
- 'ALTER TABLE rewind_notices ADD COLUMN reason TEXT',
- 'ALTER TABLE pending_plans ADD COLUMN status TEXT NOT NULL DEFAULT \'pending\'',
- 'ALTER TABLE pending_plans ADD COLUMN result_text TEXT',
- 'ALTER TABLE pending_plans ADD COLUMN before_ref TEXT',
- 'ALTER TABLE pending_plans ADD COLUMN after_ref TEXT',
- 'ALTER TABLE pending_plans ADD COLUMN paths_digest TEXT',
- ]) {
- try {
- db.exec(migration)
- }
- catch {
- // Column already exists.
- }
- }
- // Reopen fence: active turns from a previous host process become
- // abandoned; applying operations become needs-recovery (their workspace
- // refuses new rewind work until purged). Expired plans are swept too.
- db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)
- db.prepare(`UPDATE operations SET outcome = 'needs-recovery', settled_at = COALESCE(settled_at, ?), error = 'plugin restarted while the operation was applying; workspace recovery is required' WHERE outcome = 'applying'`).run(new Date().toISOString())
- // P2-11: 崩溃残留的 applying plan 精确清扫——
- // 目标 turn 已 undone → undo 事务实际完成:plan 标 applied(结果如实);
- // 否则执行状态未知(操作已转 needs-recovery 围栏接管):plan 转 expired。
- db.prepare(`
- UPDATE pending_plans SET status = 'applied',
- result_text = COALESCE(result_text, 'host restarted while this plan was applying; the undo was applied')
- WHERE status = 'applying'
- AND EXISTS (SELECT 1 FROM turns WHERE turns.turn_id = pending_plans.turn_id AND turns.status = 'undone')
- `).run()
- db.prepare(`UPDATE pending_plans SET status = 'expired', result_text = COALESCE(result_text, 'host restarted while this plan was applying') WHERE status = 'applying'`).run()
- prunePendingPlans(db)
- backupLedger(db, path)
- return db
-}
-
-/**
- * 失效 plan 清扫:过期的 pending 行转为 `expired` 永久留档,不删除。
- *
- * 过期只锁执行(confirm 路径按状态拒绝),不抹掉审计记录:卡片里的文件
- * 清单与 diff 来自命令输出文本(对话内永久存在),plan 行保留后状态轮询
- * 返回 expired,用户随时可以回看「当时预览了什么」。settled 行
- * (applied/cancelled)同样永远保留。
- */
-export function prunePendingPlans(db: Ledger): void {
- db.prepare('UPDATE pending_plans SET status = \'expired\' WHERE status = \'pending\' AND expires_at < ?')
- .run(new Date().toISOString())
-}
-
-export function registerWorkspace(db: Ledger, workspaceKey: string, workspacePath: string, snapshotRepo: string): void {
- 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: Ledger, turn: { turnId: string, sessionId: string, workspaceKey: string, startedAt: string, beforeRef?: string }): void {
- db.prepare(`
- INSERT INTO turns(turn_id, session_id, workspace_key, status, started_at, before_ref)
- VALUES (?, ?, ?, 'active', ?, ?)
- `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, turn.beforeRef ?? null)
-}
-
-export function getTurn(db: Ledger, turnId: string): TurnRow | undefined {
- return db.prepare('SELECT * FROM turns WHERE turn_id = ?').get(turnId) as unknown as TurnRow | undefined
-}
-
-export function getLatestSnapshotRef(db: Ledger, workspaceKey: string): string | undefined {
- 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) as { after_ref?: string } | undefined)?.after_ref
-}
-
-export function listChildren(db: Ledger, parentTurnId: string): TurnRow[] {
- return db.prepare('SELECT * FROM turns WHERE parent_turn_id = ? ORDER BY started_at ASC').all(parentTurnId) as unknown as TurnRow[]
-}
-
-export function createOperation(db: Ledger, operation: { operationId: string, kind: string, targetTurnId: string, requestedAt: string, beforeRef?: string }): void {
- 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: Ledger, operationId: string, outcome: string, error?: unknown): void {
- db.prepare('UPDATE operations SET settled_at = ?, outcome = ?, error = ? WHERE operation_id = ?')
- .run(new Date().toISOString(), outcome, error ? String(error) : null, operationId)
-}
-
-export interface RewindNotice {
- noticeId: string
- sessionId: string
- workspaceKey: string
- targetTurnId: string
- paths: string[]
- createdAt: string
- kind?: string
-}
-
-export function queueRewindNotice(db: Ledger, notice: RewindNotice): void {
- 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',
- )
-}
-
-/** 消费即返回的 notice:列名直通 + 解析后的 turns/paths。 */
-export interface ClaimedNotice extends NoticeRow {
- turns: string[]
- paths: string[]
-}
-
-export function claimRewindNotices(db: Ledger, sessionId: string, workspaceKey: string): ClaimedNotice[] {
- const claimedAt = new Date().toISOString()
- // BEGIN IMMEDIATE + 事务内 SELECT:读取与消费在同一个写锁内完成,两个
- // 并发 claim(双 Host 进程)不可能读到同一批 pending 行——事务外的
- // 预读会让第二个调用者返回 0 行更新却仍吐出整批 notice。
- db.exec('BEGIN IMMEDIATE')
- try {
- 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) as unknown as NoticeRow[]
- if (notices.length === 0) {
- db.exec('COMMIT')
- return []
- }
- const statement = db.prepare(`
- UPDATE rewind_notices SET status = 'consumed', claimed_at = ?
- WHERE notice_id = ? AND status = 'pending'
- `)
- for (const notice of notices)
- statement.run(claimedAt, notice.notice_id)
- db.exec('COMMIT')
- // Rows pass through verbatim (snake_case): the JS tests and the host's
- // message builder both consume raw column names.
- return notices.map(notice => ({
- ...notice,
- paths: JSON.parse(notice.paths_json),
- turns: JSON.parse(notice.turns_json || '[]'),
- }))
- }
- catch (error) {
- // ROLLBACK 自身失败(如 BEGIN 未生效)不能掩盖原始错误。
- try {
- db.exec('ROLLBACK')
- }
- catch { /* no active transaction */ }
- throw error
- }
-}
-
-export function listNeedsRecoveryWorkspaces(db: Ledger): string[] {
- 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() as { workspace_key: string }[]).map(row => row.workspace_key)
-}
-
-/**
- * 敏感文件提醒的去重查询:每会话+工作区只发一条(kind 'sensitive-files')。
- * 独立导出:baselineTask 用它避免每 turn 都跑扫描。
- */
-export function hasSensitiveNotice(db: Ledger, sessionId: string, workspaceKey: string): boolean {
- return db.prepare(`
- SELECT 1 FROM rewind_notices
- WHERE session_id = ? AND workspace_key = ? AND kind = 'sensitive-files'
- LIMIT 1
- `).get(sessionId, workspaceKey) !== undefined
-}
-
-/** 写入敏感文件提醒(kind 'sensitive-files',reason 携带文件清单);重复为 no-op。 */
-export function queueSensitiveNotice(db: Ledger, sessionId: string, workspaceKey: string, files: string[]): boolean {
- db.exec('BEGIN IMMEDIATE')
- try {
- if (hasSensitiveNotice(db, sessionId, workspaceKey)) {
- db.exec('COMMIT')
- return false
- }
- 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-sensitive', '[]', ?, 'sensitive-files', ?, 'pending', ?)
- `).run(randomUUID(), sessionId, workspaceKey, JSON.stringify(capNoticePaths(files)), files.join('; '), new Date().toISOString())
- db.exec('COMMIT')
- return true
- }
- catch (error) {
- try {
- db.exec('ROLLBACK')
- }
- catch { /* no active transaction */ }
- throw error
- }
-}
-
-/** 恢复面板行:一个被围 workspace 的 needs-recovery 操作明细。 */
-export interface RecoveryWorkspace {
- workspace_key: string
- workspace_path: string | null
- operations: {
- operation_id: string
- kind: string
- target_turn_id: string
- requested_at: string
- settled_at: string | null
- error: string | null
- }[]
-}
-
-/** 恢复面板数据源:按 workspace 分组的围栏明细(供 UI 与 recover 路由)。 */
-export function listRecoveryWorkspaces(db: Ledger): RecoveryWorkspace[] {
- const rows = db.prepare(`
- SELECT o.operation_id AS operation_id, o.kind AS kind, o.target_turn_id AS target_turn_id,
- o.requested_at AS requested_at, o.settled_at AS settled_at, o.error AS error,
- t.workspace_key AS workspace_key, w.workspace_path AS workspace_path
- FROM operations o
- JOIN turns t ON t.turn_id = o.target_turn_id
- LEFT JOIN workspaces w ON w.workspace_key = t.workspace_key
- WHERE o.outcome = 'needs-recovery'
- ORDER BY COALESCE(o.settled_at, o.requested_at) DESC
- `).all() as unknown as (RecoveryWorkspace['operations'][number] & { workspace_key: string, workspace_path: string | null })[]
- const byWorkspace = new Map<string, RecoveryWorkspace>()
- for (const row of rows) {
- let entry = byWorkspace.get(row.workspace_key)
- if (!entry) {
- entry = { workspace_key: row.workspace_key, workspace_path: row.workspace_path, operations: [] }
- byWorkspace.set(row.workspace_key, entry)
- }
- entry.operations.push({
- operation_id: row.operation_id,
- kind: row.kind,
- target_turn_id: row.target_turn_id,
- requested_at: row.requested_at,
- settled_at: row.settled_at,
- error: row.error,
- })
- }
- return [...byWorkspace.values()]
-}
-
-/**
- * 用户确认「已人工检查该 workspace」后解除恢复围栏:该 workspace 的全部
- * needs-recovery 操作转为 recovery-acknowledged 终态。账本行保留审计;
- * 围栏查询只认 needs-recovery,改写即解锁,重启清扫也不再触碰(它只扫
- * applying)。返回改写行数。
- */
-export function acknowledgeRecovery(db: Ledger, workspaceKey: string): number {
- return Number(db.prepare(`
- UPDATE operations SET outcome = 'recovery-acknowledged',
- error = COALESCE(error, '') || ' [recovery acknowledged at ' || ? || ']'
- WHERE outcome = 'needs-recovery'
- AND target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)
- `).run(new Date().toISOString(), workspaceKey).changes)
-}
-
-/**
- * P1-6:实时围栏查询。needs-recovery 可能发生在任意时刻(账本事务失败的
- * catch 路径),启动时加载的内存集合会过期——围栏判定一律查库。
- */
-export function hasNeedsRecoveryWorkspace(db: Ledger, workspaceKey: string): boolean {
- return db.prepare(`
- SELECT 1
- FROM operations o
- JOIN turns t ON t.turn_id = o.target_turn_id
- WHERE o.outcome = 'needs-recovery' AND t.workspace_key = ?
- LIMIT 1
- `).get(workspaceKey) !== undefined
-}
-
-/** 预览路径集的稳定摘要:排序后 sha256。confirm 时校验计划是否漂移(P1-2)。 */
-export function planPathsDigest(paths: string[]): string {
- return createHash('sha256').update([...paths].sort().join('\0')).digest('hex')
-}
-
-export function createPendingPlan(db: Ledger, plan: PendingPlan): string {
- db.exec('BEGIN IMMEDIATE')
- try {
- // One live plan per session+workspace: a newer preview replaces the older.
- // 被替换的旧 plan 转 expired 留档(审计可见),不再物理删除。
- db.prepare('UPDATE pending_plans SET status = \'expired\' WHERE session_id = ? AND workspace_key = ? AND status = \'pending\'')
- .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, before_ref, after_ref, paths_digest, created_at, expires_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- `).run(
- planId,
- plan.sessionId,
- plan.workspaceKey,
- plan.turnId,
- JSON.stringify(plan.paths),
- plan.beforeRef,
- plan.afterRef,
- planPathsDigest(plan.paths),
- createdAt,
- new Date(Date.now() + PENDING_PLAN_TTL_MS).toISOString(),
- )
- db.exec('COMMIT')
- return planId
- }
- catch (error) {
- try {
- db.exec('ROLLBACK')
- }
- catch {
- // BEGIN IMMEDIATE 失败时没有活动事务,回滚失败不能掩盖原始错误。
- }
- throw error
- }
-}
-
-export interface PendingPlan {
- sessionId: string
- workspaceKey: string
- turnId: string
- paths: string[]
- /** 预览时的 turn 快照 ref,confirm 时校验未被改写(P1-2)。 */
- beforeRef: string
- afterRef: string
-}
-
-/**
- * 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: Ledger, planId: string, sessionId: string): { ok: true, row: PendingPlanRow & { paths: string[] } } | { ok: false, code: number, error: string } {
- const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId) as unknown as PendingPlanRow | undefined
- if (row === undefined)
- return { ok: false, code: 404, error: 'plan not found — run /undo again' }
- if (row.session_id !== sessionId)
- return { ok: false, code: 403, error: 'the plan belongs to another session' }
- // 过期 plan 转 expired 留档但拒绝执行:过期锁的是执行,不是查看。
- if (row.status === 'expired')
- return { ok: false, code: 410, error: 'this plan has expired — run /undo again to preview a fresh plan' }
- 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('UPDATE pending_plans SET status = \'expired\' WHERE plan_id = ? AND status = \'pending\'').run(planId)
- return { ok: false, code: 410, error: 'this plan has expired — run /undo again to preview a fresh plan' }
- }
- 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: Ledger, planId: string): void {
- 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: Ledger, planId: string): (PendingPlanRow & { paths: string[] }) | undefined {
- const row = db.prepare('SELECT * FROM pending_plans WHERE plan_id = ?').get(planId) as unknown as PendingPlanRow | undefined
- if (row === undefined)
- return undefined
- // 过期 pending 转 expired 留档并原样返回(status = 'expired'),
- // 由调用方按状态拒绝执行;行本身保留供审计查看。
- if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
- db.prepare('UPDATE pending_plans SET status = \'expired\' WHERE plan_id = ? AND status = \'pending\'').run(planId)
- row.status = 'expired'
- }
- return { ...row, paths: JSON.parse(row.paths_json) }
-}
-
-/** Dismissal from the ✕ button: workspace key is unknown client-side. */
-export function markPendingPlanCancelled(db: Ledger, planId: string, sessionId: string): boolean {
- 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: Ledger, planId: string, sessionId: string, message: string): void {
- db.prepare(`
- UPDATE pending_plans SET status = 'applied', result_text = ?
- WHERE plan_id = ? AND session_id = ? AND status = 'applying'
- `).run(message, planId, sessionId)
-}
-
-export function getPendingPlanStatus(db: Ledger, planId: string, sessionId: string): { status: string, resultText: string | null } | undefined {
- const row = db.prepare('SELECT plan_id, status, result_text, expires_at FROM pending_plans WHERE plan_id = ? AND session_id = ?').get(planId, sessionId) as unknown as { plan_id: string, status: string, result_text: string | null, expires_at: string } | undefined
- if (row === undefined)
- return undefined
- // 过期 pending 转 expired 留档:状态轮询如实回报,卡片保留留档视图但不再可执行。
- if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {
- db.prepare('UPDATE pending_plans SET status = \'expired\' WHERE plan_id = ? AND status = \'pending\'').run(row.plan_id)
- row.status = 'expired'
- }
- return { status: row.status, resultText: row.result_text }
-}
-
-export function settleTurn(db: Ledger, turnId: string, afterRef: string): void {
- db.prepare('UPDATE turns SET status = \'settled\', settled_at = ?, after_ref = ?, reversible = 1 WHERE turn_id = ?')
- .run(new Date().toISOString(), afterRef, turnId)
-}
-
-export function settleNoopTurn(db: Ledger, turnId: string, afterRef: string): void {
- db.prepare('UPDATE turns SET status = \'settled\', settled_at = ?, after_ref = ?, reversible = 0, error = \'no file changes\' WHERE turn_id = ?')
- .run(new Date().toISOString(), afterRef, turnId)
-}
-
-export function settleInterruptedTurn(db: Ledger, turnId: string, afterRef: string, reason: string): void {
- 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 failTurn(db: Ledger, turnId: string, error: unknown): void {
- db.prepare('UPDATE turns SET status = \'failed\', settled_at = ?, reversible = 0, error = ? WHERE turn_id = ?')
- .run(new Date().toISOString(), String(error), turnId)
-}
-
-export function skipTurn(db: Ledger, turn: { turnId: string, sessionId: string, workspaceKey: string, startedAt: string }, reason: string): void {
- db.prepare(`
- INSERT INTO turns(turn_id, session_id, workspace_key, status, started_at, settled_at, reversible, error)
- VALUES (?, ?, ?, 'skipped', ?, ?, 0, ?)
- `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, new Date().toISOString(), reason)
-}
-
-/** skipped turn + 每会话/工作区一次性 heads-up(去重由 rewind_notices 承担)。 */
-export function recordSkippedTurn(db: Ledger, turn: { turnId: string, sessionId: string, workspaceKey: string, startedAt: string }, reason: string): void {
- db.exec('BEGIN IMMEDIATE')
- 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) {
- try {
- db.exec('ROLLBACK')
- }
- catch {
- // BEGIN IMMEDIATE 失败时没有活动事务,回滚失败不能掩盖原始错误。
- }
- throw error
- }
-}
-
-export function markTurnSnapshotMissing(db: Ledger, turnId: string): void {
- db.prepare('UPDATE turns SET reversible = 0, error = \'snapshot ref missing (snapshot repository was wiped)\' WHERE turn_id = ?').run(turnId)
-}
-
-export function listReversibleTurns(db: Ledger, sessionId: string, workspaceKey: string): TurnRow[] {
- 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) as unknown as TurnRow[]
-}
-
-export interface LatestTurnSummary {
- turn_id: string
- workspace_key: string
- status: string
- reversible: number
- settled_at: string | null
-}
-
-export function getLatestTurnSummary(db: Ledger, sessionId: string, workspaceKey?: string): LatestTurnSummary | undefined {
- if (workspaceKey === undefined) {
- 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) as unknown as LatestTurnSummary | undefined
- }
- return db.prepare(`
- SELECT turn_id, workspace_key, status, reversible, settled_at
- FROM turns WHERE session_id = ? AND workspace_key = ? ORDER BY started_at DESC LIMIT 1
- `).get(sessionId, workspaceKey) as unknown as LatestTurnSummary | undefined
-}
-
-export function getLatestTurn(db: Ledger, sessionId: string, workspaceKey: string): TurnRow | undefined {
- 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) as unknown as TurnRow | undefined
-}
-
-export function getLatestAppliedUndo(db: Ledger, sessionId: string, workspaceKey: string): OperationRow | undefined {
- return db.prepare(`
- SELECT * FROM operations
- WHERE kind = 'undo' AND outcome = 'applied'
- AND target_turn_id IN (SELECT turn_id FROM turns WHERE session_id = ? AND workspace_key = ?)
- ORDER BY settled_at DESC LIMIT 1
- `).get(sessionId, workspaceKey) as unknown as OperationRow | undefined
-}
-
-/** 消费超过 7 天的 notice 行删除;pending 与近期行保留(弹窗去重语义)。 */
-export function pruneConsumedNotices(db: Ledger, maxAgeMs: number = 7 * 24 * 60 * 60 * 1000): number {
- const cutoff = new Date(Date.now() - maxAgeMs).toISOString()
- return Number(db.prepare('DELETE FROM rewind_notices WHERE status = \'consumed\' AND claimed_at < ?').run(cutoff).changes)
-}
-
-/** notice 路径清单上限(P1-4):超出部分以摘要行代替,防账本行与模型上下文膨胀。 */
-export const MAX_NOTICE_PATHS = 500
-
-function capNoticePaths(paths: string[]): string[] {
- return paths.length > MAX_NOTICE_PATHS
- ? [...paths.slice(0, MAX_NOTICE_PATHS), `…and ${paths.length - MAX_NOTICE_PATHS} more path(s)`]
- : paths
-}
-
-/** undo 完成事务:turn → undone、operation → applied、notice 入队。 */
-export interface UndoCompletion {
- noticeId: string
- sessionId: string
- workspaceKey: string
- targetTurnId: string
- restoredPaths: string[]
- /** 恢复失败的单路径清单(含原因),随 operation.error 与 notice 持久化。 */
- notRestored: { path: string, reason: string }[]
- operationId: string
- createdAt: string
-}
-
-/**
- * 完成一次 undo 的唯一入口:单事务内校验并落 turn/operation/notice。
- *
- * - turn 允许从 settled 或 interrupted 进入 undone(interrupted turn 的文件
- * 同样会被恢复,状态必须跟着走,否则会残留在可撤销列表里被重复 undo);
- * - 两个 UPDATE 各带状态条件,changes !== 1 即状态漂移:事务回滚且
- * operation 落 needs-recovery,交给启动围栏拦截该 workspace;
- * - 未恢复路径写入 operation.error 与 notice,让审计和 redo 知道部分失败。
- */
-export function completeUndoTransaction(db: Ledger, completion: UndoCompletion): 'undone' | 'needs-recovery' {
- const summary = completion.notRestored.length > 0
- ? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')
- : null
- db.exec('BEGIN IMMEDIATE')
- try {
- const turn = db.prepare(`
- UPDATE turns SET status = 'undone', settled_at = ?
- WHERE turn_id = ? AND status IN ('settled', 'interrupted') AND reversible = 1
- `).run(new Date().toISOString(), completion.targetTurnId)
- if (turn.changes !== 1)
- throw new Error(`TURN_STATE_MISMATCH: turn ${completion.targetTurnId} is not in a restorable state`)
- const operation = db.prepare(`
- UPDATE operations SET outcome = 'applied', settled_at = ?, error = ?
- WHERE operation_id = ? AND outcome = 'applying'
- `).run(new Date().toISOString(), summary, completion.operationId)
- if (operation.changes !== 1)
- throw new Error(`OPERATION_STATE_MISMATCH: operation ${completion.operationId} is not applying`)
- 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', ?, 'undo')
- `).run(
- completion.noticeId,
- completion.sessionId,
- completion.workspaceKey,
- completion.targetTurnId,
- JSON.stringify([completion.targetTurnId]),
- JSON.stringify(capNoticePaths([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)])),
- completion.createdAt,
- )
- db.exec('COMMIT')
- return 'undone'
- }
- catch (error) {
- try {
- db.exec('ROLLBACK')
- }
- catch {
- // 回滚失败不掩盖原始错误;needs-recovery 围栏写入仍要执行。
- }
- // 账本未能完成:operation 落 needs-recovery,启动围栏将拦截该 workspace
- db.prepare(`
- UPDATE operations SET outcome = 'needs-recovery', settled_at = ?, error = ?
- WHERE operation_id = ? AND outcome = 'applying'
- `).run(new Date().toISOString(), String((error as Error).message), completion.operationId)
- throw error
- }
-}
-
-/** redo 完成事务的输入:旧 undo operation + 本次 redo 自己的 applying operation。 */
-export interface RedoCompletion {
- noticeId: string
- sessionId: string
- workspaceKey: string
- targetTurnId: string
- /** 被重做的旧 undo operation(applied 状态)。 */
- redoneOperationId: string
- /** 本次 redo 登记的 operation(applying 状态)。 */
- operationId: string
- restoredPaths: string[]
- /** 重做失败的单路径清单(含原因),随 operation.error 与 notice 持久化。 */
- notRestored: { path: string, reason: string }[]
- createdAt: string
-}
-
-/**
- * 完成一次 redo 的唯一入口:单事务内校验并落旧 operation/turn/新 operation/notice。
- *
- * - 旧 undo operation 只能从 applied → redone,turn 只能从 undone → settled,
- * 任一 UPDATE 命中数 !== 1 即状态漂移:事务回滚且本次 redo operation 落
- * needs-recovery,交给启动围栏拦截该 workspace(与 undo 路径对等,P0-4);
- * - 未恢复路径写入 operation.error 与 notice,部分重做同样留下持久审计。
- */
-export function completeRedoTransaction(db: Ledger, completion: RedoCompletion): 'settled' | 'needs-recovery' {
- const summary = completion.notRestored.length > 0
- ? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')
- : null
- db.exec('BEGIN IMMEDIATE')
- try {
- const previous = db.prepare(`
- UPDATE operations SET outcome = 'redone', settled_at = ?
- WHERE operation_id = ? AND kind = 'undo' AND outcome = 'applied'
- `).run(new Date().toISOString(), completion.redoneOperationId)
- if (previous.changes !== 1)
- throw new Error(`OPERATION_STATE_MISMATCH: undo operation ${completion.redoneOperationId} is no longer applied`)
- const turn = db.prepare(`
- UPDATE turns SET status = 'settled', reversible = 1, settled_at = ?
- WHERE turn_id = ? AND status = 'undone'
- `).run(new Date().toISOString(), completion.targetTurnId)
- if (turn.changes !== 1)
- throw new Error(`TURN_STATE_MISMATCH: turn ${completion.targetTurnId} is not undone`)
- const operation = db.prepare(`
- UPDATE operations SET outcome = 'applied', settled_at = ?, error = ?
- WHERE operation_id = ? AND outcome = 'applying'
- `).run(new Date().toISOString(), summary, completion.operationId)
- if (operation.changes !== 1)
- throw new Error(`OPERATION_STATE_MISMATCH: operation ${completion.operationId} is not applying`)
- 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(
- completion.noticeId,
- completion.sessionId,
- completion.workspaceKey,
- completion.targetTurnId,
- JSON.stringify([completion.targetTurnId]),
- JSON.stringify(capNoticePaths([...completion.restoredPaths, ...completion.notRestored.map(entry => entry.path)])),
- completion.createdAt,
- )
- db.exec('COMMIT')
- return 'settled'
- }
- catch (error) {
- try {
- db.exec('ROLLBACK')
- }
- catch {
- // 回滚失败不掩盖原始错误;needs-recovery 围栏写入仍要执行。
- }
- // 账本未能完成:redo operation 落 needs-recovery,启动围栏将拦截该 workspace
- db.prepare(`
- UPDATE operations SET outcome = 'needs-recovery', settled_at = ?, error = ?
- WHERE operation_id = ? AND outcome = 'applying'
- `).run(new Date().toISOString(), String((error as Error).message), completion.operationId)
- throw error
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts
deleted file mode 100644
index e2efd7b7..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * host/service/maintenance.ts — 工作区级 turnrewind 数据清除。
- *
- * 只删除本插件自己的 snapshot repo 与账本行;用户 .git、工作区文件与其他
- * workspace 的数据绝不触碰(maintenance.test 钉死)。
- */
-
-import { existsSync, rmSync } from 'node:fs'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { join, resolve } from 'pathe'
-import { workspaceHash, workspaceKey } from './git-snapshot'
-import { openLedger } from './ledger'
-import { acquireWorkspaceLockSync } from './workspace-lock'
-
-export function resolveRootDir(explicit?: string): string {
- if (explicit)
- return resolve(explicit)
- return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
-}
-
-export interface PurgeSummary {
- rootDir: string
- repoDir: string
- repoExisted: boolean
- ledger?: { operations: number, notices: number, plans: number, turns: number, workspaces: number }
-}
-
-/**
- * Remove every piece of turnrewind data bound to one workspace: the private
- * snapshot repository on disk and all ledger rows that reference it.
- *
- * 跨进程互斥(P1-1):purge 是破坏性维护操作,与运行中的 Host(快照捕获、
- * undo 等)互斥;workspace 被占用时直接抛 WorkspaceLockBusyError,由 CLI
- * 提示先停止 Host 再执行。
- */
-export function purgeWorkspace(rootDir: string, workspaceDir: string): PurgeSummary {
- const workspaceIdentity = workspaceKey(workspaceDir)
- const repoDir = join(rootDir, 'snapshots', `${workspaceHash(workspaceDir)}.git`)
- const summary: PurgeSummary = { rootDir, repoDir, repoExisted: false, ledger: undefined }
- const lock = acquireWorkspaceLockSync(rootDir, workspaceDir)
- try {
- const ledgerPath = join(rootDir, 'ledger.sqlite')
- if (existsSync(ledgerPath)) {
- const db = openLedger(rootDir)
- try {
- db.exec('BEGIN IMMEDIATE')
- 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: Number(operations.changes),
- notices: Number(notices.changes),
- plans: Number(plans.changes),
- turns: Number(turns.changes),
- workspaces: Number(workspaces.changes),
- }
- }
- catch (error) {
- try {
- db.exec('ROLLBACK')
- }
- catch {
- // BEGIN IMMEDIATE 失败时没有活动事务,回滚失败不能掩盖原始错误。
- }
- throw error
- }
- finally {
- db.close()
- }
- }
-
- summary.repoExisted = existsSync(repoDir)
- rmSync(repoDir, { recursive: true, force: true })
- return summary
- }
- finally {
- lock.release()
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/planner.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/planner.ts
deleted file mode 100644
index 58cc168a..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/planner.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * host/service/planner.ts — undo 计划的子树聚合与冲突分类(纯函数)。
- */
-
-import type { DiskState, PathState } from '../types'
-import type { TurnRow } from './ledger'
-import { planPathsDigest } from './ledger'
-
-/** 叶序收集 turn 及其全部后代(父撤销的递归范围)。 */
-export function collectDescendantTurns(turn: TurnRow, childrenByParent: Map<string, TurnRow[]>): TurnRow[] {
- const result: TurnRow[] = []
- const visit = (current: TurnRow): void => {
- for (const child of childrenByParent.get(current.turn_id) ?? []) {
- visit(child)
- result.push(child)
- }
- }
- visit(turn)
- result.push(turn)
- return result
-}
-
-export interface PathPlanEntry {
- path: string
- firstTurn: string
- lastTurn: string
-}
-
-/** 聚合多 turn 的路径计划:重叠路径以区间(first→last)表示,不重复。 */
-export function aggregatePathPlan(turns: TurnRow[], pathReader: (turn: TurnRow) => string[]): PathPlanEntry[] {
- const byPath = new Map<string, PathPlanEntry>()
- 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(current: DiskState, expected: PathState): 'safe' | 'conflict' {
- if (current.kind !== expected.kind)
- return 'conflict'
- if (current.digest !== expected.digest)
- return 'conflict'
- return 'safe'
-}
-
-/** pending plan 中参与漂移校验的绑定列(P1-2)。 */
-export interface PendingPlanBinding {
- before_ref: string | null
- after_ref: string | null
- paths_digest: string | null
-}
-
-/**
- * 计划漂移校验(P1-2):确认时的 turn 快照 ref 与重算 diff 必须与预览一致,
- * 即「确认的就是预览时看到的」。绑定列为 NULL 的旧格式 plan(无从校验)
- * 从严处理:一律按漂移拒绝并要求重新预览——宁可多看一次预览,
- * 不可在不可验证的计划上执行恢复。
- */
-export function planDrift(plan: PendingPlanBinding, target: TurnRow, currentPaths: string[]): string | undefined {
- if (plan.before_ref === null || plan.after_ref === null || plan.paths_digest === null)
- return 'the plan predates preview binding and cannot be verified'
- if (target.before_ref !== plan.before_ref || target.after_ref !== plan.after_ref)
- return 'the turn snapshots no longer match the preview'
- if (planPathsDigest(currentPaths) !== plan.paths_digest)
- return 'the change set no longer matches the preview'
- return undefined
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/retention.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/retention.ts
deleted file mode 100644
index a47a8d30..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/retention.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * host/service/retention.ts — 快照容量治理(P2-4)。
- *
- * 约束:快照提交是链式的(每次 capture 以最新 ref 为 parent),删除中间 ref
- * 后 `git gc` 也无法回收(新提交仍可达旧对象)。因此空间治理的两级策略:
- *
- * 1. 保留条数(TURNREWIND_RETAIN_TURNS,默认 50):每个 workspace 只保留
- * 最近 N 个可撤销 turn,更老的标记 reversible=0(账本行保留为审计),
- * 不再作为 /undo 目标。零数据移动、零风险。
- * 2. 仓库重建(TURNREWIND_MAX_SNAPSHOT_MB,默认 1024):快照仓库超限时
- * 整仓删除——下一次 capture 走既有的「parent 丢失 → 重建基线」自愈路径,
- * 空间全量回收;该 workspace 全部可撤销 turn 如实标记 expired,账本与
- * 操作审计保留。
- *
- * 触发点:Host 启动后每个 workspace 首次触碰(ensureRuntime)——此时该
- * workspace 无活动 turn、无进行中的 undo,是唯一无锁需要的静默安全点。
- * 低磁盘提前失败(statfs)属平台能力,留待 sandbox bridge 一并接入。
- */
-
-import type { SnapshotStore } from '../types'
-import type { Ledger } from './ledger'
-import { spawnSync } from 'node:child_process'
-import { existsSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs'
-import process from 'node:process'
-import { join } from 'pathe'
-import { SYNC_GIT_TIMEOUT_MS } from '../constants'
-import { workspaceKey } from './git-snapshot'
-
-/** 每个 workspace 保留的最近可撤销 turn 数。 */
-export const DEFAULT_RETAIN_TURNS = 50
-
-/** 快照仓库容量上限(MB),超过即整仓重建。 */
-export const DEFAULT_MAX_SNAPSHOT_MB = 1024
-
-function readPositiveEnv(name: string): number | undefined {
- const raw = process.env[name]
- if (raw === undefined || raw === '')
- return undefined
- const value = Number(raw)
- return Number.isFinite(value) && value > 0 ? value : undefined
-}
-
-export interface RetentionOptions {
- retainTurns?: number
- maxSnapshotMb?: number
-}
-
-export interface RetentionResult {
- /** 因超出保留条数被标记过期的 turn 数。 */
- expiredByCount: number
- /** 因仓库超限被重建(true 时该 workspace 全部可撤销 turn 同时过期)。 */
- rebuilt: boolean
- /** 重建/过期时一并标记的 turn 数(含 expiredByCount 之外的部分)。 */
- expiredByRebuild: number
- /** 快照仓库当前占用(MB,重建前测量)。 */
- repoSizeMb: number
-}
-
-function directorySizeMb(dir: string): number {
- let total = 0
- const visit = (path: string): void => {
- let entries
- try {
- entries = readdirSync(path, { withFileTypes: true })
- }
- catch {
- return
- }
- for (const entry of entries) {
- const full = join(path, entry.name)
- if (entry.isDirectory()) {
- visit(full)
- }
- else if (entry.isFile()) {
- try {
- total += Number(statSync(full).size)
- }
- catch {
- // 并发清理/AV 句柄:丢一个文件的统计不影响量级判断。
- }
- }
- }
- }
- visit(dir)
- return total / (1024 * 1024)
-}
-
-/**
- * 回收私有仓库中不可达的 loose object。主要来源是 diffAgainstDisk 把冲突文件
- * 的当前磁盘内容 `hash-object -w` 进仓库:这些对象没有任何 ref 可达,反复
- * 预览/冲突 diff 会持续积累,是提前触发整仓重建的主因。prune 只删除不可达
- * 对象(refs/turnrewind/* 链上的对象不受影响),放在容量测量之前,让上限
- * 判断基于治理后的真实占用。同步执行:与 git-workspace 的 rev-parse 同级,
- * 仅在 workspace 首次触碰(每进程每仓库一次)发生。
- */
-function pruneRepoLooseObjects(repoDir: string): void {
- if (!existsSync(join(repoDir, 'HEAD')))
- return
- try {
- spawnSync('git', ['--git-dir', repoDir, 'prune', '--expire=now'], {
- timeout: SYNC_GIT_TIMEOUT_MS,
- killSignal: 'SIGKILL',
- })
- }
- catch {
- // 容量治理尽力而为:prune 失败(git 缺失/被击杀)不影响过期与重建逻辑。
- }
-}
-
-/**
- * 对一个 workspace 执行容量治理。在无活动 turn / 无 undo 的安全点调用
- * (当前唯一调用点:ensureRuntime 的 workspace 首次触碰,调用方持跨进程
- * workspace 锁)。
- */
-export function enforceRetention(db: Ledger, store: SnapshotStore, options: RetentionOptions = {}): RetentionResult {
- const retainTurns = options.retainTurns ?? readPositiveEnv('TURNREWIND_RETAIN_TURNS') ?? DEFAULT_RETAIN_TURNS
- const maxSnapshotMb = options.maxSnapshotMb ?? readPositiveEnv('TURNREWIND_MAX_SNAPSHOT_MB') ?? DEFAULT_MAX_SNAPSHOT_MB
- const workspaceIdentity = workspaceKey(store.workspaceDir)
- const result: RetentionResult = { expiredByCount: 0, rebuilt: false, expiredByRebuild: 0, repoSizeMb: 0 }
-
- // 1) 保留条数:最近 N 个之外的可撤销 turn 标记过期(账本行保留审计)。
- const reversible = db.prepare(`
- SELECT turn_id FROM turns
- WHERE workspace_key = ? AND reversible = 1 AND status IN ('settled', 'interrupted')
- ORDER BY started_at DESC
- `).all(workspaceIdentity) as { turn_id: string }[]
- const excess = reversible.slice(retainTurns)
- const expire = db.prepare(`
- UPDATE turns SET reversible = 0,
- error = 'retention: beyond the most recent kept reversible turns'
- WHERE turn_id = ? AND reversible = 1
- `)
- for (const row of excess)
- result.expiredByCount += Number(expire.run(row.turn_id).changes)
-
- // 2) 容量上限:先回收不可达 loose object,再测量治理后的真实占用;
- // 超限即整仓重建——旧 turn 的 refs 随仓消失,全部如实标记,
- // 下一次 capture 经既有自愈路径建立新基线。
- pruneRepoLooseObjects(store.repoDir)
- result.repoSizeMb = directorySizeMb(store.repoDir)
- if (result.repoSizeMb > maxSnapshotMb) {
- // 两阶段重建:先把 live 仓库整体改名进隔离目录,再删隔离目录。rename
- // 是原子发布点,之后任何一步死亡都自洽——live 路径已空,下次 capture
- // 走既有自愈路径重建基线,账本过期如实;直删在半途死亡会留下一个半删
- // 的 live 目录。固定名隔离目录由本轮先清:同 workspace 的治理已被
- // workspace 锁串行化,残留只可能来自上一轮崩溃。
- const quarantine = `${store.repoDir}.retention-quarantine`
- rmSync(quarantine, { recursive: true, force: true })
- // 先记录本次容量重建将标记过期的行:rename 失败时必须回滚账本,
- // 避免快照仓库还在但所有 turn 已不可撤销(Windows 打开句柄/杀软锁是现实场景)。
- const affected = db.prepare(`
- SELECT turn_id FROM turns
- WHERE workspace_key = ? AND reversible = 1 AND status IN ('settled', 'interrupted')
- `).all(workspaceIdentity) as { turn_id: string }[]
- db.prepare(`
- UPDATE turns SET reversible = 0,
- error = 'retention: snapshot repository rebuilt (size cap)'
- WHERE workspace_key = ? AND reversible = 1 AND status IN ('settled', 'interrupted')
- `).run(workspaceIdentity)
- try {
- renameSync(store.repoDir, quarantine)
- }
- catch (error) {
- const revert = db.prepare(`UPDATE turns SET reversible = 1, error = NULL WHERE turn_id = ?`)
- for (const row of affected)
- revert.run(row.turn_id)
- throw error
- }
- try {
- rmSync(quarantine, { recursive: true, force: true })
- }
- catch {
- // 尽力而为:隔离目录残留不回滚账本(过期已是事实),下一轮治理重试。
- }
- result.rebuilt = true
- result.expiredByRebuild = reversible.length
- }
- return result
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/sensitive.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/sensitive.ts
deleted file mode 100644
index d8433811..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/sensitive.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * host/service/sensitive.ts — 秘密文件快照提醒(启发式,只提醒不改变语义)。
- *
- * Git 目录模式把快照面完全委托给源仓库 ignore 规则:未写进 ignore 的
- * .env/密钥类文件会被捕获进私有快照并可被 /undo 恢复(这是有意的取舍,
- * 见 README「快照范围与敏感文件」)。本模块在会话首次追踪某工作区时做一次
- * 浅层扫描(根 + 两层,上限 500 个文件,跳过 .git/node_modules 等噪音目录),
- * 命中启发式再经 `git check-ignore --stdin` 批量过滤掉已 ignore 的文件——
- * 剩下的就是"会被快照的疑似秘密",由调用方写成每会话/工作区一条的
- * heads-up notice。扫描/探测失败一律静默降级为"无发现":这是提醒,不是门禁。
- */
-
-import { Buffer } from 'node:buffer'
-import { spawn } from 'node:child_process'
-import { readdirSync } from 'node:fs'
-import process from 'node:process'
-import { join } from 'pathe'
-import { SYNC_GIT_TIMEOUT_MS } from '../constants'
-
-/**
- * 基名启发式:.env*、证书/密钥扩展名、常见凭据文件名。宁可漏报不误报——
- * 提醒的措辞由调用方承担,这里只负责"看起来像秘密"。
- */
-const SENSITIVE_NAME: RegExp[] = [
- /^\.env$/i,
- /^\.env\./i,
- /\.(pem|key|pfx|p12|keystore|jks)$/i,
- /^id_rsa/i,
- /^credentials/i,
- /^secrets?/i,
- /^\.npmrc$/i,
-]
-
-function isSensitiveName(name: string): boolean {
- return SENSITIVE_NAME.some(re => re.test(name))
-}
-
-const MAX_SCAN_FILES = 500
-const MAX_SCAN_DEPTH = 2
-const SKIP_DIRS = new Set(['.git', '.turnrewind', 'node_modules'])
-
-function collectCandidates(root: string, rel: string, depth: number, out: string[]): void {
- if (out.length >= MAX_SCAN_FILES)
- return
- let entries: import('node:fs').Dirent[]
- try {
- entries = readdirSync(rel === '' ? root : join(root, rel), { withFileTypes: true })
- }
- catch {
- return
- }
- for (const entry of entries) {
- if (out.length >= MAX_SCAN_FILES)
- return
- const childRel = rel === '' ? entry.name : `${rel}/${entry.name}`
- if (entry.isDirectory()) {
- if (SKIP_DIRS.has(entry.name) || depth >= MAX_SCAN_DEPTH)
- continue
- collectCandidates(root, childRel, depth + 1, out)
- continue
- }
- if (entry.isFile() && isSensitiveName(entry.name))
- out.push(childRel)
- }
-}
-
-/**
- * `git check-ignore -z --stdin` 批量过滤:返回未被 ignore 的候选。
- * git 缺失/超时/异常路径一律返回全部候选(宁可多提醒一次)。
- */
-function filterIgnored(workspaceDir: string, candidates: string[]): Promise<string[]> {
- if (candidates.length === 0)
- return Promise.resolve([])
- return new Promise((resolvePromise) => {
- const child = spawn('git', ['-c', 'core.quotepath=false', 'check-ignore', '-z', '--stdin'], {
- cwd: workspaceDir,
- env: { ...process.env },
- })
- const chunks: Buffer[] = []
- let settled = false
- let timeout: ReturnType<typeof setTimeout> | undefined
- const settle = (value: string[]): void => {
- if (settled)
- return
- settled = true
- if (timeout !== undefined)
- clearTimeout(timeout)
- resolvePromise(value)
- }
- timeout = setTimeout(() => {
- child.kill('SIGKILL')
- settle(candidates)
- }, SYNC_GIT_TIMEOUT_MS)
- child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))
- child.stdin.on('error', () => {})
- child.on('error', () => settle(candidates))
- child.on('close', (code) => {
- // 0 = 有被 ignore 的;1 = 全部未被 ignore;两者都是有效答案。
- if (code !== 0 && code !== 1)
- return settle(candidates)
- const ignored = new Set(Buffer.concat(chunks).toString('utf8').split('\0').filter(Boolean))
- settle(candidates.filter(file => !ignored.has(file)))
- })
- child.stdin.end(candidates.join('\0'))
- })
-}
-
-/** 未被 ignore 的疑似秘密文件(工作区相对、正斜杠路径)。 */
-export async function findUnignoredSensitiveFiles(workspaceDir: string): Promise<string[]> {
- const candidates: string[] = []
- collectCandidates(workspaceDir, '', 0, candidates)
- return filterIgnored(workspaceDir, candidates)
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
deleted file mode 100644
index 159437d7..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ /dev/null
@@ -1,814 +0,0 @@
-/**
- * host/service/undo.ts — undo 执行核心:计划构建/格式化、两阶段 pending plan、
- * 原子恢复(含单文件失败收集)、redo(冻结中)、回滚与 notice 注入消息。
- *
- * 执行不变式:执行前先拍 operation 快照(beforeRef);--skip-conflicts 的回滚
- * 只碰实际尝试过的路径(用户明确保留的冲突文件绝不覆盖);单文件恢复失败
- * 计入「未恢复」清单而不炸整体;操作异常时从 beforeRef 回滚,回滚也失败则
- * 落 needs-recovery 由启动围栏拦截。
- */
-
-import type { PlanEntry, SnapshotStore, UndoInput } from '../types'
-import type { Ledger, PendingPlanRow, TurnRow } from './ledger'
-import { randomUUID } from 'node:crypto'
-import { resolve } from 'pathe'
-import { MAX_FILE_BYTES } from '../constants'
-import {
- captureSnapshot,
- classifyPathChange,
- currentState,
- gitRef,
- probeWorkspace,
- restorePath,
- snapshotDiff,
- snapshotFileDiff,
- stateAt,
- workspaceKey,
-} from './git-snapshot'
-import { isSystemSensitiveWorkspace } from './guard'
-
-/**
- * applyUndo — /undo 命令入口(两阶段流:预览卡 → --confirm 执行)。
- *
- * 依赖 workspaceForAgent/workspaceIssue/workspaceKeyFor(宿主装配层的判定),
- * 经 WorkspaceEnv 注入保持本文件可独立单测。
- */
-
-import {
- claimPendingPlan,
- completeRedoTransaction,
- completeUndoTransaction,
- createOperation,
- createPendingPlan,
- getLatestAppliedUndo,
- getLatestTurnSummary,
- getTurn,
- listReversibleTurns,
- markPendingPlanApplied,
- markPendingPlanCancelled,
- markTurnSnapshotMissing,
- releasePendingPlanClaim,
- settleOperation,
-} from './ledger'
-
-import { classifyUndo, planDrift } from './planner'
-import { acquireWorkspaceLock } from './workspace-lock'
-
-// ————————————————— redo(与 undo 同等的生产加固:applying operation / 失败明细 / needs-recovery) —————————————————
-
-async function applyRedo(runtime: WorkspaceRuntime, invocation: UndoInvocation, workspaceDir: string, workspaceKey: string): Promise<UndoOutcome> {
- 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: string[] = []
- for (const path of paths) {
- const expected = await stateAt(runtime.store, turn.before_ref, path)
- const actual = await currentState(workspaceDir, path)
- if (classifyUndo(actual, expected) === 'conflict')
- conflicts.push(path)
- }
- if (conflicts.length > 0) {
- const lines: string[] = []
- 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 {
- // 与 undo 相同的跨进程互斥(P1-1);redo 虽被入口冻结,加固路径保持一致。
- const lock = await acquireWorkspaceLock(runtime.store.rootDir, runtime.workspaceDir, { waitMs: 10000 })
- try {
- const operationId = randomUUID()
- const beforeRef = `refs/turnrewind/redo-${operationId}`
- await captureSnapshot(runtime.store, beforeRef, `turnrewind redo ${turn.turn_id}`, runtime.parentRef)
- // redo 与 undo 对等:先登记 applying operation,崩溃/账本失败时由
- // needs-recovery 围栏接管,不再留下无围栏的部分 redo(P0-4)。
- createOperation(runtime.db, {
- operationId,
- kind: 'redo',
- targetTurnId: turn.turn_id,
- requestedAt: new Date().toISOString(),
- beforeRef,
- })
- const restoredPaths: string[] = []
- const failedPaths: { path: string, reason: string }[] = []
- for (const path of paths) {
- try {
- await restorePath(runtime.store, turn.after_ref, path)
- restoredPaths.push(path)
- }
- catch (error) {
- // 与 undo 相同的单路径策略:一个文件失败不炸整体,失败明细持久化。
- failedPaths.push({ path, reason: String((error as Error).message ?? error) })
- }
- }
- completeRedoTransaction(runtime.db, {
- noticeId: randomUUID(),
- sessionId: invocation.agent.session.id,
- workspaceKey,
- targetTurnId: turn.turn_id,
- redoneOperationId: op.operation_id,
- operationId,
- restoredPaths,
- notRestored: failedPaths,
- createdAt: new Date().toISOString(),
- })
- runtime.parentRef = beforeRef
- let text = `re-applied ${restoredPaths.length} file(s). The next model request will receive a rewind notice.`
- if (failedPaths.length > 0)
- text += ` Not restored (${failedPaths.length} file(s)): ${failedPaths.map(failure => `${failure.path} (${failure.reason.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.reason})`).join('; ')}.`
- return { kind: 'success', text }
- }
- finally {
- lock.release()
- }
- }
- catch (error) {
- // completeRedoTransaction 已把本次 redo operation 落 needs-recovery,
- // 启动围栏会拦截该 workspace;这里只负责把原因带给用户。
- return { kind: 'error', text: String((error as Error)?.message ?? error) }
- }
- finally {
- runtime.undoing = false
- }
-}
-
-// ————————————————— workspace 判定(与 host/apply 共用的唯一实现) —————————————————
-
-export function workspaceForSession(session: { header?: { cwd?: string } } | undefined): string | undefined {
- 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
-}
-
-export function workspaceForAgent(agent: { session?: { header?: { cwd?: string } } } | undefined): string | undefined {
- return workspaceForSession(agent?.session)
-}
-
-export function workspaceKeyFor(path: string): string {
- return workspaceKey(path)
-}
-
-export function workspaceIssue(workspaceDir: string): string | undefined {
- if (isSystemSensitiveWorkspace(workspaceDir))
- return `TURNREWIND_WORKSPACE_UNSUPPORTED: ${workspaceDir} is a system directory`
- const probe = probeWorkspace(workspaceDir)
- return probe.ok ? undefined : probe.reason
-}
-
-export interface WorkspaceRuntime {
- db: Ledger
- store: SnapshotStore
- workspaceKey: string
- workspaceDir: string
- parentRef: string | undefined
- undoing: boolean
- disposed: boolean
-}
-
-export interface UndoInvocation {
- rawInput: string
- agent: { session: { id: string, header?: { cwd?: string } } }
-}
-
-export interface UndoOutcome {
- kind: 'success' | 'error'
- text: string
-}
-
-/** 解析 /undo 的输入行(turn id / 预览与冲突策略 / 两阶段 confirm/cancel / 诊断)。 */
-export function parseUndoInput(rawInput: string): UndoInput | { error: string } {
- const parts = rawInput.trim().split(/\s+/u).filter(Boolean)
- let turnId: string | undefined
- let dryRun = false
- let preview = false
- let skipConflicts = false
- let force = false
- let redo = false
- let confirm = false
- let cancel = false
- let doctor = 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 === '--doctor')
- doctor = 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 (doctor && (turnId !== undefined || dryRun || preview || skipConflicts || force || redo || confirm || cancel))
- return { error: 'Usage: /undo --doctor (cannot be combined with 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, doctor }
-}
-
-export function assertSessionOwner(target: TurnRow, agent: { session: { id: string } }): UndoOutcome | undefined {
- if (target.session_id !== agent.session.id)
- return { kind: 'error', text: 'The selected turn belongs to another session.' }
- return undefined
-}
-
-function indent(text: string, prefix: string): string {
- return text.split('\n').map(line => prefix + line).join('\n')
-}
-
-async function safeDiffAgainstDisk(store: SnapshotStore, ref: string, path: string): Promise<string> {
- try {
- const { diffAgainstDisk } = await import('./git-snapshot')
- return await diffAgainstDisk(store, ref, path)
- }
- catch {
- return '(unable to inspect the on-disk file safely)'
- }
-}
-
-/** 冲突检测:不可检视路径(symlink/escape)按冲突处理。 */
-async function diskMatchesSnapshot(runtime: WorkspaceRuntime, workspaceDir: string, ref: string, path: string): Promise<boolean> {
- try {
- const { currentState } = await import('./git-snapshot')
- return classifyUndo(await currentState(workspaceDir, path), await stateAt(runtime.store, ref, path)) !== 'conflict'
- }
- catch {
- return false
- }
-}
-
-/** 有界并发 map:大路径数的 undo 计划不再一次起满量 git 子进程(P1-7)。 */
-async function mapWithConcurrency<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
- const results: R[] = Array.from({ length: items.length })
- let next = 0
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
- while (next < items.length) {
- const index = next++
- results[index] = await fn(items[index]!)
- }
- })
- await Promise.all(workers)
- return results
-}
-
-/** 单个 plan 的路径并发预算:每条路径内部还有多次 git 子进程调用。 */
-const PLAN_ENTRY_CONCURRENCY = 8
-
-/**
- * 构建只读 undo 计划:每个路径的变化分类、磁盘是否仍匹配 turn 后快照、
- * before 快照是否超限(超限条目恢复时单文件失败,绝不静默)。
- */
-export async function buildPlanEntries(runtime: WorkspaceRuntime, workspaceDir: string, target: TurnRow, paths: string[]): Promise<PlanEntry[]> {
- return mapWithConcurrency(paths, PLAN_ENTRY_CONCURRENCY, 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',
- unsupported: beforeState.kind === 'unsupported',
- }
- })
-}
-
-function summarizeChanges(entries: PlanEntry[]): string {
- 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}`
-}
-
-export interface PlanFormatOptions {
- preview?: boolean
- dryRun?: boolean
- withDiffs?: boolean
-}
-
-/** P1-4:计划输出的规模上限——清单条数与逐文件 diff 都有界,防 UI/上下文膨胀。 */
-const MAX_LISTED_FILES = 200
-const MAX_DIFF_FILES = 50
-
-function capList<T>(items: T[], max: number): { shown: T[], total: number, omitted: number } {
- return { shown: items.slice(0, max), total: items.length, omitted: Math.max(0, items.length - max) }
-}
-
-function omittedNote(omitted: number, label: string): string {
- return ` …and ${omitted} more ${label} (not listed)`
-}
-
-export async function formatPlan(runtime: WorkspaceRuntime, target: TurnRow, entries: PlanEntry[], options: PlanFormatOptions): Promise<string> {
- const conflicts = entries.filter(entry => entry.conflict)
- const oversized = entries.filter(entry => entry.tooLarge)
- const unsupported = entries.filter(entry => entry.unsupported)
- const lines: string[] = []
- lines.push(`${options.preview ? 'Undo preview' : options.dryRun ? 'Undo plan' : 'Undo preflight'}: turn ${target.turn_id}; ${entries.length} file(s) (${summarizeChanges(entries)}); ${conflicts.length} conflict(s).`)
- const listing = capList(entries.map(entry => `${entry.change.padEnd(8)} ${entry.path}${entry.conflict ? ' [conflict]' : ''}${entry.tooLarge ? ' [too large]' : ''}${entry.unsupported ? ' [unsupported]' : ''}`), MAX_LISTED_FILES)
- for (const line of listing.shown)
- lines.push(` ${line}`)
- if (listing.omitted > 0)
- lines.push(omittedNote(listing.omitted, 'file(s)'))
- if (oversized.length > 0) {
- lines.push('')
- lines.push(`Oversized files (over the ${MAX_FILE_BYTES / (1024 * 1024)} MB restore limit) cannot be restored by this undo; they will be reported as not restored:`)
- for (const entry of oversized)
- lines.push(` ${entry.path}`)
- }
- if (unsupported.length > 0) {
- lines.push('')
- lines.push('Unrestorable entries (symlinks and other unsupported types in the before snapshot) will be reported as not restored; recreate them manually if intended:')
- for (const entry of unsupported)
- lines.push(` ${entry.path}`)
- }
- if (options.preview || options.withDiffs) {
- lines.push('')
- lines.push('Undo will apply (turn output → restored state):')
- const diffFiles = capList(entries, MAX_DIFF_FILES)
- for (const entry of diffFiles.shown) {
- const diff = await snapshotFileDiff(runtime.store, target.after_ref!, target.before_ref!, entry.path)
- lines.push(`--- ${entry.path}`)
- lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')
- }
- if (diffFiles.omitted > 0)
- lines.push(omittedNote(diffFiles.omitted, 'diff(s)'))
- }
- if (conflicts.length > 0) {
- lines.push('')
- lines.push('Conflicts (turn output → current disk; undo would overwrite these changes):')
- const conflictFiles = capList(conflicts, MAX_DIFF_FILES)
- for (const entry of conflictFiles.shown) {
- const diff = await safeDiffAgainstDisk(runtime.store, target.after_ref!, entry.path)
- lines.push(`--- ${entry.path}`)
- lines.push(diff ? indent(diff, ' ') : ' (no textual diff)')
- }
- if (conflictFiles.omitted > 0)
- lines.push(omittedNote(conflictFiles.omitted, 'conflict diff(s)'))
- if (!options.dryRun && !options.preview)
- lines.push('Re-run with --skip-conflicts to restore only the non-conflicted files, or --force to overwrite the conflicts.')
- }
- return lines.join('\n')
-}
-
-export interface NoticeMessage {
- id: string
- role: 'user'
- content: { type: 'text', text: string }[]
- source: {
- kind: 'plugin'
- plugin: string
- form: 'rewind-notice' | 'undo-unavailable-notice' | 'rewind-privacy-notice'
- sections: { name: string, text: string }[]
- }
-}
-
-const PLUGIN_NAME = 'dsh-tauri-turnrewind'
-
-function createRewindNoticeMessage(notice: { notice_id: string, kind?: string, turns: string[], target_turn_id: string, paths: string[] }): NoticeMessage {
- 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: PLUGIN_NAME,
- form: 'rewind-notice',
- sections: [{ name: PLUGIN_NAME, text }],
- },
- }
-}
-
-function createSensitiveNoticeMessage(notice: { notice_id: string, paths: string[] }): NoticeMessage {
- const paths = notice.paths.map(path => `- ${path}`).join('\n')
- const text = [
- '[Turn rewind privacy notice]',
- 'These sensitive-looking files are NOT ignored by the repository\'s ignore rules, so they are captured into the private snapshot repo and restored by /undo:',
- paths,
- '',
- 'If that is not intended, add them to .gitignore or .git/info/exclude — the snapshot scope follows the repository\'s ignore rules on every capture.',
- ].join('\n')
- return {
- id: `turnrewind-notice-${notice.notice_id}`,
- role: 'user',
- content: [{ type: 'text', text }],
- source: {
- kind: 'plugin',
- plugin: PLUGIN_NAME,
- form: 'rewind-privacy-notice',
- sections: [{ name: PLUGIN_NAME, text }],
- },
- }
-}
-
-function createUnsupportedNoticeMessage(notice: { notice_id: string, reason: string | null }): NoticeMessage {
- 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: PLUGIN_NAME,
- form: 'undo-unavailable-notice',
- sections: [{ name: PLUGIN_NAME, text }],
- },
- }
-}
-
-export function createNoticeMessage(notice: { notice_id: string, kind?: string, reason?: string | null, turns?: string[], target_turn_id?: string | null, paths?: string[] }): NoticeMessage {
- if (notice.kind === 'sensitive-files')
- return createSensitiveNoticeMessage({ notice_id: notice.notice_id, paths: notice.paths ?? [] })
- if (notice.kind === 'unsupported')
- return createUnsupportedNoticeMessage({ notice_id: notice.notice_id, reason: notice.reason ?? '' })
- return createRewindNoticeMessage({
- notice_id: notice.notice_id,
- kind: notice.kind,
- turns: notice.turns ?? [],
- target_turn_id: notice.target_turn_id ?? '',
- paths: notice.paths ?? [],
- })
-}
-
-/** 共享 undo 执行器(命令路径与确认 HTTP 路由共用)。 */
-export async function executeUndoRestore(
- runtime: WorkspaceRuntime,
- params: { sessionId: string, workspaceKey: string, target: TurnRow, paths: string[], entries: PlanEntry[], skipConflicts?: boolean },
-): Promise<string> {
- const { sessionId, workspaceKey, target, paths, entries, skipConflicts } = params
- // 跨进程互斥(P1-1):operation 快照、文件恢复与账本事务与另一个进程
- // 对同一 workspace 的 capture/settle/undo 互斥;忙等 10s 后显式报错。
- const lock = await acquireWorkspaceLock(runtime.store.rootDir, runtime.workspaceDir, { waitMs: 10000 })
- try {
- 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: string[] = []
- const failedPaths: { path: string, reason: string }[] = []
- for (const entry of targets) {
- // P1-3: symlink/其他不可恢复类型的快照条目直接跳过并上报,
- // 不再伪装成普通文件写回(restorePath 内还有同规则的双保险)。
- if (entry.unsupported) {
- failedPaths.push({ path: entry.path, reason: 'TURNREWIND_UNSUPPORTED_TARGET: snapshot entry is a symlink or otherwise unrestorable' })
- continue
- }
- 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, reason: String((error as Error).message ?? error) })
- }
- }
- const skippedPaths = skipConflicts
- ? entries.filter(entry => entry.conflict).map(entry => entry.path)
- : []
- // 单事务完成 turn/operation/notice;含 notRestored 明细,部分失败
- // 持久化进 operation.error 与 notice(P0-5)。状态漂移或事务失败时
- // operation 落 needs-recovery,由启动围栏拦截(P0-3)。
- completeUndoTransaction(runtime.db, {
- noticeId: randomUUID(),
- sessionId,
- workspaceKey,
- targetTurnId: target.turn_id,
- restoredPaths,
- notRestored: failedPaths,
- operationId,
- createdAt: new Date().toISOString(),
- })
- 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.reason.includes('TURNREWIND_FILE_TOO_LARGE') ? 'over the size limit' : failure.reason})`).join('; ')}.`
- return text
- }
- catch (error) {
- let rollbackError: unknown = 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)}`)
- }
- }
- finally {
- lock.release()
- }
-}
-
-export async function turnRefsExist(store: SnapshotStore, turn: TurnRow): Promise<boolean> {
- 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),
- )
-}
-
-export interface WorkspaceEnv {
- workspaceForAgent: (agent: { session: { header?: { cwd?: string } } }) => string | undefined
- workspaceIssue: (dir: string) => string | undefined
- workspaceKeyFor: (path: string) => string
-}
-
-export interface ActiveTurnEntry {
- workspaceKey: string
- sessionId: string
-}
-
-export function workspaceHasActiveTurn(active: Map<string, unknown>, workspaceKey: string): boolean {
- for (const entry of active.values() as IterableIterator<ActiveTurnEntry>) {
- if (entry.workspaceKey === workspaceKey)
- return true
- }
- return false
-}
-
-export function workspaceHasActiveTurnForOtherSession(active: Map<string, unknown>, workspaceKey: string, sessionId: string): boolean {
- for (const entry of active.values() as IterableIterator<ActiveTurnEntry>) {
- if (entry.workspaceKey === workspaceKey && entry.sessionId !== sessionId)
- return true
- }
- return false
-}
-
-export async function applyUndo(
- runtime: WorkspaceRuntime,
- active: Map<string, unknown>,
- invocation: UndoInvocation,
- env: WorkspaceEnv = { workspaceForAgent, workspaceIssue, workspaceKeyFor },
-): Promise<UndoOutcome> {
- const parsed = parseUndoInput(invocation.rawInput)
- if ('error' in parsed)
- return { kind: 'error', text: parsed.error }
- // 功能冻结闸门(2026-09-03 审查 P0-4 决策):redo 先禁用、暂不开放。
- // 底层加固已落地并保留测试(applying operation / 失败明细 / needs-recovery
- // 事务),重新开放时把本分支换回 `return applyRedo(...)` 即可。
- if (parsed.redo)
- return { kind: 'error', text: '/undo --redo is temporarily disabled. The most recent undo cannot be re-applied for now.' }
-
- const workspaceDir = env.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 ? env.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 = env.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: TurnRow | undefined
- let planRow: (PendingPlanRow & { paths: string[] }) | undefined
- let pendingPlanClaimed = false
- let pendingPlanCommitted = false
- const abortPendingPlanClaim = (): void => {
- if (pendingPlanClaimed) {
- releasePendingPlanClaim(runtime.db, parsed.turnId!)
- pendingPlanClaimed = false
- }
- runtime.undoing = false
- }
- // Target selection runs BEFORE the execution try/finally below, so a thrown
- // probe (SQLite IOERR/BUSY while reading the ledger) must release the
- // reservation and any claimed plan explicitly. A stranded runtime.undoing
- // would silently refuse every later undo AND make new turns skip their
- // baseline (TURNREWIND_WORKSPACE_BUSY) until the host restarts.
- try {
- 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
- planRow = claim.row
- const pendingTurnId = claim.row.turn_id
- target = getTurn(runtime.db, pendingTurnId)
- if (!target || !await turnRefsExist(runtime.store, target)) {
- abortPendingPlanClaim()
- return { kind: 'error', text: 'The pending plan\'s snapshot data no longer exists. Run /undo again to preview a fresh plan.' }
- }
- }
- else if (parsed.turnId) {
- // Reserve before the first await so a concurrent direct-execute cannot
- // build a plan against disk state this invocation is about to change.
- runtime.undoing = true
- target = getTurn(runtime.db, parsed.turnId)
- if (target && !await turnRefsExist(runtime.store, target)) {
- runtime.undoing = false
- 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 {
- runtime.undoing = true
- // 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)
- }
- }
- }
- catch (error) {
- abortPendingPlanClaim()
- throw error
- }
- if (!target) {
- runtime.undoing = false
- const latest = getLatestTurnSummary(runtime.db, invocation.agent.session.id, workspaceKey)
- const detail = latest
- ? ` Latest turn ${latest.turn_id} is ${latest.status} (reversible=${latest.reversible}).`
- : ''
- return { kind: 'error', text: `No reversible turn was found for this session.${detail}` }
- }
- const ownershipError = assertSessionOwner(target, invocation.agent)
- if (ownershipError) {
- runtime.undoing = false
- abortPendingPlanClaim()
- return ownershipError
- }
- if (target.workspace_key !== workspaceKey) {
- runtime.undoing = false
- 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) {
- runtime.undoing = false
- 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)
- // 计划漂移校验(P1-2):确认时的快照 ref 与重算 diff 必须与预览一致,
- // 保证「确认的就是预览时看到的」。漂移即释放 claim 并要求重新预览。
- if (planRow) {
- const drift = planDrift(planRow, target, paths)
- if (drift) {
- abortPendingPlanClaim()
- return { kind: 'error', text: `${drift} — run /undo again to preview a fresh plan.` }
- }
- }
- if (paths.length === 0) {
- if (pendingPlanClaimed) {
- markPendingPlanApplied(runtime.db, parsed.turnId!, invocation.agent.session.id, 'No file changes were recorded for this turn.')
- 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,
- beforeRef: target.before_ref!,
- afterRef: target.after_ref!,
- })
- 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 as Error)?.message ?? error) }
- }
- }
- finally {
- if (pendingPlanClaimed && !pendingPlanCommitted)
- abortPendingPlanClaim()
- else
- runtime.undoing = false
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts
deleted file mode 100644
index 5574212e..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/**
- * host/service/workspace-lock.ts — 跨进程 workspace 互斥(P1-1)。
- *
- * 进程内的 Map/Promise 互斥只覆盖单个 Host;两个 Host 进程、Host 与 purge
- * 脚本、或重启交叠仍可能同时写同一 workspace 的快照仓库与账本。这里用
- * O_EXCL 锁文件实现跨进程互斥:
- *
- * $DSH_HOME/locks/<workspace-hash>.lock { pid, token, acquiredAt, host }
- *
- * - 持有判定:锁文件存在且 pid 存活且未超 TTL。进程崩溃后 pid 探测立即
- * 失效,下一个申请者接管并重写锁;TTL(30 分钟,远大于 git 子进程 5 分钟
- * 预算链)只作为「持锁进程挂死但 pid 被复用/仍存活」时的兜底。
- * - token 所有权:release 只删除 token 匹配的锁,避免接管误删他人新锁。
- * - 锁放在插件私有目录,不触碰用户工作区;同一进程内调用方保证不嵌套
- * (capture / settle / undo / redo 之间已有 in-process 互斥与 FIFO 顺序)。
- */
-
-import { randomUUID } from 'node:crypto'
-import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { hostname } from 'node:os'
-import process from 'node:process'
-import { dirname, join } from 'pathe'
-import { workspaceHash } from './git-snapshot'
-
-/** 持锁进程挂死(pid 仍被占用)时的接管兜底预算。 */
-export const LOCK_STALE_TTL_MS = 30 * 60 * 1000
-
-/** 忙等重试间隔与总尝试上限(100 次 × 100ms ≈ 10s 等待 + 接管竞态余量)。 */
-const LOCK_RETRY_DELAY_MS = 100
-const LOCK_MAX_ATTEMPTS = 200
-
-interface LockContent {
- pid: number
- token: string
- acquiredAt: string
- host: string
-}
-
-export class WorkspaceLockBusyError extends Error {
- constructor(workspaceDir: string, holder?: LockContent) {
- super(`TURNREWIND_LOCK_BUSY: ${workspaceDir} is locked by another process${holder ? ` (pid ${holder.pid})` : ''}`)
- this.name = 'WorkspaceLockBusyError'
- }
-}
-
-export interface WorkspaceLockHandle {
- release: () => void
-}
-
-function lockPathFor(rootDir: string, workspaceDir: string): string {
- return join(rootDir, 'locks', `${workspaceHash(workspaceDir)}.lock`)
-}
-
-function pidAlive(pid: number): boolean {
- try {
- process.kill(pid, 0)
- return true
- }
- catch (error) {
- // P1-5: EPERM 表示进程存在但当前用户无权发信号——视为存活,
- // 交给 TTL 兜底;ESRCH(及其他)才是真正死亡。
- if ((error as NodeJS.ErrnoException)?.code === 'EPERM')
- return true
- return false
- }
-}
-
-function readLockContent(path: string): LockContent | undefined {
- try {
- const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<LockContent>
- if (typeof parsed.pid === 'number' && typeof parsed.token === 'string' && typeof parsed.acquiredAt === 'string')
- return parsed as LockContent
- return undefined
- }
- catch {
- return undefined
- }
-}
-
-function isStale(content: LockContent | undefined): boolean {
- if (!content)
- return true
- if (!pidAlive(content.pid))
- return true
- return Date.now() - Date.parse(content.acquiredAt) > LOCK_STALE_TTL_MS
-}
-
-function writeLockFile(path: string, token: string): void {
- const payload: LockContent = {
- pid: process.pid,
- token,
- acquiredAt: new Date().toISOString(),
- host: hostname(),
- }
- // 'wx' 是互斥点:同一路径只有一个进程能创建成功。
- const fd = openSync(path, 'wx')
- try {
- writeFileSync(fd, JSON.stringify(payload))
- }
- finally {
- closeSync(fd)
- }
-}
-
-function releaseLockFile(path: string, token: string): void {
- // 只删除自己名下的锁:锁被接管后旧 token 不匹配,留着让接管者清理。
- const current = readLockContent(path)
- if (current?.token === token)
- rmSync(path, { force: true })
-}
-
-/** 异步获取:waitMs 内按 100ms 步长忙等;超时或竞态余量耗尽抛 WorkspaceLockBusyError。 */
-export async function acquireWorkspaceLock(rootDir: string, workspaceDir: string, { waitMs = 0 }: { waitMs?: number } = {}): Promise<WorkspaceLockHandle> {
- const path = lockPathFor(rootDir, workspaceDir)
- mkdirSync(dirname(path), { recursive: true })
- const token = randomUUID()
- const deadline = Date.now() + waitMs
- for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt += 1) {
- try {
- writeLockFile(path, token)
- // P1-5 发布竞态防护:wx 创建到内容写完之间,其他进程可能读到空文件
- // 并判 stale 接管。获锁后回读自检——token 不在(已被接管/覆盖)即
- // 视为未获锁并重试,绝不形成双持锁。
- if (readLockContent(path)?.token !== token) {
- // 锁已被其他进程接管:只清理自己名下的锁(token 不匹配时不会删除),
- // 绝不删除他人的有效锁,否则两个进程会并发写同一 workspace。
- releaseLockFile(path, token)
- continue
- }
- let released = false
- return {
- release() {
- if (released)
- return
- released = true
- releaseLockFile(path, token)
- },
- }
- }
- catch (error) {
- if ((error as NodeJS.ErrnoException)?.code !== 'EEXIST')
- throw error
- const holder = readLockContent(path)
- if (!isStale(holder)) {
- if (holder && Date.now() < deadline) {
- await new Promise(resolvePromise => setTimeout(resolvePromise, LOCK_RETRY_DELAY_MS))
- continue
- }
- throw new WorkspaceLockBusyError(workspaceDir, holder)
- }
- // 过期/残缺锁:接管后立刻重试(rm 与 open 之间的竞态由 'wx' 仲裁)。
- rmSync(path, { force: true })
- }
- }
- throw new WorkspaceLockBusyError(workspaceDir, readLockContent(path))
-}
-
-/** 同步获取(purge CLI 等 offline 工具):只尝试一次,忙即抛错。 */
-export function acquireWorkspaceLockSync(rootDir: string, workspaceDir: string): WorkspaceLockHandle {
- const path = lockPathFor(rootDir, workspaceDir)
- if (!existsSync(dirname(path)))
- mkdirSync(dirname(path), { recursive: true })
- const token = randomUUID()
- try {
- writeLockFile(path, token)
- }
- catch (error) {
- if ((error as NodeJS.ErrnoException)?.code !== 'EEXIST')
- throw error
- throw new WorkspaceLockBusyError(workspaceDir, readLockContent(path))
- }
- // P1-5: 与异步路径一致的回读自检。
- if (readLockContent(path)?.token !== token) {
- releaseLockFile(path, token)
- throw new WorkspaceLockBusyError(workspaceDir, readLockContent(path))
- }
- let released = false
- return {
- release() {
- if (released)
- return
- released = true
- releaseLockFile(path, token)
- },
- }
-}
-
-/** 在 workspace 锁内执行异步工作:获取失败抛 WorkspaceLockBusyError,成功后保证释放。 */
-export async function withWorkspaceLock<T>(rootDir: string, workspaceDir: string, work: () => Promise<T>, { waitMs = 0 }: { waitMs?: number } = {}): Promise<T> {
- const handle = await acquireWorkspaceLock(rootDir, workspaceDir, { waitMs })
- try {
- return await work()
- }
- finally {
- handle.release()
- }
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/host/types/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/host/types/index.ts
deleted file mode 100644
index 7057c123..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/host/types/index.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * host/types/index.ts — 宿主侧共享类型。
- *
- * SQLite 账本行、快照状态与 Git 子进程结果的形状集中在 barrel;跨文件协议
- * (pending plan、undo 结果)也在此定义,组件/服务文件不得重复声明。
- */
-
-export type HostContext = any
-
-/** 快照仓库句柄:一个 Git worktree 对应一个私有 snapshot repo。 */
-export interface SnapshotStore {
- /** 数据根目录($DSH_HOME),workspace 锁文件的定位依赖它。 */
- rootDir: string
- repoDir: string
- workspaceDir: string
- sourceGitDir: string
- sourceCommonDir: string
- sourceIndexPath: string
- sourceInfoExclude: string
- /** 自愈降级后为 true:不再写 alternates、不再复制源 index。 */
- selfContained?: boolean
- /** empty blob 缓存(hash-object 惰性写入后复用)。 */
- emptyBlob?: string
-}
-
-/** 一次 capture 的结果:commit id + 规范化后的 ref 名。 */
-export interface Snapshot {
- commit: string
- refName: string
-}
-
-/** 文件在某个快照提交里的状态。mode 为 git 条目 mode('100644'/'100755')。 */
-export type PathState
- = | { kind: 'absent', digest: null }
- | { kind: 'file', digest: string, mode: string }
- | { kind: 'tooLarge', digest: null }
- | { kind: 'unsupported', digest: null }
-
-/** 磁盘当前状态(conflict 检测用)。 */
-export type DiskState = PathState
-
-/** 路径在 turn 内的变化分类。 */
-export type PathChange = 'created' | 'deleted' | 'modified'
-
-/** 恢复单路径的结果。 */
-export type RestoreResult
- = | { path: string, result: 'restored' }
- | { path: string, result: 'removed' }
-
-/** 工作区资格探测结果。 */
-export interface WorkspaceProbe {
- ok: boolean
- workspaceDir?: string
- commonDir?: string
- reason?: string
-}
-
-/** git rev-parse 解析出的源仓库元数据。 */
-export interface GitWorkspaceInfo {
- workspaceDir: string
- requestedDir: string
- gitDir: string
- commonDir: string
- indexPath: string
- infoExcludePath: string | undefined
-}
-
-/** undo 计划的单路径条目。 */
-export interface PlanEntry {
- path: string
- change: PathChange
- conflict: boolean
- /** before 快照超限:恢复会失败并计入未恢复清单。 */
- tooLarge: boolean
- /** before 快照中的条目不可恢复(symlink 等):恢复会跳过并计入未恢复清单。 */
- unsupported: boolean
-}
-
-/** /undo 命令解析结果(confirm/cancel 为标志;plan id 或 turn id 落在 turnId)。 */
-export interface UndoInput {
- turnId?: string
- dryRun?: boolean
- preview?: boolean
- skipConflicts?: boolean
- force?: boolean
- redo?: boolean
- confirm?: boolean
- cancel?: boolean
- /** 只读诊断:/undo --doctor(不能与其他选项组合)。 */
- doctor: boolean
-}
-
-/** 命令/路由共用的执行结果形状。 */
-export interface UndoOutcome {
- kind: 'success' | 'error'
- text: string
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/index.ts b/archiving/dsh-tauri-turnrewind-ts/src/index.ts
deleted file mode 100644
index b84d5602..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/index.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * dsh-tauri-turnrewind 宿主侧(node half):turn 级工作区撤销(Git 目录快照模式)。
- *
- * 三层目录(host / client / shared):
- * - index.ts(本文件) public barrel:只保留导出面(name/inject/apply/领域能力);
- * - shared/constants.ts 跨 half 协议常量(插件名 / API 前缀 / storage 基名);
- * - host/ Node half(apply 装配 / service 领域 / routes HTTP 路由);
- * - client/ Browser half(两阶段 undo 卡片 / 不可用弹窗 / 轮询)。
- *
- * 模型(OpenCode 式 Git 目录快照):
- * 1. 会话 cwd 必须位于 Git worktree(子目录归并到根;非 Git 记 skipped);
- * 2. 每个工作区一个私有 snapshot repo($DSH_HOME/snapshots/<hash>.git),经
- * alternates 借用源仓库对象;ignore 语义委托源仓库;
- * 3. turn 开始前 barrier 拍 before 快照,turn/end 后拍 after 快照;
- * 4. /undo 两阶段:预览卡(红绿 diff)→ ✓(经 /api/turnrewind/confirm)→ 恢复;
- * 5. 恢复是原子 bak-swap;崩溃窗口由启动清扫复活;绝不触碰用户 HEAD/index。
- */
-
-export { apply, inject, name, turnSnapshotRef, waitForTurnBaseline } from './host/apply'
-export { jsonRoute } from './host/routes'
-export { createDialogProjection } from './host/service/dialog-projection'
-export {
- captureSnapshot,
- createSnapshotStore,
- currentState,
- gitAvailable,
- gitExitIsClean,
- gitRef,
- probeWorkspace,
- restoreCrashedSwaps,
- restorePath,
- runGit,
- snapshotDiff,
- snapshotFileDiff,
- stateAt,
- workspaceHash,
- workspaceKey,
-} from './host/service/git-snapshot'
-export { gitUnavailableReason, gitWorkspace } from './host/service/git-workspace'
-export { isSystemSensitiveWorkspace } from './host/service/guard'
-export { openLedger } from './host/service/ledger'
-export { purgeWorkspace, resolveRootDir } from './host/service/maintenance'
-export { classifyUndo } from './host/service/planner'
-export { enforceRetention } from './host/service/retention'
-export { applyUndo, buildPlanEntries, executeUndoRestore, formatPlan, parseUndoInput, turnRefsExist } from './host/service/undo'
-export { acquireWorkspaceLock, acquireWorkspaceLockSync, withWorkspaceLock, WorkspaceLockBusyError } from './host/service/workspace-lock'
-export { TURNREWIND_API_PREFIX, TURNREWIND_PLUGIN_NAME, TURNREWIND_STORAGE_BASE } from './shared/constants'
diff --git a/archiving/dsh-tauri-turnrewind-ts/src/shared/constants.ts b/archiving/dsh-tauri-turnrewind-ts/src/shared/constants.ts
deleted file mode 100644
index 5f5bae36..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/src/shared/constants.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * shared/constants.ts — 跨 host/client 的稳定协议常量。
- *
- * API 前缀与插件名是两半端共享的线协议面:host 路由注册、client RPC 各自硬编码
- * 会漂移,集中在此由两端共同引用。
- */
-
-/** 插件名(诊断元数据 / registrant / storage key 前缀)。 */
-export const TURNREWIND_PLUGIN_NAME = 'dsh-tauri-turnrewind'
-
-/** HTTP 路由前缀(host route + client rpc 同源 fetch)。 */
-export const TURNREWIND_API_PREFIX = '/api/turnrewind'
-
-/** 弹窗去重的 localStorage 基名(不带冒号,driver 侧拼前缀)。 */
-export const TURNREWIND_STORAGE_BASE = 'dsh-tauri-turnrewind'
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/atomic-restore.test.js b/archiving/dsh-tauri-turnrewind-ts/test/atomic-restore.test.js
deleted file mode 100644
index a7276e3d..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restoreCrashedSwaps, restorePath, stateAt } from '../src/host/service/git-snapshot'
-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/archiving/dsh-tauri-turnrewind-ts/test/barrier.test.js b/archiving/dsh-tauri-turnrewind-ts/test/barrier.test.js
deleted file mode 100644
index 2a4be46c..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 'pathe'
-import { it } from 'vitest'
-import { createSnapshotStore, gitRef } from '../src/host/service/git-snapshot'
-import { apply, turnSnapshotRef } from '../src/index'
-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/archiving/dsh-tauri-turnrewind-ts/test/ci-build.test.js b/archiving/dsh-tauri-turnrewind-ts/test/ci-build.test.js
deleted file mode 100644
index e16b2913..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/ci-build.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import { spawnSync } from 'node:child_process'
-import { existsSync } from 'node:fs'
-import { resolve } from 'node:path'
-import { describe, expect, it } from 'vitest'
-
-// Regression: `CI=true tsdown` used to exit 1 with
-// "ERROR We recommend using the ESM format instead of CommonJS" because tsdown
-// inferred target node22.15.0 from this package's `engines.node` and its default
-// `failOnWarn: 'ci-only'` escalated warnLegacyCJS into a CI failure. The client
-// half pins an explicit es2022 target (see tsdown.config.ts); this test guards
-// the whole contract: CI mode must build cleanly, the legacy-CJS notice must be
-// gone at the source, and dist/client.cjs (the DSH ModuleLoader CJS contract)
-// must still be produced.
-const pkgDir = resolve(import.meta.dirname, '..')
-const tsdownCli = resolve(pkgDir, 'node_modules/tsdown/dist/run.mjs')
-
-describe('cI build (tsdown failOnWarn: ci-only)', () => {
- it('builds with CI=true without the legacy-CJS error and keeps client.cjs', () => {
- const result = spawnSync(process.execPath, [tsdownCli], {
- cwd: pkgDir,
- env: { ...process.env, CI: 'true' },
- encoding: 'utf8',
- timeout: 90_000,
- windowsHide: true,
- })
-
- expect(result.status).toBe(0)
- expect(result.stderr).not.toContain('We recommend using the ESM format')
- expect(result.stdout).toContain('Build complete')
- expect(existsSync(resolve(pkgDir, 'dist/client.cjs'))).toBe(true)
- }, 120_000)
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/client-view.test.js b/archiving/dsh-tauri-turnrewind-ts/test/client-view.test.js
deleted file mode 100644
index e6756c88..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/client-view.test.js
+++ /dev/null
@@ -1,158 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { peekCardTranslator, peekSubmitLine, setCardTranslator, setSubmitLine } from '../src/client/components/command-view'
-import * as client from '../src/client/index'
-
-it('exposes the cordis plugin face and pure helpers', () => {
- assert.equal(typeof client.apply, 'function')
- // `remote` 必须在列:turn 尾部按钮读 ctx.remote 执行 /undo,未声明 inject 时
- // cordis 代理会抛,整个插件 apply 失败(线上复现过 Failed to load plugins)。
- assert.deepEqual(client.inject, ['slots', 'sessions', 'locale', 'remote'])
- 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', () => {
- // The host route answers 404 once the pending plan expired or was purged.
- 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 = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'gone' })
- assert.deepEqual(explicit, { status: 'gone', stop: true, resultText: null })
-})
-
-it('resolvePlanStatus treats expired as a terminal archived state (not gone)', () => {
- // Expired plans stay in the ledger: the card keeps its archived view and
- // only execution is refused — it must NOT collapse to gone.
- const expired = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'expired' })
- assert.deepEqual(expired, { status: 'expired', stop: true, resultText: null })
-})
-
-it('resolvePlanStatus stops polling once the plan settles', () => {
- 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 = client.resolvePlanStatus({ ok: true, status: 200 }, { status: 'applied' })
- assert.deepEqual(appliedBare, { status: 'applied', stop: true, resultText: null })
- 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 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 settling the plan', () => {
- for (const res of [{ ok: false, status: 500 }, { ok: false, status: 503 }, { ok: true, status: 200 }]) {
- 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', () => {
- 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(client.resolveOwnerSessionId({ node: { sessionId: 'session-b' } }), 'session-b')
-})
-
-it('resolveOwnerSessionId never guesses from missing or invalid ids', () => {
- 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 strips the unsupported flag from unrestorable entries', () => {
- const parsed = client.parseUndoOutput([
- 'Undo preflight: turn s:1; 2 file(s) (modified 2, created 0, deleted 0); 0 conflict(s).',
- ' modified link [unsupported]',
- ' modified keep.txt',
- ].join('\n'))
- assert.deepEqual(
- parsed.files.map(file => [file.path, file.conflict]),
- [['link', false], ['keep.txt', false]],
- )
-})
-
-it('parseUndoOutput still extracts the pending plan id', () => {
- const parsed = client.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 parsed = client.parseUndoOutput([
- 'Undo preflight: turn s:1; 3 file(s) (modified 2, created 1, deleted 0); 1 conflict(s).',
- ' modified my notes.txt',
- // Host formats change.padEnd(8) plus one separator: created has two spaces.
- ' 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)
-})
-
-it('channel setters are latest-owner-wins (HMR interleave guard)', () => {
- const channelA = async () => null
- const channelB = async () => null
- const translatorA = key => key
- const translatorB = key => key
-
- const releaseChannelA = setSubmitLine(channelA)
- const releaseTranslatorA = setCardTranslator(translatorA)
- // A newer install (an HMR successor) takes the channels over.
- const releaseChannelB = setSubmitLine(channelB)
- const releaseTranslatorB = setCardTranslator(translatorB)
-
- // The stale instance's cleanup must not clear the successor's channels.
- releaseChannelA()
- releaseTranslatorA()
- assert.equal(peekSubmitLine(), channelB)
- assert.equal(peekCardTranslator(), translatorB)
-
- // Only the latest owner's release actually clears.
- releaseChannelB()
- releaseTranslatorB()
- assert.equal(peekSubmitLine(), null)
- assert.equal(peekCardTranslator(), null)
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/dialog-projection.test.js b/archiving/dsh-tauri-turnrewind-ts/test/dialog-projection.test.js
deleted file mode 100644
index 0ad3fccb..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 '../src/host/service/dialog-projection'
-
-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/archiving/dsh-tauri-turnrewind-ts/test/doctor.test.js b/archiving/dsh-tauri-turnrewind-ts/test/doctor.test.js
deleted file mode 100644
index 57c644d9..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/doctor.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { collectDoctorReport } from '../src/host/service/doctor'
-import { captureSnapshot, createSnapshotStore, workspaceKey } from '../src/host/service/git-snapshot'
-import { createOperation, insertTurn, openLedger, registerWorkspace, settleOperation, settleTurn } from '../src/host/service/ledger'
-import { parseUndoInput } from '../src/host/service/undo'
-import { commitAll, initGitWorkspace } from './git-test-utils.js'
-
-it('parses --doctor as a standalone flag', () => {
- const alone = parseUndoInput('--doctor')
- assert.ok(!('error' in alone) && alone.doctor)
- const combined = parseUndoInput('--doctor --force')
- assert.ok('error' in combined && /--doctor/.test(combined.error))
-})
-
-it('collects a full read-only doctor report for an eligible workspace', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-doctor-'))
- const workspace = join(root, 'workspace')
- let db
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'a.txt'), 'one')
- await commitAll(workspace, 'initial')
- const dataRoot = join(root, 'data')
- // Close before the temp root is removed even when an assertion fails:
- // an open SQLite handle makes Windows rm fail with EBUSY and masks the
- // real failure (observed on CI).
- db = openLedger(dataRoot)
- const store = createSnapshotStore(dataRoot, workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/doctor-before', 'before')
- await writeFile(join(workspace, 'a.txt'), 'two')
- await captureSnapshot(store, 'refs/turnrewind/doctor-after', 'after', 'refs/turnrewind/doctor-before')
- // The ledger rows are written from the caller's raw spelling while the
- // doctor resolves the key through the canonical probe result. CI temp
- // dirs make the two spellings differ (macOS /var vs /private/var,
- // Windows 8.3 RUNNER~1); workspaceKey must canonicalize both onto one
- // identity or the "latest turn" section below reports none recorded.
- registerWorkspace(db, workspaceKey(workspace), workspace, store.repoDir)
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: workspaceKey(workspace),
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: before.refName,
- })
- settleTurn(db, 'session:1', 'refs/turnrewind/doctor-after')
-
- const report = await collectDoctorReport(db, dataRoot, { session: { id: 'session', header: { cwd: workspace } } })
- assert.match(report, /^Turn rewind doctor$/mu)
- assert.match(report, /git: available/u)
- assert.match(report, /workspace: .+ \(git worktree, eligible\)/u)
- assert.match(report, /ledger: healthy \(opened with quick_check\) — 1 turn\(s\)/u)
- assert.match(report, /recovery fence: none/u)
- assert.match(report, /latest turn in this session: session:1 is settled \(reversible=1\)/u)
- assert.match(report, /snapshot repo: .+ — 2 snapshot ref\(s\), borrows source objects \(alternates\)/u)
- assert.match(report, /ledger backup: .+h old/u)
-
- // A fenced workspace surfaces as blocked with its operations.
- createOperation(db, { operationId: 'op-x', kind: 'undo', targetTurnId: 'session:1', requestedAt: '2026-01-01T00:02:00.000Z' })
- settleOperation(db, 'op-x', 'needs-recovery', 'test')
- const fencedReport = await collectDoctorReport(db, dataRoot, { session: { id: 'session', header: { cwd: workspace } } })
- assert.match(fencedReport, /- recovery fence: 1 workspace\(s\) BLOCKED/u)
- assert.match(fencedReport, /undo → session:1/u)
- }
- finally {
- db?.close()
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/git-gc.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-gc.test.js
deleted file mode 100644
index d5f5ab03..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restorePath, stateAt } from '../src/host/service/git-snapshot'
-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/archiving/dsh-tauri-turnrewind-ts/test/git-ignore.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-ignore.test.js
deleted file mode 100644
index ccd364ac..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 '../src/host/service/git-snapshot'
-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/archiving/dsh-tauri-turnrewind-ts/test/git-kill.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-kill.test.js
deleted file mode 100644
index aee526ac..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, gitExitIsClean, runGit } from '../src/host/service/git-snapshot'
-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/archiving/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
deleted file mode 100644
index ca315f4b..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/git-snapshot.test.js
+++ /dev/null
@@ -1,439 +0,0 @@
-import assert from 'node:assert/strict'
-import { chmod, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt, workspaceHash, workspaceKey } from '../src/host/service/git-snapshot'
-import { completeUndoTransaction, createOperation, getLatestTurn, insertTurn, openLedger, settleInterruptedTurn, settleTurn } from '../src/host/service/ledger'
-import { initGitWorkspace, resolvedRealPath } from './git-test-utils.js'
-
-it('persists entry mode in snapshots and restores the executable bit', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-mode-test-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'run.sh'), '#!/bin/sh\necho hi\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/mode-before', 'before')
- // Windows git (core.filemode=false) always records 100644; POSIX records
- // the real mode. Both platforms must surface the mode on the state.
- assert.equal((await stateAt(store, before.commit, 'run.sh')).mode, '100644')
-
- if (process.platform === 'win32')
- return
-
- // POSIX round trip: the turn flips the exec bit — a mode-only change that
- // must appear in the diff and be restorable with the bit intact.
- await chmod(join(workspace, 'run.sh'), 0o755)
- const after = await captureSnapshot(store, 'refs/turnrewind/mode-after', 'after', before.commit)
- assert.equal((await stateAt(store, after.commit, 'run.sh')).mode, '100755')
- assert.deepEqual(await snapshotDiff(store, before.commit, after.commit), ['run.sh'])
-
- // Clear the bit on disk, then restore from the exec snapshot: the mode
- // comes back with the content.
- await chmod(join(workspace, 'run.sh'), 0o644)
- await restorePath(store, after.commit, 'run.sh')
- const restored = await stat(join(workspace, 'run.sh'))
- assert.ok((restored.mode & 0o111) !== 0, 'executable bit must be restored')
- assert.equal((await currentState(workspace, 'run.sh')).mode, '100755')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('reports snapshot symlinks as unsupported and refuses to restore them', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-snap-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'target.txt'), 'target\n')
- try {
- await symlink(join(workspace, 'target.txt'), join(workspace, 'link'))
- }
- catch (error) {
- if (error.code === 'EPERM' || error.code === 'EACCES')
- return
- throw error
- }
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/symlink-snap', 'snap')
-
- // The snapshot entry has git mode 120000: stateAt reports unsupported
- // instead of masquerading the link target text as file content (P1-3).
- assert.equal((await stateAt(store, snapshot.commit, 'link')).kind, 'unsupported')
-
- // Restore refuses even when the disk link is gone — the blob is only the
- // link target text and must never be written as a regular file.
- await rm(join(workspace, 'link'))
- await assert.rejects(
- () => restorePath(store, snapshot.commit, 'link'),
- /TURNREWIND_UNSUPPORTED_TARGET.*symlink/u,
- )
- assert.equal(await readFile(join(workspace, 'target.txt'), 'utf8'), 'target\n')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-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: workspaceKey(workspace),
- 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: workspaceKey(workspace),
- 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)
- createOperation(db, { operationId: 'op-b', kind: 'undo', targetTurnId: 'session:B', requestedAt: '2026-01-01T00:01:30.000Z' })
- completeUndoTransaction(db, {
- noticeId: 'notice-b',
- sessionId: 'session',
- workspaceKey: workspaceKey(workspace),
- targetTurnId: 'session:B',
- restoredPaths: filesB,
- notRestored: [],
- operationId: 'op-b',
- createdAt: '2026-01-01T00:02:00.000Z',
- })
- assert.equal(getLatestTurn(db, 'session', workspaceKey(workspace)).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((await currentState(workspace, 'line-endings.txt')).digest, (await stateAt(store, after.commit, 'line-endings.txt')).digest)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('renders a line-ending flip plus appends without phantom duplicate lines', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-crlf-diff-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- // Pre-turn file with CRLF endings (the Windows checkout norm).
- await writeFile(join(workspace, 'modified3.txt'), '文件 3\r\n用于测试 undo。\r\n')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- const before = await captureSnapshot(store, 'refs/turnrewind/crlfdiff-before', 'before')
- // The turn rewrites the same content with LF endings and appends two lines.
- await writeFile(join(workspace, 'modified3.txt'), '文件 3\n用于测试 undo。\n额外追加一行。\n额外追加第二行。')
- const after = await captureSnapshot(store, 'refs/turnrewind/crlfdiff-after', 'after', before.commit)
-
- // Byte-exact git cannot pair the two visually identical lines; the
- // --ignore-cr-at-eol preview keeps the ending flip from rendering the
- // line as both deleted and added — only the real content change shows.
- const undoDiff = await snapshotFileDiff(store, after.commit, before.commit, 'modified3.txt')
- assert.match(undoDiff, /-额外追加一行。/u)
- assert.match(undoDiff, /-额外追加第二行。/u)
- assert.doesNotMatch(undoDiff, /\+用于测试 undo。/u)
- }
- 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)
- await assert.rejects(() => currentState(workspace, '../outside.txt'), /TURNREWIND_PATH_ESCAPE/)
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('refuses to restore or inspect the workspace root itself', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-root-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 snapshot = await captureSnapshot(store, 'refs/turnrewind/root-ref', 'snap')
-
- // '.' normalizes to the workspace root; a restore there would delete the
- // whole workspace including .git. Both disk-touching entries must refuse.
- await assert.rejects(restorePath(store, snapshot.commit, '.'), /TURNREWIND_PATH_ESCAPE/)
- await assert.rejects(() => currentState(workspace, '.'), /TURNREWIND_PATH_ESCAPE/)
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'one')
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('refuses a non-empty directory at an absent path and removes an empty one', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-dir-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 before = await captureSnapshot(store, 'refs/turnrewind/dir-before', 'before')
-
- // The turn created a file that the human later replaced by a directory
- // holding unrelated files: undo must not recursively delete that tree.
- await mkdir(join(workspace, 'foo'))
- await writeFile(join(workspace, 'foo', 'user-file.txt'), 'keep me')
- await assert.rejects(
- restorePath(store, before.commit, 'foo'),
- /TURNREWIND_UNSUPPORTED_TARGET.*non-empty directory/u,
- )
- assert.equal(await readFile(join(workspace, 'foo', 'user-file.txt'), 'utf8'), 'keep me')
-
- // An empty directory holds nothing to lose: the restore removes it
- // (regression pin — rmSync without directory semantics throws EISDIR).
- await mkdir(join(workspace, 'bar'))
- assert.deepEqual(await restorePath(store, before.commit, 'bar'), { path: 'bar', result: 'removed' })
- await assert.rejects(stat(join(workspace, 'bar')), { code: 'ENOENT' })
- }
- 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, resolvedRealPath(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')
-})
-
-it('folds path case on case-insensitive platforms only', () => {
- // Windows and macOS (APFS default) treat the two spellings as one
- // workspace; Linux keeps them distinct.
- assert.equal(workspaceKey('C:\\Proj\\One', 'win32'), workspaceKey('c:\\proj\\one', 'win32'))
- assert.equal(workspaceKey('/Users/dev/Proj', 'darwin'), workspaceKey('/Users/dev/proj', 'darwin'))
- assert.notEqual(workspaceKey('/home/dev/Proj', 'linux'), workspaceKey('/home/dev/proj', 'linux'))
-})
-
-it('maps different spellings of one directory to a single workspace identity', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-key-spelling-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- // CI temp dirs are reachable under different spellings: macOS /var vs
- // /private/var (os.tmpdir sits behind that symlink) and Windows 8.3
- // short names (TEMP=C:\Users\RUNNER~1\... on the runner). The caller's
- // spelling and the canonical on-disk spelling must produce one key and
- // one snapshot-repo hash, or a workspace splits into two domains.
- assert.equal(workspaceKey(workspace), workspaceKey(resolvedRealPath(workspace)))
- assert.equal(workspaceHash(workspace), workspaceHash(resolvedRealPath(workspace)))
-
- // A link alias points at the same directory: junctions need no
- // elevation on Windows, plain symlinks cover POSIX.
- const alias = join(root, 'workspace-alias')
- await symlink(workspace, alias, process.platform === 'win32' ? 'junction' : 'dir')
- assert.equal(workspaceKey(alias), workspaceKey(workspace))
- assert.equal(workspaceHash(alias), workspaceHash(workspace))
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/git-state.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-state.test.js
deleted file mode 100644
index 0315013c..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/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 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restorePath } from '../src/host/service/git-snapshot'
-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/archiving/dsh-tauri-turnrewind-ts/test/git-test-utils.js b/archiving/dsh-tauri-turnrewind-ts/test/git-test-utils.js
deleted file mode 100644
index 598b54f9..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/git-test-utils.js
+++ /dev/null
@@ -1,67 +0,0 @@
-import { Buffer } from 'node:buffer'
-import { spawn } from 'node:child_process'
-import { realpathSync } from 'node:fs'
-import { mkdir } from 'node:fs/promises'
-import { resolve } from 'pathe'
-
-/**
- * macOS 上 /var → /private/var 的 symlink 导致 mkdtemp 返回的路径与
- * git --show-toplevel 返回的路径不同;Windows CI 上 TEMP 还可能是 8.3 短名
- * (C:\Users\RUNNER~1\...)而 git 返回磁盘长名。测试比较路径时统一走
- * realpathSync.native + pathe resolve 归一化——`.native` 会把 8.3 短名展开为
- * 长名(plain realpathSync 不会),与生产侧 safeRealpath/workspaceKey 一致。
- */
-export function resolvedRealPath(p) {
- return resolve(realpathSync.native(p))
-}
-
-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/archiving/dsh-tauri-turnrewind-ts/test/git-worktree.test.js b/archiving/dsh-tauri-turnrewind-ts/test/git-worktree.test.js
deleted file mode 100644
index 32940ff5..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/git-worktree.test.js
+++ /dev/null
@@ -1,108 +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 } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, gitRef, restorePath, stateAt } from '../src/host/service/git-snapshot'
-import { commitAll, gitOutput, initGitWorkspace, resolvedRealPath, 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, resolvedRealPath(main))
- assert.equal(linkedStore.workspaceDir, resolvedRealPath(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)
- // store.workspaceDir is the canonical on-disk root (same spelling
- // gitWorkspace reports); the raw mkdtemp spelling may differ on CI
- // (macOS /var vs /private/var, Windows 8.3 RUNNER~1 vs runneradmin).
- assert.equal(subStore.workspaceDir, resolvedRealPath(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', 'refs/turnrewind/packed-before')
- 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/archiving/dsh-tauri-turnrewind-ts/test/guard.test.js b/archiving/dsh-tauri-turnrewind-ts/test/guard.test.js
deleted file mode 100644
index a83aa1c4..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/guard.test.js
+++ /dev/null
@@ -1,106 +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 } from 'pathe'
-import { it } from 'vitest'
-import { createSnapshotStore, probeWorkspace } from '../src/host/service/git-snapshot'
-import { isSystemSensitiveWorkspace } from '../src/host/service/guard'
-import { initGitWorkspace, resolvedRealPath } 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, resolvedRealPath(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, resolvedRealPath(workspace))
-
- const nestedStore = createSnapshotStore(join(root, 'data'), nested)
- const rootStore = createSnapshotStore(join(root, 'data'), workspace)
- assert.equal(nestedStore.repoDir, rootStore.repoDir)
- // store.workspaceDir is the canonical on-disk worktree root (the same
- // spelling gitWorkspace reports). Compare against the canonical form:
- // CI temp dirs are reachable under a raw spelling that differs (macOS
- // /var vs /private/var, Windows 8.3 RUNNER~1 vs runneradmin).
- assert.equal(nestedStore.workspaceDir, resolvedRealPath(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/archiving/dsh-tauri-turnrewind-ts/test/heads-up.test.js b/archiving/dsh-tauri-turnrewind-ts/test/heads-up.test.js
deleted file mode 100644
index e7a7c139..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/heads-up.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { createHeadsUpTracker, resolveSessionsService } from '../src/client/utils/heads-up'
-
-function notice(id, reason = 'r') {
- return { id, reason }
-}
-
-it('seeds the first observation of a session without popping', () => {
- const tracker = createHeadsUpTracker()
- assert.deepEqual(tracker.observe('s1', [notice('a'), notice('b')]), [])
- // Seeded ids never re-pop for the same session.
- assert.deepEqual(tracker.observe('s1', [notice('a'), notice('b')]), [])
-})
-
-it('pops exactly once for notices arriving while the page is alive', () => {
- const tracker = createHeadsUpTracker()
- tracker.observe('s1', [notice('a')])
- assert.deepEqual(tracker.observe('s1', [notice('b')]), [notice('b')])
- // The same notice does not pop twice.
- assert.deepEqual(tracker.observe('s1', [notice('b')]), [])
-})
-
-it('re-seeds when the session switches and treats its history as archived', () => {
- const tracker = createHeadsUpTracker()
- tracker.observe('s1', [notice('a')])
- // Switching to s2: its existing notice is history, not a fresh alert.
- assert.deepEqual(tracker.observe('s2', [notice('b')]), [])
- // Back to s1: its known notice stays archived.
- assert.deepEqual(tracker.observe('s1', [notice('a')]), [])
- // A genuinely new notice in s1 still pops.
- assert.deepEqual(tracker.observe('s1', [notice('c')]), [notice('c')])
-})
-
-it('resolveSessionsService accepts only services with the full list shape', () => {
- const good = { list: { getSnapshot: () => ({}), subscribe: () => () => {} } }
- assert.equal(resolveSessionsService([undefined, null, {}, good]), good)
- assert.equal(resolveSessionsService([{ list: { getSnapshot: () => ({}) } }]), undefined)
- assert.equal(resolveSessionsService([]), undefined)
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/ledger.test.js b/archiving/dsh-tauri-turnrewind-ts/test/ledger.test.js
deleted file mode 100644
index 87cd210e..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/ledger.test.js
+++ /dev/null
@@ -1,870 +0,0 @@
-import assert from 'node:assert/strict'
-import { copyFileSync, existsSync, writeFileSync } from 'node:fs'
-import { mkdtemp, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { acknowledgeRecovery, backupLedger, claimPendingPlan, claimRewindNotices, completeRedoTransaction, completeUndoTransaction, createOperation, createPendingPlan, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurn, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listNeedsRecoveryWorkspaces, listRecoveryWorkspaces, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, planPathsDigest, pruneConsumedNotices, prunePendingPlans, queueRewindNotice, recordSkippedTurn, releasePendingPlanClaim, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from '../src/host/service/ledger'
-
-/** Windows may hold freshly closed sqlite sidecar files briefly: retry, then give up quietly. */
-async function cleanupDir(root) {
- for (let attempt = 0; ; attempt += 1) {
- try {
- await rm(root, { recursive: true, force: true })
- return
- }
- catch (error) {
- if (attempt >= 4 || !['EBUSY', 'EPERM', 'ENOTEMPTY'].includes(error.code))
- return
- await new Promise(resolve => setTimeout(resolve, 150))
- }
- }
-}
-
-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')
- createOperation(db, { operationId: 'op-undo', kind: 'undo', targetTurnId: 'session:undo', requestedAt: '2026-01-01T00:00:30.000Z' })
- completeUndoTransaction(db, {
- noticeId: 'notice-undo',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:undo',
- restoredPaths: ['src/reverted.ts'],
- notRestored: [],
- operationId: 'op-undo',
- 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('never double-claims notices across concurrent ledger connections', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-notice-race-'))
- // Two connections stand in for two host processes sharing one ledger file:
- // the claim is a BEGIN IMMEDIATE transaction, so the reader cannot observe
- // a pending batch that another claimer is about to consume.
- const first = openLedger(root)
- const second = openLedger(root)
- try {
- queueRewindNotice(first, {
- noticeId: 'notice-race',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:1',
- paths: ['src/only.ts'],
- createdAt: '2026-01-01T00:00:00.000Z',
- })
-
- const claimedByFirst = claimRewindNotices(first, 'session', 'workspace')
- assert.equal(claimedByFirst.length, 1)
- assert.equal(claimedByFirst[0].notice_id, 'notice-race')
- // The second connection must see the consumed state, not a stale
- // pre-transaction snapshot of the same pending row.
- assert.deepEqual(claimRewindNotices(second, 'session', 'workspace'), [])
- assert.deepEqual(claimRewindNotices(second, 'session', 'workspace'), [])
- }
- finally {
- first.close()
- second.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('keeps cancelled plans archived across newer previews and past their TTL', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-plan-archive-'))
- const db = openLedger(root)
- try {
- const planA = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'workspace',
- turnId: 'session:1',
- paths: ['a.txt'],
- beforeRef: 'refs/turnrewind/turn-session-1-before',
- afterRef: 'refs/turnrewind/turn-session-1-after',
- })
- assert.equal(markPendingPlanCancelled(db, planA, 'session'), true)
-
- // A newer preview archives only the pending predecessor: the user's
- // explicit dismissal stays 'cancelled' — refresh must reproduce it.
- const planB = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'workspace',
- turnId: 'session:2',
- paths: ['b.txt'],
- beforeRef: 'refs/turnrewind/turn-session-2-before',
- afterRef: 'refs/turnrewind/turn-session-2-after',
- })
- assert.equal(getPendingPlanStatus(db, planA, 'session')?.status, 'cancelled')
-
- // Past-TTL sweeping (startup or lazy) flips only pending rows.
- db.prepare('UPDATE pending_plans SET expires_at = ?').run(new Date(Date.now() - 1000).toISOString())
- prunePendingPlans(db)
- assert.equal(getPendingPlanStatus(db, planA, 'session')?.status, 'cancelled')
- assert.equal(getPendingPlanStatus(db, planB, 'session')?.status, 'expired')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('backs up a healthy ledger and refuses a corrupt one', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-bak-'))
- try {
- const db = openLedger(root)
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: 'workspace',
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/turn-session-1-before',
- })
- // Open-time backup predates this insert: force a second snapshot so the
- // .bak carries the row (the 24h TTL would otherwise skip it).
- backupLedger(db, join(root, 'ledger.sqlite'), { force: true })
- db.close()
-
- const backupPath = join(root, 'ledger.sqlite.bak')
- assert.equal(existsSync(backupPath), true)
-
- // The documented recovery path: a corrupt ledger is replaced by its
- // backup and opens cleanly (schema valid, rows from the backup remain).
- const corrupt = 'this is not a sqlite database, just garbage bytes'.repeat(64)
- writeFileSync(join(root, 'ledger.sqlite'), corrupt)
- assert.throws(() => openLedger(root), /TURNREWIND_LEDGER_CORRUPT|database/u)
- copyFileSync(backupPath, join(root, 'ledger.sqlite'))
- const restored = openLedger(root)
- assert.equal(restored.prepare('SELECT COUNT(*) AS n FROM turns').get().n, 1)
- restored.close()
- }
- finally {
- // Windows may briefly hold freshly closed sqlite sidecar files, and the
- // temp dir removal can hit EBUSY/EPERM long after every close: swallow —
- // a leaked temp dir is harmless, a masked assertion is not.
- await cleanupDir(root).catch(() => {})
- }
-})
-
-it('lists fenced workspaces for recovery and lifts the fence on acknowledgement', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-recovery-'))
- const db = openLedger(root)
- try {
- // A turn whose undo landed needs-recovery (transaction failure path).
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: 'c:\\proj\\one',
- 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-one', kind: 'undo', targetTurnId: 'session:1', requestedAt: '2026-01-01T00:01:00.000Z' })
- // The transaction-failure path leaves the operation needs-recovery.
- settleOperation(db, 'op-one', 'needs-recovery', 'test: interrupted')
- // Account for the workspace so the recovery row carries its path.
- db.prepare(`INSERT INTO workspaces(workspace_key, workspace_path, snapshot_repo, created_at) VALUES ('c:\\proj\\one', 'C:\\Proj\\One', 'repo.git', '2026-01-01T00:00:00.000Z')`).run()
-
- const fenced = listRecoveryWorkspaces(db)
- assert.equal(fenced.length, 1)
- assert.equal(fenced[0].workspace_key, 'c:\\proj\\one')
- assert.equal(fenced[0].workspace_path, 'C:\\Proj\\One')
- assert.equal(fenced[0].operations.length, 1)
- assert.equal(fenced[0].operations[0].operation_id, 'op-one')
-
- // Acknowledgement is a terminal rewrite: the fence queries (which only
- // match needs-recovery) stop matching, and the audit row stays annotated.
- assert.equal(acknowledgeRecovery(db, 'c:\\proj\\one'), 1)
- assert.deepEqual(listRecoveryWorkspaces(db), [])
- const row = db.prepare(`SELECT outcome, error FROM operations WHERE operation_id = 'op-one'`).get()
- assert.equal(row.outcome, 'recovery-acknowledged')
- assert.match(row.error, /recovery acknowledged at /u)
- // Repeat acknowledgement is a no-op (already terminal).
- assert.equal(acknowledgeRecovery(db, 'c:\\proj\\one'), 0)
- }
- 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'],
- ]) {
- createOperation(db, { operationId: `op-${turnId}`, kind: 'undo', targetTurnId: turnId, requestedAt: time })
- completeUndoTransaction(db, {
- noticeId: `notice-${turnId}`,
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: turnId,
- restoredPaths: [path],
- notRestored: [],
- operationId: `op-${turnId}`,
- 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')
- createOperation(db, { operationId: 'op-later', kind: 'undo', targetTurnId: 'session:later', requestedAt: '2026-01-01T00:01:30.000Z' })
- completeUndoTransaction(db, {
- noticeId: 'notice-later',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:later',
- restoredPaths: ['later.txt'],
- notRestored: [],
- operationId: 'op-later',
- 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',
- })
- completeUndoTransaction(db, {
- noticeId: 'notice-undo-2',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:1',
- restoredPaths: ['a.ts'],
- notRestored: [],
- operationId: 'op-undo',
- createdAt: '2026-01-01T00:01:00.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')
-
- createOperation(db, {
- operationId: 'op-redo',
- kind: 'redo',
- targetTurnId: 'session:1',
- requestedAt: '2026-01-01T00:02:00.000Z',
- beforeRef: 'refs/turnrewind/redo-op-redo',
- })
- completeRedoTransaction(db, {
- noticeId: 'notice-redo',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:1',
- redoneOperationId: 'op-undo',
- operationId: 'op-redo',
- restoredPaths: ['a.ts'],
- notRestored: [],
- 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)
- // The redo itself is recorded as an applied operation.
- assert.equal(db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-redo').outcome, 'applied')
-
- 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('fences a redo whose undo operation is no longer applied as needs-recovery', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-redo-fence-test-'))
- const db = openLedger(root)
- try {
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: 'workspace-fence',
- 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',
- })
- // The undo transaction completes: turn is undone, old op applied.
- completeUndoTransaction(db, {
- noticeId: 'notice-undo',
- sessionId: 'session',
- workspaceKey: 'workspace-fence',
- targetTurnId: 'session:1',
- restoredPaths: ['a.ts'],
- notRestored: [],
- operationId: 'op-undo',
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- // Consume the legitimate undo notice so the final assertion can require
- // that no ADDITIONAL (redo) notice leaked from the failed transaction.
- assert.equal(claimRewindNotices(db, 'session', 'workspace-fence').length, 1)
- createOperation(db, {
- operationId: 'op-redo',
- kind: 'redo',
- targetTurnId: 'session:1',
- requestedAt: '2026-01-01T00:02:00.000Z',
- })
- // Another writer flipped the old undo operation out from under us: the
- // redo must roll back and fence this workspace via needs-recovery.
- settleOperation(db, 'op-undo', 'rolled_back')
- assert.throws(
- () => completeRedoTransaction(db, {
- noticeId: 'notice-redo',
- sessionId: 'session',
- workspaceKey: 'workspace-fence',
- targetTurnId: 'session:1',
- redoneOperationId: 'op-undo',
- operationId: 'op-redo',
- restoredPaths: ['a.ts'],
- notRestored: [],
- createdAt: '2026-01-01T00:02:00.000Z',
- }),
- /OPERATION_STATE_MISMATCH/u,
- )
- // The redo operation was fenced; the workspace lands in the recovery list.
- assert.equal(db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-redo').outcome, 'needs-recovery')
- assert.deepEqual(listNeedsRecoveryWorkspaces(db), ['workspace-fence'])
- // Nothing from the failed transaction leaked: turn is still undone, no redo notice.
- assert.equal(getTurn(db, 'session:1').status, 'undone')
- assert.equal(claimRewindNotices(db, 'session', 'workspace-fence').length, 0)
- }
- 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`)
- }
- createOperation(db, { operationId: 'op-session-3', kind: 'undo', targetTurnId: 'session:3', requestedAt: '2026-01-01T00:02:30.000Z' })
- completeUndoTransaction(db, {
- noticeId: 'notice-3',
- sessionId: 'session',
- workspaceKey: 'workspace',
- targetTurnId: 'session:3',
- restoredPaths: ['a.txt'],
- notRestored: [],
- operationId: 'op-session-3',
- 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'],
- beforeRef: 'refs/turnrewind/turn-1-before',
- afterRef: 'refs/turnrewind/turn-1-after',
- })
- const first = claimPendingPlan(db, planId, 'session')
- assert.equal(first.ok, true)
- if (first.ok) {
- // The preview binding (P1-2) is persisted with the plan.
- assert.equal(first.row.before_ref, 'refs/turnrewind/turn-1-before')
- assert.equal(first.row.after_ref, 'refs/turnrewind/turn-1-after')
- assert.equal(first.row.paths_digest, planPathsDigest(['a.txt']))
- }
- assert.equal(getPendingPlanStatus(db, planId, 'session').status, 'applying')
- assert.equal(claimPendingPlan(db, planId, 'session').ok, false)
- assert.equal(markPendingPlanCancelled(db, planId, 'session'), false)
-
- 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('archives expired plans as expired instead of deleting them', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-plan-expire-'))
- const db = openLedger(root)
- try {
- const planId = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'workspace',
- turnId: 'session:1',
- paths: ['a.txt'],
- beforeRef: 'refs/turnrewind/b',
- afterRef: 'refs/turnrewind/a',
- })
- // Force the plan past its TTL.
- db.prepare('UPDATE pending_plans SET expires_at = \'2020-01-01T00:00:00.000Z\' WHERE plan_id = ?').run(planId)
-
- // The status poll converts it to expired and reports it (NOT gone):
- // the card keeps its archived view, only execution is refused.
- assert.deepEqual(getPendingPlanStatus(db, planId, 'session'), { status: 'expired', resultText: null })
- assert.equal(db.prepare('SELECT status FROM pending_plans WHERE plan_id = ?').get(planId).status, 'expired')
-
- // The row lookup for the confirm route also reports expired (not undefined).
- const row = getPendingPlanRow(db, planId)
- assert.equal(row.status, 'expired')
-
- // Claiming an expired plan is refused with a precise error; the row stays.
- const claim = claimPendingPlan(db, planId, 'session')
- assert.equal(claim.ok, false)
- assert.equal(claim.ok ? 200 : claim.code, 410)
- assert.match(claim.ok ? '' : claim.error, /has expired/u)
- assert.equal(db.prepare('SELECT status FROM pending_plans WHERE plan_id = ?').get(planId).status, 'expired')
-
- // A newer preview expires the replaced plan (kept as archive) instead of deleting it.
- const secondId = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'workspace',
- turnId: 'session:2',
- paths: ['b.txt'],
- beforeRef: 'refs/turnrewind/b2',
- afterRef: 'refs/turnrewind/a2',
- })
- db.prepare('UPDATE pending_plans SET expires_at = \'2020-01-01T00:00:00.000Z\' WHERE plan_id = ?').run(secondId)
- prunePendingPlans(db)
- const statuses = db.prepare('SELECT plan_id, status FROM pending_plans WHERE session_id = ? ORDER BY plan_id').all('session')
- assert.equal(statuses.length, 2)
- assert.deepEqual(statuses.map(row2 => row2.status), ['expired', 'expired'])
- }
- 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 })
- }
-})
-
-it('completes an interrupted turn undo in one transaction', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-interrupted-undo-'))
- const db = openLedger(root)
- try {
- insertTurn(db, { turnId: 'session:9', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/i1-before' })
- settleInterruptedTurn(db, 'session:9', 'refs/turnrewind/i1-after', 'turn ended with error')
- createOperation(db, { operationId: 'op-int', kind: 'undo', targetTurnId: 'session:9', requestedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/op-before' })
-
- const outcome = completeUndoTransaction(db, {
- noticeId: 'n-int',
- sessionId: 'session',
- workspaceKey: 'ws',
- targetTurnId: 'session:9',
- restoredPaths: ['a.txt'],
- notRestored: [],
- operationId: 'op-int',
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- assert.equal(outcome, 'undone')
- assert.equal(getTurn(db, 'session:9').status, 'undone')
- const op = db.prepare('SELECT outcome FROM operations WHERE operation_id = ?').get('op-int')
- assert.equal(op.outcome, 'applied')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('surfaces partial restore failures in operation and notice', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-partial-'))
- const db = openLedger(root)
- try {
- insertTurn(db, { turnId: 'session:p', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/p-before' })
- settleTurn(db, 'session:p', 'refs/turnrewind/p-after')
- createOperation(db, { operationId: 'op-p', kind: 'undo', targetTurnId: 'session:p', requestedAt: '2026-01-01T00:00:00.000Z' })
-
- completeUndoTransaction(db, {
- noticeId: 'n-p',
- sessionId: 'session',
- workspaceKey: 'ws',
- targetTurnId: 'session:p',
- restoredPaths: ['a.txt'],
- notRestored: [{ path: 'big.bin', reason: 'over the size limit' }],
- operationId: 'op-p',
- createdAt: '2026-01-01T00:01:00.000Z',
- })
- const op = db.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('op-p')
- assert.equal(op.outcome, 'applied')
- assert.match(op.error, /big\.bin \(over the size limit\)/)
- const notice = db.prepare('SELECT paths_json FROM rewind_notices WHERE notice_id = ?').get('n-p')
- const paths = JSON.parse(notice.paths_json)
- assert.deepEqual(paths.sort(), ['a.txt', 'big.bin'])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('lands needs-recovery when the turn state drifted after files were restored', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-mismatch-'))
- const db = openLedger(root)
- try {
- insertTurn(db, { turnId: 'session:m', sessionId: 'session', workspaceKey: 'ws', startedAt: '2026-01-01T00:00:00.000Z', beforeRef: 'refs/turnrewind/m-before' })
- createOperation(db, { operationId: 'op-m', kind: 'undo', targetTurnId: 'session:m', requestedAt: '2026-01-01T00:00:00.000Z' })
- // Simulate the crash window: files restored on disk, but the turn state
- // drifted elsewhere. No turn rows may update.
- db.prepare('UPDATE turns SET status = \'failed\' WHERE turn_id = ?').run('session:m')
-
- assert.throws(
- () => completeUndoTransaction(db, {
- noticeId: 'n-m',
- sessionId: 'session',
- workspaceKey: 'ws',
- targetTurnId: 'session:m',
- restoredPaths: ['a.txt'],
- notRestored: [],
- operationId: 'op-m',
- createdAt: '2026-01-01T00:01:00.000Z',
- }),
- /TURN_STATE_MISMATCH/,
- )
- const op = db.prepare('SELECT outcome, error FROM operations WHERE operation_id = ?').get('op-m')
- assert.equal(op.outcome, 'needs-recovery')
- assert.match(op.error, /TURN_STATE_MISMATCH/)
- const notices = db.prepare('SELECT COUNT(*) c FROM rewind_notices').get().c
- assert.equal(notices, 0)
- assert.deepEqual(listNeedsRecoveryWorkspaces(db), ['ws'])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/lifecycle.test.js b/archiving/dsh-tauri-turnrewind-ts/test/lifecycle.test.js
deleted file mode 100644
index 6376706c..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/lifecycle.test.js
+++ /dev/null
@@ -1,230 +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 } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, workspaceKey } from '../src/host/service/git-snapshot'
-import { getTurn, insertTurn, openLedger, settleTurn } from '../src/host/service/ledger'
-import { applyUndo, waitForTurnBaseline } from '../src/index'
-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: workspaceKey(workspace),
- 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: workspaceKey(workspace),
- 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('applies a confirmed undo and reports redo as disabled', { 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')))
- assert.equal(getTurn(db, 'session:1').status, 'undone')
-
- // Redo is frozen at the parser: even with a clean workspace the entry
- // refuses before any snapshot/conflict work happens.
- const redo = await applyUndo(runtime, active, invocation('--redo'))
- assert.equal(redo.kind, 'error')
- assert.match(redo.text, /temporarily disabled/u)
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')
- assert.equal(getTurn(db, 'session:1').status, 'undone')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('rejects a confirm whose change set drifted from the preview', async () => {
- const { root, workspace, db, runtime, active, invocation } = await setupTurn()
- try {
- const preview = await applyUndo(runtime, active, invocation())
- assert.equal(preview.kind, 'success')
- const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]
- assert.ok(planId, 'preview must carry a pending plan id')
-
- // Simulate plan drift: the persisted binding no longer matches what the
- // confirm recomputes. The confirm must refuse and release the claim.
- db.prepare('UPDATE pending_plans SET paths_digest = ? WHERE plan_id = ?').run('0'.repeat(64), planId)
- const confirmed = await applyUndo(runtime, active, invocation(`--confirm ${planId}`))
- assert.equal(confirmed.kind, 'error')
- assert.match(confirmed.text, /change set no longer matches/u)
-
- // Nothing was restored and the plan stays pending for a fresh confirm.
- assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v2\n')
- const row = db.prepare('SELECT status FROM pending_plans WHERE plan_id = ?').get(planId)
- assert.equal(row.status, 'pending')
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('rejects invalid option combinations', async () => {
- const { root, db, runtime, active, invocation } = await setupTurn()
- try {
- 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('releases the workspace reservation when target selection throws', async () => {
- const { root, db, runtime, active, invocation } = await setupTurn()
- // Closing the ledger makes target selection throw (a stand-in for a real
- // SQLITE_BUSY/IOERR). The reservation is taken before that first probe, so a
- // throw must release it: a stranded runtime.undoing silently refuses every
- // later undo and makes new turns skip their baseline until the host restarts.
- db.close()
- try {
- await assert.rejects(() => applyUndo(runtime, active, invocation('')))
- assert.equal(runtime.undoing, false)
- }
- finally {
- await rm(root, { recursive: true, force: 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/archiving/dsh-tauri-turnrewind-ts/test/maintenance.test.js b/archiving/dsh-tauri-turnrewind-ts/test/maintenance.test.js
deleted file mode 100644
index 801bcb5c..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/maintenance.test.js
+++ /dev/null
@@ -1,207 +0,0 @@
-import assert from 'node:assert/strict'
-import { existsSync } from 'node:fs'
-import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, workspaceHash, workspaceKey } from '../src/host/service/git-snapshot'
-import { createOperation, createPendingPlan, getTurn, insertTurn, openLedger, queueRewindNotice, registerWorkspace, settleTurn } from '../src/host/service/ledger'
-import { purgeWorkspace } from '../src/host/service/maintenance'
-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 wsKey = workspaceKey(workspace)
- try {
- const db = openLedger(root)
- registerWorkspace(db, wsKey, workspace, join(root, 'snapshots', 'x.git'))
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: wsKey,
- 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: wsKey,
- 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 data registered under a different spelling of the same workspace', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-purge-spelling-'))
- const workspace = join(root, 'ws')
- try {
- await initGitWorkspace(workspace)
- const db = openLedger(root)
- registerWorkspace(db, workspaceKey(workspace), workspace, join(root, 'snapshots', 'ws.git'))
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: 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')
- 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')
-
- // Purge through a link alias of the same directory (junctions need no
- // elevation on Windows): canonical identity must land on the one
- // snapshot repo and ledger domain instead of forking a second empty one.
- const alias = join(root, 'ws-alias')
- await symlink(workspace, alias, process.platform === 'win32' ? 'junction' : 'dir')
- const summary = purgeWorkspace(root, alias)
- assert.equal(summary.repoExisted, true)
- assert.deepEqual(summary.ledger, { operations: 0, notices: 0, plans: 0, turns: 1, workspaces: 1 })
- assert.equal(existsSync(repoDir), false)
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-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'],
- beforeRef: 'refs/turnrewind/turn-1-before',
- afterRef: 'refs/turnrewind/turn-1-after',
- })
- createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: workspaceKey(join(root, 'other')),
- turnId: 'session:2',
- paths: ['b.txt'],
- beforeRef: 'refs/turnrewind/turn-2-before',
- afterRef: 'refs/turnrewind/turn-2-after',
- })
- db.close()
-
- 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/archiving/dsh-tauri-turnrewind-ts/test/migration.test.js b/archiving/dsh-tauri-turnrewind-ts/test/migration.test.js
deleted file mode 100644
index c589b40d..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/migration.test.js
+++ /dev/null
@@ -1,132 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdtemp, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { DatabaseSync } from 'node:sqlite'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { claimRewindNotices, createPendingPlan, getPendingPlanStatus, hasNeedsRecoveryWorkspace, openLedger } from '../src/host/service/ledger'
-
-/**
- * 迁移重放:用 git 历史上最早的账本 schema(pending_plans 无
- * status/result_text/before_ref/after_ref/paths_digest,rewind_notices 无
- * turns_json/kind/reason,operations 无 after_ref)构造一个"老版本遗物",
- * openLedger 必须 idempotent 地补列并让遗留数据继续工作。
- */
-const LEGACY_SCHEMA = `
- CREATE TABLE workspaces (
- workspace_key TEXT PRIMARY KEY,
- workspace_path TEXT NOT NULL,
- snapshot_repo TEXT NOT NULL,
- created_at TEXT NOT NULL
- );
- CREATE TABLE 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 TABLE 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,
- before_ref TEXT,
- error TEXT
- );
- CREATE TABLE rewind_notices (
- notice_id TEXT PRIMARY KEY,
- session_id TEXT NOT NULL,
- workspace_key TEXT NOT NULL,
- target_turn_id TEXT,
- paths_json TEXT NOT NULL DEFAULT '[]',
- status TEXT NOT NULL DEFAULT 'pending',
- created_at TEXT NOT NULL,
- claimed_at TEXT
- );
- CREATE TABLE 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,
- created_at TEXT NOT NULL,
- expires_at TEXT NOT NULL
- );
- CREATE INDEX turns_session_idx ON turns(session_id, started_at);
-`
-
-/** Windows may hold freshly closed sqlite sidecar files briefly: retry, then give up quietly. */
-async function cleanupDir(root) {
- for (let attempt = 0; ; attempt += 1) {
- try {
- await rm(root, { recursive: true, force: true })
- return
- }
- catch (error) {
- if (attempt >= 4 || !['EBUSY', 'EPERM', 'ENOTEMPTY'].includes(error.code))
- return
- await new Promise(resolve => setTimeout(resolve, 150))
- }
- }
-}
-
-it('upgrades a legacy ledger in place and keeps every row working', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-migration-'))
- try {
- // Build the pre-migration database with representative rows.
- const legacy = new DatabaseSync(join(root, 'ledger.sqlite'))
- legacy.exec(LEGACY_SCHEMA)
- legacy.exec(`
- INSERT INTO workspaces VALUES ('c:\\legacy', 'C:\\Legacy', 'repo.git', '2026-01-01T00:00:00.000Z');
- INSERT INTO turns VALUES ('session:1', 'session', NULL, 'c:\\legacy', 'settled', '2026-01-01T00:00:00.000Z', '2026-01-01T00:01:00.000Z', 'refs/turnrewind/turn-1-before', 'refs/turnrewind/turn-1-after', 1, NULL);
- INSERT INTO operations VALUES ('op-legacy', 'undo', 'session:1', '2026-01-01T00:02:00.000Z', NULL, 'applying', 'refs/turnrewind/op-before', NULL);
- INSERT INTO rewind_notices VALUES ('notice-legacy', 'session', 'c:\\legacy', 'session:1', '[]', 'pending', '2026-01-01T00:03:00.000Z', NULL);
- INSERT INTO pending_plans VALUES ('plan-legacy', 'session', 'c:\\legacy', 'session:1', '["a.txt"]', '2026-01-01T00:04:00.000Z', '2026-01-01T00:09:00.000Z');
- `)
- legacy.close()
-
- // Reopening runs the idempotent migrations plus the reopen sweeps.
- const db = openLedger(root)
-
- // The legacy applying operation is fenced exactly like a modern crash,
- // and the legacy turn is still there for the recovery panel to describe.
- assert.equal(hasNeedsRecoveryWorkspace(db, 'c:\\legacy'), true)
-
- // The legacy plan row survives; its past TTL is archived as expired and
- // the status poll answers from the migrated columns.
- const status = getPendingPlanStatus(db, 'plan-legacy', 'session')
- assert.equal(status?.status, 'expired')
-
- // A brand-new plan (with preview binding columns) writes fine.
- const freshPlan = createPendingPlan(db, {
- sessionId: 'session',
- workspaceKey: 'c:\\legacy',
- turnId: 'session:1',
- paths: ['a.txt'],
- beforeRef: 'refs/turnrewind/turn-1-before',
- afterRef: 'refs/turnrewind/turn-1-after',
- })
- assert.notEqual(freshPlan, undefined)
-
- // The legacy notice claims cleanly: turns_json was added with an empty
- // default and parses, paths come through verbatim.
- const notices = claimRewindNotices(db, 'session', 'c:\\legacy')
- assert.equal(notices.length, 1)
- assert.equal(notices[0].notice_id, 'notice-legacy')
- assert.deepEqual(notices[0].turns, [])
- assert.deepEqual(notices[0].paths, [])
- db.close()
- }
- finally {
- await cleanupDir(root)
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/oversize.test.js b/archiving/dsh-tauri-turnrewind-ts/test/oversize.test.js
deleted file mode 100644
index 06d3238d..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/oversize.test.js
+++ /dev/null
@@ -1,121 +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 } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, restorePath, stateAt, workspaceKey } from '../src/host/service/git-snapshot'
-import { insertTurn, openLedger, settleTurn } from '../src/host/service/ledger'
-import { applyUndo } from '../src/index'
-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')
- let db
- 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)
-
- 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: workspaceKey(workspace),
- 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: workspaceKey(workspace),
- 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')
- }
- finally {
- db?.close()
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/planner.test.js b/archiving/dsh-tauri-turnrewind-ts/test/planner.test.js
deleted file mode 100644
index 5ad2a46f..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/planner.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { planPathsDigest } from '../src/host/service/ledger'
-import { aggregatePathPlan, classifyUndo, collectDescendantTurns, planDrift } from '../src/host/service/planner'
-
-it('collects a selected turn subtree in leaf-first order', () => {
- const root = { turn_id: 'p' }
- 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')
-})
-
-it('detects pending plan drift against the confirmed turn and diff', () => {
- const target = { turn_id: 's:1', before_ref: 'refs/turnrewind/b', after_ref: 'refs/turnrewind/a' }
- const binding = {
- before_ref: 'refs/turnrewind/b',
- after_ref: 'refs/turnrewind/a',
- paths_digest: planPathsDigest(['a.txt', 'b.txt']),
- }
- // Same refs and the same path set in any order: no drift.
- assert.equal(planDrift(binding, target, ['b.txt', 'a.txt']), undefined)
- // A different change set is drift even when the refs still match.
- assert.match(planDrift(binding, target, ['a.txt']), /change set no longer matches/u)
- // Rewritten turn refs are drift regardless of the recomputed paths.
- assert.match(
- planDrift(binding, { ...target, after_ref: 'refs/turnrewind/a2' }, ['a.txt', 'b.txt']),
- /snapshots no longer match/u,
- )
- // Legacy plans (NULL binding columns) cannot be verified: they are rejected
- // (forced re-preview) instead of being trusted without checks.
- assert.match(
- planDrift({ before_ref: null, after_ref: null, paths_digest: null }, target, []),
- /predates preview binding/u,
- )
-})
-
-it('produces a stable order-independent paths digest', () => {
- assert.equal(planPathsDigest(['b.txt', 'a.txt']), planPathsDigest(['a.txt', 'b.txt']))
- assert.notEqual(planPathsDigest(['a.txt']), planPathsDigest(['a.txt', 'b.txt']))
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/retention.test.js b/archiving/dsh-tauri-turnrewind-ts/test/retention.test.js
deleted file mode 100644
index fc8344cb..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/retention.test.js
+++ /dev/null
@@ -1,152 +0,0 @@
-import assert from 'node:assert/strict'
-import { Buffer } from 'node:buffer'
-import { existsSync } from 'node:fs'
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { afterEach, it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, workspaceKey } from '../src/host/service/git-snapshot'
-import { insertTurn, openLedger, settleTurn } from '../src/host/service/ledger'
-import { enforceRetention } from '../src/host/service/retention'
-import { gitOutput, initGitWorkspace } from './git-test-utils.js'
-
-const cleanups = []
-// Ledgers must close before the temp roots are removed: an open SQLite handle
-// on Windows makes rm fail with EBUSY, which then masks the real failure.
-// (CI observed exactly this: the prunes-unreachable test failed with EBUSY on
-// the retry path instead of reporting its own assertion.)
-const openDbs = []
-
-afterEach(async () => {
- for (const db of openDbs.reverse())
- db.close()
- openDbs.length = 0
- for (const dispose of cleanups.reverse())
- await dispose()
- cleanups.length = 0
- for (const name of ['TURNREWIND_RETAIN_TURNS', 'TURNREWIND_MAX_SNAPSHOT_MB'])
- delete process.env[name]
-})
-
-async function makeRoot() {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-retention-'))
- cleanups.push(async () => rm(root, { recursive: true, force: true }))
- return root
-}
-
-function openLedgerTracked(ledgerRoot) {
- const db = openLedger(ledgerRoot)
- openDbs.push(db)
- return db
-}
-
-async function makeWorkspace(root, name) {
- const workspace = join(root, name)
- await initGitWorkspace(workspace)
- return workspace
-}
-
-function seedTurns(db, workspaceKey, count, offset = 0) {
- for (let index = 0; index < count; index++) {
- const turnId = `session:${offset + index + 1}`
- const startedAt = new Date(Date.UTC(2026, 0, 1, 0, offset + index)).toISOString()
- insertTurn(db, { turnId, sessionId: 'session', workspaceKey, startedAt, beforeRef: `refs/turnrewind/${turnId}-before` })
- settleTurn(db, turnId, `refs/turnrewind/${turnId}-after`)
- }
-}
-
-it('expires turns beyond the retention count, keeping the most recent', async () => {
- const root = await makeRoot()
- const workspace = await makeWorkspace(root, 'ws')
- const db = openLedgerTracked(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- seedTurns(db, workspaceKey(store.workspaceDir), 5)
- process.env.TURNREWIND_RETAIN_TURNS = '3'
-
- const result = enforceRetention(db, store, { maxSnapshotMb: 1024 })
- assert.equal(result.expiredByCount, 2)
- assert.equal(result.rebuilt, false)
-
- // The 3 most recent reversible turns survive; the 2 oldest are archived.
- const reversible = db.prepare(`
- SELECT turn_id FROM turns WHERE reversible = 1 ORDER BY started_at
- `).all().map(row => row.turn_id)
- assert.deepEqual(reversible, ['session:3', 'session:4', 'session:5'])
- const archived = db.prepare(`
- SELECT error FROM turns WHERE reversible = 0 AND turn_id LIKE 'session:%'
- `).all().map(row => row.error)
- assert.ok(archived.every(error => /retention:/u.test(error)))
-})
-
-it('rebuilds the snapshot repository when it exceeds the size cap', async () => {
- const root = await makeRoot()
- const workspace = await makeWorkspace(root, 'ws')
- const db = openLedgerTracked(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- seedTurns(db, workspaceKey(store.workspaceDir), 2)
- // Simulate a bloated snapshot repo (the size walk reads the real directory).
- await mkdir(join(store.repoDir, 'objects'), { recursive: true })
- await writeFile(join(store.repoDir, 'objects', 'blob'), Buffer.alloc(2 * 1024 * 1024, 1))
- // A leftover quarantine from a crashed earlier rebuild must be swept first.
- await mkdir(`${store.repoDir}.retention-quarantine`, { recursive: true })
- await writeFile(join(`${store.repoDir}.retention-quarantine`, 'junk'), Buffer.alloc(1024, 1))
- process.env.TURNREWIND_MAX_SNAPSHOT_MB = '1'
-
- const result = enforceRetention(db, store, { retainTurns: 50 })
- assert.equal(result.rebuilt, true)
- assert.equal(result.expiredByRebuild, 2)
- assert.equal(result.repoSizeMb >= 1, true)
-
- // The repo directory is gone (next capture self-heals a fresh baseline)
- // and every reversible turn of the workspace is archived with the reason.
- const exists = await db.prepare(`
- SELECT COUNT(*) AS count FROM turns
- WHERE workspace_key = ? AND reversible = 1
- `).get(workspaceKey(workspace))
- assert.equal(exists.count, 0)
- const errors = db.prepare(`
- SELECT error FROM turns WHERE workspace_key = ? AND reversible = 0
- `).all().map(row => row.error)
- assert.ok(errors.every(error => /snapshot repository rebuilt/u.test(error)))
- // Two-phase rebuild: no half-deleted live directory or quarantine leftover.
- assert.equal(existsSync(store.repoDir), false)
- assert.equal(existsSync(`${store.repoDir}.retention-quarantine`), false)
-})
-
-it('keeps everything when under both limits', async () => {
- const root = await makeRoot()
- const workspace = await makeWorkspace(root, 'ws')
- const db = openLedgerTracked(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- seedTurns(db, workspaceKey(store.workspaceDir), 3)
- process.env.TURNREWIND_RETAIN_TURNS = '10'
- process.env.TURNREWIND_MAX_SNAPSHOT_MB = '1024'
-
- const result = enforceRetention(db, store)
- assert.equal(result.expiredByCount, 0)
- assert.equal(result.rebuilt, false)
- assert.equal(db.prepare('SELECT COUNT(*) AS count FROM turns WHERE reversible = 1').get().count, 3)
-})
-
-it('prunes unreachable loose objects before measuring the size cap', async () => {
- const root = await makeRoot()
- const workspace = await makeWorkspace(root, 'ws')
- const db = openLedgerTracked(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- // A real capture first: the private repository must exist (and the reachable
- // objects it holds must survive the prune).
- const seed = await captureSnapshot(store, 'refs/turnrewind/prune-seed', 'seed')
- // Simulate the disk-content blobs diffAgainstDisk hashes into the repo
- // during conflict previews: written via hash-object, referenced by nothing.
- const stray = join(workspace, 'stray.txt')
- await writeFile(stray, 'unreachable preview content\n')
- const oid = (await gitOutput(workspace, ['--git-dir', store.repoDir, 'hash-object', '-w', 'stray.txt'])).trim()
- const loosePath = join(store.repoDir, 'objects', oid.slice(0, 2), oid.slice(2))
- assert.equal(existsSync(loosePath), true)
-
- const result = enforceRetention(db, store)
- assert.equal(result.rebuilt, false)
- assert.equal(existsSync(loosePath), false, 'unreachable loose object must be pruned')
- // The reachable snapshot chain is untouched by the prune.
- assert.equal((await gitOutput(workspace, ['--git-dir', store.repoDir, 'cat-file', '-t', seed.commit])).trim(), 'commit')
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/routes.test.js b/archiving/dsh-tauri-turnrewind-ts/test/routes.test.js
deleted file mode 100644
index e8a5eb1f..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/routes.test.js
+++ /dev/null
@@ -1,104 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { jsonRoute } from '../src/host/routes'
-
-function makeReq({ method = 'POST', headers = { 'content-type': 'application/json' } } = {}) {
- const listeners = new Map()
- const req = {
- method,
- url: '/',
- socket: { remoteAddress: '127.0.0.1' },
- headers,
- on(event, listener) {
- listeners.set(event, listener)
- return () => {}
- },
- destroy() {},
- }
- const emit = (event, payload) => {
- listeners.get(event)?.(payload)
- }
- return {
- req,
- emit,
- end: async () => {
- listeners.get('end')?.()
- await Promise.resolve()
- },
- }
-}
-
-function makeRes() {
- const res = {
- statusCode: undefined,
- body: undefined,
- headers: {},
- responses: 0,
- writeHead(code, headers) {
- res.statusCode = code
- Object.assign(res.headers, headers)
- },
- setHeader(name, value) {
- res.headers[name] = value
- },
- end(body) {
- res.responses += 1
- res.body = body
- },
- destroy() {},
- }
- return res
-}
-
-const okHandler = async () => [200, { ok: true }]
-
-it('enforces method restrictions on mutate routes', async () => {
- const route = jsonRoute('/api/x', okHandler, { mutate: true })
- const { req, end } = makeReq({ method: 'GET' })
- const res = makeRes()
- route.handler(req, res)
- await end()
- assert.equal(res.statusCode, 405)
- assert.equal(res.responses, 1)
-})
-
-it('rejects oversized bodies immediately with 413', async () => {
- const route = jsonRoute('/api/x', okHandler, { mutate: true })
- const { req, emit } = makeReq()
- const res = makeRes()
- route.handler(req, res)
- emit('data', 'x'.repeat(20000))
- assert.equal(res.statusCode, 413)
- assert.equal(res.responses, 1)
-})
-
-it('returns 415 for non-JSON content types on mutate routes', async () => {
- const route = jsonRoute('/api/x', okHandler, { mutate: true })
- const { req, end } = makeReq({ headers: { 'content-type': 'text/plain' } })
- const res = makeRes()
- route.handler(req, res)
- await end()
- assert.equal(res.statusCode, 415)
-})
-
-it('sets nosniff and no-store headers on every response', async () => {
- const route = jsonRoute('/api/x', okHandler, { mutate: true })
- const { req, end } = makeReq()
- const res = makeRes()
- route.handler(req, res)
- await end()
- assert.equal(res.statusCode, 200)
- assert.equal(res.headers['x-content-type-options'], 'nosniff')
- assert.equal(res.headers['cache-control'], 'no-store')
-})
-
-it('never responds twice when the stream errors after a response', async () => {
- const route = jsonRoute('/api/x', okHandler, { mutate: true })
- const { req, end, emit } = makeReq()
- const res = makeRes()
- route.handler(req, res)
- await end()
- emit('error', new Error('late stream error'))
- assert.equal(res.statusCode, 200)
- assert.equal(res.responses, 1)
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/security.test.js b/archiving/dsh-tauri-turnrewind-ts/test/security.test.js
deleted file mode 100644
index 947c401b..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/security.test.js
+++ /dev/null
@@ -1,251 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { captureSnapshot, createSnapshotStore, currentState, restorePath, stateAt, workspaceKey } from '../src/host/service/git-snapshot'
-import { insertTurn, openLedger, settleTurn } from '../src/host/service/ledger'
-import { applyUndo } from '../src/index'
-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)
- await assert.rejects(() => 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)
- await assert.rejects(() => 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 })
- }
-})
-
-it('keeps snapshot symlinks unrestorable and reported by undo', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-symlink-undo-'))
- const workspace = join(root, 'workspace')
- let db
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, 'keep.txt'), 'before\n')
- await writeFile(join(workspace, 'original.txt'), 'original\n')
- try {
- await symlink('original.txt', join(workspace, 'link'))
- }
- catch (error) {
- if (error.code === 'EPERM' || error.code === 'EACCES')
- return
- throw error
- }
- db = openLedger(join(root, 'ledger'))
- const store = createSnapshotStore(join(root, 'data'), workspace)
- await captureSnapshot(store, 'refs/turnrewind/sl-before', 'before')
-
- // The turn: replace the symlink with a regular file and edit keep.txt.
- await rm(join(workspace, 'link'))
- await writeFile(join(workspace, 'link'), 'now-a-file\n')
- await writeFile(join(workspace, 'keep.txt'), 'after\n')
- await captureSnapshot(store, 'refs/turnrewind/sl-after', 'after', 'refs/turnrewind/sl-before')
- insertTurn(db, {
- turnId: 'session:1',
- sessionId: 'session',
- workspaceKey: workspaceKey(workspace),
- startedAt: '2026-01-01T00:00:00.000Z',
- beforeRef: 'refs/turnrewind/sl-before',
- })
- settleTurn(db, 'session:1', 'refs/turnrewind/sl-after')
-
- const runtime = {
- db,
- store,
- workspaceKey: workspaceKey(workspace),
- parentRef: 'refs/turnrewind/sl-after',
- undoing: false,
- }
- const invocation = (rawInput = '') => ({
- rawInput,
- agent: { session: { id: 'session', header: { cwd: workspace } } },
- })
-
- // The preview flags the symlink entry as unsupported (P1-3).
- const preview = await applyUndo(runtime, new Map(), invocation())
- assert.equal(preview.kind, 'success')
- assert.match(preview.text, /link \[unsupported\]/u)
- assert.match(preview.text, /Unrestorable entries/u)
-
- // Confirm: keep.txt restores normally; the link is reported as not
- // restored and stays a regular file instead of receiving target text.
- const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]
- const confirmed = await applyUndo(runtime, new Map(), invocation(`--confirm ${planId}`))
- assert.equal(confirmed.kind, 'success')
- assert.match(confirmed.text, /Not restored \(1 file\(s\)\): link/u)
- assert.equal(await readFile(join(workspace, 'link'), 'utf8'), 'now-a-file\n')
- assert.equal(await readFile(join(workspace, 'keep.txt'), 'utf8'), 'before\n')
- }
- finally {
- db?.close()
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
-
-it('refuses Windows junction directories like symlinks', async () => {
- if (process.platform !== 'win32')
- return
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-junction-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')
- // Junctions need no elevation on Windows and are reparse points like
- // symlinks — traversal through them must be refused identically (P1-5).
- await symlink(outside, join(workspace, 'junction'), 'junction')
- const store = createSnapshotStore(join(root, 'data'), workspace)
- await assert.rejects(() => currentState(workspace, 'junction/secret.txt'), /TURNREWIND_SYMLINK_UNSUPPORTED/)
- const snapshot = await captureSnapshot(store, 'refs/turnrewind/junction', 'junction')
- await assert.rejects(
- () => restorePath(store, snapshot.commit, 'junction/secret.txt'),
- /TURNREWIND_SYMLINK_UNSUPPORTED/,
- )
- }
- finally {
- await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/sensitive.test.js b/archiving/dsh-tauri-turnrewind-ts/test/sensitive.test.js
deleted file mode 100644
index 73ea2ba6..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/sensitive.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'pathe'
-import { it } from 'vitest'
-import { claimRewindNotices, hasSensitiveNotice, openLedger, queueSensitiveNotice } from '../src/host/service/ledger'
-import { findUnignoredSensitiveFiles } from '../src/host/service/sensitive'
-import { createNoticeMessage } from '../src/host/service/undo'
-import { initGitWorkspace, runGit } from './git-test-utils.js'
-
-it('finds unignored sensitive files and filters gitignored ones', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-sensitive-'))
- const workspace = join(root, 'workspace')
- try {
- await initGitWorkspace(workspace)
- await writeFile(join(workspace, '.gitignore'), '/.env\n/creds/**\n')
- await writeFile(join(workspace, '.env'), 'SECRET=1\n')
- await writeFile(join(workspace, 'server.pem'), '-----BEGIN\n')
- await mkdir(join(workspace, 'sub'))
- await writeFile(join(workspace, 'sub', 'token.key'), 'k\n')
- await mkdir(join(workspace, 'creds'), { recursive: true })
- await writeFile(join(workspace, 'creds', 'id_rsa'), 'k\n')
- await runGit(workspace, ['add', '.gitignore'])
-
- const found = await findUnignoredSensitiveFiles(workspace)
- assert.deepEqual(found, ['server.pem', 'sub/token.key'])
- }
- finally {
- await rm(root, { recursive: true, force: true })
- }
-})
-
-it('queues one sensitive notice per session and workspace and builds its message', async () => {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-sensitive-notice-'))
- const db = openLedger(root)
- try {
- assert.equal(hasSensitiveNotice(db, 'session', 'ws'), false)
- assert.equal(queueSensitiveNotice(db, 'session', 'ws', ['.env', 'sub/token.key']), true)
- // Repeat (another process racing, another turn) is a no-op.
- assert.equal(queueSensitiveNotice(db, 'session', 'ws', ['.env']), false)
- assert.equal(hasSensitiveNotice(db, 'session', 'ws'), true)
-
- const notices = claimRewindNotices(db, 'session', 'ws')
- assert.equal(notices.length, 1)
- assert.equal(notices[0].kind, 'sensitive-files')
- assert.deepEqual(notices[0].paths, ['.env', 'sub/token.key'])
-
- const message = createNoticeMessage(notices[0])
- assert.match(message.source.form, /rewind-privacy-notice/u)
- assert.match(message.content[0].text, /\[Turn rewind privacy notice\]/u)
- assert.match(message.content[0].text, /- \.env/u)
- // Already consumed: no further notices.
- assert.deepEqual(claimRewindNotices(db, 'session', 'ws'), [])
- }
- finally {
- db.close()
- await rm(root, { recursive: true, force: true })
- }
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/styles.test.js b/archiving/dsh-tauri-turnrewind-ts/test/styles.test.js
deleted file mode 100644
index 0ccdb3a3..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/styles.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-import assert from 'node:assert/strict'
-import { CssRender } from 'dsh-tauri/client'
-import { it } from 'vitest'
-import { buildDialogStyleNodes } from '../src/client/styles'
-import { buildCommandViewStyleNodes } from '../src/client/styles/command-view'
-
-/** css-render 不给数字补 px:裸数字会生成非法声明并被浏览器静默丢弃。 */
-const UNITLESS = new Set([
- 'flex',
- 'opacity',
- 'font-weight',
- 'line-height',
- 'z-index',
- 'order',
- 'zoom',
- 'min-width',
- 'column-count',
- 'inset',
-])
-
-function assertNoBareNumbers(css, label) {
- for (const match of css.matchAll(/([a-z-]+)\s*:\s*([^;{}]+)/g)) {
- const prop = match[1]
- const value = match[2].trim()
- if (UNITLESS.has(prop))
- continue
- assert.doesNotMatch(
- value,
- /^\d+(\.\d+)?$/,
- `${label}: ${prop}: ${value} is a bare number — css-render will not append px and the browser drops the declaration`,
- )
- }
-}
-
-it('renders command-view styles with explicit px units', () => {
- const css = buildCommandViewStyleNodes(CssRender()).render()
- assertNoBareNumbers(css, 'command-view')
- // The dimensional properties that silently failed before the fix.
- assert.match(css, /gap:\s*8px/u)
- assert.match(css, /border-radius:\s*10px/u)
- assert.match(css, /font-size:\s*12px/u)
- assert.match(css, /max-height:\s*260px/u)
- // Hint text stays high-contrast across themes (black on light, white on dark).
- assert.match(css, /\.dsh-turnrewind-card-hint\s*\{[^}]*--dsw-alias-label-primary/u)
-})
-
-it('renders dialog styles with explicit px units', () => {
- const css = buildDialogStyleNodes(CssRender()).render()
- assertNoBareNumbers(css, 'dialog')
- assert.match(css, /border-radius:\s*12px/u)
- assert.match(css, /max-height:\s*160px/u)
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/turn-action.test.js b/archiving/dsh-tauri-turnrewind-ts/test/turn-action.test.js
deleted file mode 100644
index 887ef132..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/turn-action.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import assert from 'node:assert/strict'
-import { it } from 'vitest'
-import { resolveCommandRunner, turnIdFor, undoCommandLine } from '../src/client/utils/turn-action'
-
-const translate = key => `[${key}]`
-
-it('builds the ledger turn id from the session id and the slot turn number', () => {
- // 账本 turn id 与宿主事件一致:<sessionId>:<turn>。
- assert.equal(turnIdFor('sess-1', 7), 'sess-1:7')
- assert.equal(turnIdFor('sess-1', '7'), 'sess-1:7')
- assert.equal(turnIdFor('sess-1', 0), 'sess-1:0')
-})
-
-it('refuses to target a turn without a usable session id or turn number', () => {
- assert.equal(turnIdFor(null, 3), null)
- assert.equal(turnIdFor('', 3), null)
- assert.equal(turnIdFor('sess-1', undefined), null)
- assert.equal(turnIdFor('sess-1', 'turn-3'), null)
- assert.equal(turnIdFor('sess-1', 1.5), null)
- assert.equal(turnIdFor('sess-1', -1), null)
- assert.equal(turnIdFor('sess-1', Number.NaN), null)
-})
-
-it('submits the same command line a human would type', () => {
- assert.equal(undoCommandLine('sess-1:7'), '/undo sess-1:7')
-})
-
-it('resolves the command runner only when the host exposes remote.commands.execute', () => {
- assert.equal(resolveCommandRunner({}, translate), null)
- assert.equal(resolveCommandRunner({ remote: {} }, translate), null)
- assert.equal(resolveCommandRunner({ remote: { commands: { execute: 'nope' } } }, translate), null)
- assert.equal(typeof resolveCommandRunner({ remote: { commands: { execute: async () => {} } } }, translate), 'function')
-})
-
-it('degrades to null when the cordis proxy rejects the property access', () => {
- // 未在 inject 里声明 remote 时,cordis 的 context 代理读该属性会直接抛。
- // 这个抛绝不能冒泡到 apply(线上表现为整个客户端插件 "Failed to load plugins")。
- const throwing = new Proxy({}, {
- get(_target, key) {
- throw new Error(`cannot get property "${String(key)}" without inject`)
- },
- })
- assert.equal(resolveCommandRunner(throwing, translate), null)
-})
-
-it('runs the command against the given session and surfaces host failures', async () => {
- const calls = []
- const ctx = {
- remote: {
- commands: {
- async execute(sessionId, line, images) {
- calls.push({ sessionId, line, images, self: this })
- if (line.includes('boom'))
- throw new Error('TURNREWIND_BOOM')
- },
- },
- },
- }
- const run = resolveCommandRunner(ctx, translate)
- assert.ok(run)
-
- // 成功路径:调用宿主、返回 null、images 恒为空数组。
- assert.equal(await run('/undo sess-1:7', 'sess-1'), null)
- assert.deepEqual(calls[0], { sessionId: 'sess-1', line: '/undo sess-1:7', images: [], self: ctx.remote.commands })
-
- // 会话缺失:不发命令,直接返回既有文案。
- assert.equal(await run('/undo sess-1:7', null), translate('sessionMissing'))
- assert.equal(calls.length, 1)
-
- // 宿主抛错:把错误文本交回按钮显示。
- assert.equal(await run('/undo boom', 'sess-1'), 'TURNREWIND_BOOM')
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/test/workspace-lock.test.js b/archiving/dsh-tauri-turnrewind-ts/test/workspace-lock.test.js
deleted file mode 100644
index 36a6185a..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/test/workspace-lock.test.js
+++ /dev/null
@@ -1,121 +0,0 @@
-import assert from 'node:assert/strict'
-import { spawnSync } from 'node:child_process'
-import { existsSync, readFileSync } from 'node:fs'
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { dirname, join } from 'pathe'
-import { afterEach, it } from 'vitest'
-import { workspaceHash } from '../src/host/service/git-snapshot'
-import { acquireWorkspaceLock, acquireWorkspaceLockSync, withWorkspaceLock, WorkspaceLockBusyError } from '../src/host/service/workspace-lock'
-
-const cleanup = []
-
-afterEach(async () => {
- for (const dispose of cleanup.reverse())
- await dispose()
- cleanup.length = 0
-})
-
-async function makeRoot() {
- const root = await mkdtemp(join(tmpdir(), 'turnrewind-lock-test-'))
- cleanup.push(async () => rm(root, { recursive: true, force: true }))
- return root
-}
-
-function lockPath(root, workspaceDir) {
- // Mirror the private layout: locks/<workspace-hash>.lock (same hash as the module).
- return join(root, 'locks', `${workspaceHash(workspaceDir)}.lock`)
-}
-
-let cachedDeadPid
-
-/** A pid that is guaranteed to be gone: the child exited before we return. */
-function deadPid() {
- if (cachedDeadPid === undefined) {
- const result = spawnSync(process.execPath, ['-e', 'process.exit(0)'])
- cachedDeadPid = result.pid ?? -1
- }
- return cachedDeadPid
-}
-
-async function writeLock(root, workspaceDir, { pid, ageMs = 0 }) {
- const path = lockPath(root, workspaceDir)
- await mkdir(dirname(path), { recursive: true })
- const acquiredAt = new Date(Date.now() - ageMs).toISOString()
- await writeFile(path, JSON.stringify({ pid, token: 'external', acquiredAt, host: 'test' }), 'utf8')
-}
-
-it('releases the lock on release and allows reacquire', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- const handle = await acquireWorkspaceLock(root, ws)
- assert.ok(existsSync(lockPath(root, ws)))
- handle.release()
- assert.equal(existsSync(lockPath(root, ws)), false)
- const second = await acquireWorkspaceLock(root, ws)
- second.release()
-})
-
-it('refuses a second holder while the lock is alive', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- const handle = await acquireWorkspaceLock(root, ws)
- try {
- await assert.rejects(
- () => acquireWorkspaceLock(root, ws),
- error => error instanceof WorkspaceLockBusyError && /TURNREWIND_LOCK_BUSY/u.test(error.message),
- )
- // The sync variant fails the same way for offline tools.
- assert.throws(() => acquireWorkspaceLockSync(root, ws), WorkspaceLockBusyError)
- }
- finally {
- handle.release()
- }
-})
-
-it('takes over a lock left by a dead process', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- await writeLock(root, ws, { pid: deadPid() })
- const handle = await acquireWorkspaceLock(root, ws)
- // Takeover rewrites the file with the new owner's token.
- const content = JSON.parse(readFileSync(lockPath(root, ws), 'utf8'))
- assert.notEqual(content.token, 'external')
- handle.release()
- assert.equal(existsSync(lockPath(root, ws)), false)
-})
-
-it('takes over a lock whose TTL expired even if the pid is alive', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- // Our own pid is alive, but the acquisition is 31 minutes old.
- await writeLock(root, ws, { pid: process.pid, ageMs: 31 * 60 * 1000 })
- const handle = await acquireWorkspaceLock(root, ws)
- handle.release()
-})
-
-it('release never removes a lock taken over by another owner', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- const handle = await acquireWorkspaceLock(root, ws)
- // Simulate a takeover: the file now belongs to someone else.
- await writeLock(root, ws, { pid: process.pid })
- handle.release()
- // The foreign lock survives; a new acquirer still sees it as busy.
- await assert.rejects(() => acquireWorkspaceLock(root, ws), WorkspaceLockBusyError)
-})
-
-it('withWorkspaceLock runs the work and always releases', async () => {
- const root = await makeRoot()
- const ws = join(root, 'workspace')
- const result = await withWorkspaceLock(root, ws, async () => 'done')
- assert.equal(result, 'done')
- assert.equal(existsSync(lockPath(root, ws)), false)
- await assert.rejects(
- () => withWorkspaceLock(root, ws, async () => {
- throw new Error('boom')
- }),
- /boom/u,
- )
- assert.equal(existsSync(lockPath(root, ws)), false, 'release must happen even when the work throws')
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/tsconfig.json b/archiving/dsh-tauri-turnrewind-ts/tsconfig.json
deleted file mode 100644
index 520166d0..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/tsconfig.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "extends": "../../tsconfig.json",
- "include": ["src/**/*.ts", "src/**/*.tsx", "../../types/**/*.d.ts"]
-}
diff --git a/archiving/dsh-tauri-turnrewind-ts/tsdown.config.ts b/archiving/dsh-tauri-turnrewind-ts/tsdown.config.ts
deleted file mode 100644
index 58ba9a4f..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/tsdown.config.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { defineDshConfig } from 'dsh-tauri-tsdown'
-
-export default defineDshConfig({
- // The client half runs inside the DSH Web ModuleLoader (Chromium webview),
- // never on Node. Without an explicit target, tsdown infers node22.15.0 from
- // this package's `engines.node`, and warnLegacyCJS then flags the intentional
- // CJS client bundle as a legacy CommonJS package — escalated to an
- // "We recommend using the ESM format" ERROR (exit 1) by tsdown's default
- // `failOnWarn: 'ci-only'` under CI=true. Pin the client bundle to its real
- // runtime floor (es2022; WebView2 is evergreen Chromium) so the CJS contract
- // stays intact and the warning is corrected at the source. The host half
- // keeps its Node target, and every other warning remains CI-fatal.
- client: { target: 'es2022' },
-})
diff --git a/archiving/dsh-tauri-turnrewind-ts/vitest.config.ts b/archiving/dsh-tauri-turnrewind-ts/vitest.config.ts
deleted file mode 100644
index ab33fb46..00000000
--- a/archiving/dsh-tauri-turnrewind-ts/vitest.config.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-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/docs/plugins/11.\344\274\230\345\214\226\350\256\241\345\210\222.turnrewind\345\256\236\347\216\260.md" "b/docs/plugins/11.\344\274\230\345\214\226\350\256\241\345\210\222.turnrewind\345\256\236\347\216\260.md"
index f18ff6fb..6f54ccd6 100644
--- "a/docs/plugins/11.\344\274\230\345\214\226\350\256\241\345\210\222.turnrewind\345\256\236\347\216\260.md"
+++ "b/docs/plugins/11.\344\274\230\345\214\226\350\256\241\345\210\222.turnrewind\345\256\236\347\216\260.md"
@@ -2,7 +2,8 @@
> 状态:**已实施**(方案经确认后落地;实施结果与验证证据见文末 §11)
> 关联文档:[docs/spec/TURNREWIND.md](../spec/TURNREWIND.md)(交互稿)、[docs/AGENTS.plugins.md](../AGENTS.plugins.md)(插件规范)
-> 归档参考:`archiving/dsh-tauri-turnrewind-ts/`(**仅作参考,不参与实现**,属旧架构 demo)
+> 归档参考:旧架构 demo `dsh-tauri-turnrewind-ts`(**仅作参考、从未参与实现**)已按需求**删除**;
+> 由它提取出的加固项与延后项记录见 §13(提取清单与裁决)与 §13.3(TODO)。
---
@@ -649,7 +650,7 @@ eslint 0 error / 0 warning;`tsc --noEmit` 通过;`pnpm build:plugins` 重新
### 13.0 缘起、清单与裁决
-按需求复核 `archiving/dsh-tauri-turnrewind-ts/`(**仍只作参考、不拷贝代码**),提取出对现架构
+按需求复核旧架构 demo `dsh-tauri-turnrewind-ts`(**仍只作参考、不拷贝代码**),提取出对现架构
有价值的一组加固项,编号 `B1–B14` 与 `A4`。需求方裁决:
| 裁决 | 内容 |
@@ -719,3 +720,85 @@ eslint 0 error / 0 warning;`tsc --noEmit` 通过;`pnpm build:plugins` 重新
| 上限的可测性 | 真实上限(64MB / 512MB / 2GB) | 全部提供**选项覆盖**(`CaptureOptions.limits`、`{ maxRepoMb }`),缺省仍是宿主常量;测试用小上限走完同一条代码路径 |
| `GIT_UNAVAILABLE` | 有单测 | **未单测**:模拟「没有 git」需要改进程级 `PATH`,会污染同进程其它用例;已通过探测路径的代码审查与缓存不写入保证覆盖 |
+## 14. 第五轮:开放「打开文件」(新核心进侧边栏 / 旧核心静默)
+
+### 14.0 需求与关键调研
+
+> 需求原文:**「开放"打开文件"的功能,但要像官方新核心 `.nArs4W_producedChip` 一样,
+> 打开侧边栏的文件,旧核心静默(不打开文件)」**,并追加 **「不要加 hover 样式,
+> 就开放功能就好」**。
+
+先核对了两个内核里 `turnTail` owner props 的 `openFile` 到底是什么——**这是本轮最关键的一步**,
+因为两个内核都派发它,若只按「有没有 `openFile`」判断,旧核心上会**打开系统程序**:
+
+| 内核 | 派发点 | `openFile(path)` 的实现 | 实际效果 |
+|---|---|---|---|
+| `0.1.5-rc.1` | `dsh-client-ui-chat/lib/client.js` `TurnTailNodeView` → `renderSlotChain('conversation.chat.turnTail', { turn, seq, openFile })` | `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`(可带 `{ line }`) | **应用内右侧边栏**文本预览页签 |
+| `0.1.2-rc.1` | 同上(同样的 `{ turn, seq, openFile }`) | `ctx.remote.session.openWorkspacePath({ path: resolveWorkspacePath(cwd, path) })` | 交给**宿主/系统**打开该路径 |
+
+官方新核心的 `producedChip` 也正是走这条路(`dsh-client-ui-deliverables` 的 `ProducedFiles`:
+`<button onClick={() => openFile(path)}>`),README 原文即「Each chip opens the file through the
+owner's `openFile`, which the chat view routes to the right Sidebar as a text-preview tab」。
+
+### 14.1 判据:能力探测,不是版本号
+
+`0.1.5-rc.1` 的 `dsh-client-ui-sidebar-right` 会 `ctx.reflect.provide('sidebarRight', controller)`;
+`0.1.2-rc.1` 里**连这个包都不存在**(`@deepseek-ai` 下只有 `dsh-client-ui-sidebar`,且不提供
+`openResource`)。因此判据取「`sidebarRight` 服务是否存在」:
+
+| 决策 | 落地 |
+|---|---|
+| 何时探测 | **点击那一刻**,而不是 `apply` 时——`sidebarRight` 由另一个客户端插件发布,apply 顺序不保证它已就位 |
+| 怎么探测 | `ctx.reflect.get('sidebarRight')`(cordis 的 reflect 直接查注册表,不受 inject 守卫限制) |
+| 为什么不写进 `inject` | 声明式依赖在旧内核上会让**插件加载直接失败**;能力探测缺席时只是退化成「不可点」 |
+| 为什么不用 `openFile.length` / 版本号 | 前者是脆弱实现细节,后者与「内核继续漂移」的既定风险直接冲突 |
+
+能力缺席时的渲染也一并处理:标题与清单行渲染成**不可点的普通元素**(`<span>` / `<div>`),
+不渲染「点了没反应」的按钮——「静默」应当是**没有假交互**,而不是有交互但什么都不做。
+
+### 14.2 落地
+
+| 文件 | 变更 |
+|---|---|
+| `client/capabilities/index.ts`(新) | `registerCapabilities(ctx)` / `hasSidebarPreview()`;disposer 只在仍是自己那次安装时清引用 |
+| `client/utils/open-file.ts`(新) | 纯函数 `fileOpenHandler({ openFile, sidebarPreview })`:两条都满足才返回处理器;打开失败(同步抛错 / rejected promise)静默——卡片没有错误面,且打开只是便利功能 |
+| `client/index.ts` | 新增 `ctx.effect(() => registerCapabilities(cx), …: capabilities)` |
+| `client/constants/index.ts` | `TURNREWIND_SIDEBAR_RIGHT_SERVICE = 'sidebarRight'` + effect 标签(注释里写明**为什么绝不能进 `inject`**) |
+| `client/components/turn-changes-card.tsx` | 单文件标题 → `<button class="__title--link">`(`title` 放完整路径、`aria-label` 用新文案 `openFile: '打开 {name}'`);清单行经 `renderFileRow` 二选一渲染(可点 → `<button>`,否则 `<div>`);删除 `TODO(open-file)` |
+| `client/components/turn-changes-card.cssr.ts` | 新增 `__title--link` 与 `__file--open` 的**按钮基座重置**(`border:none` / `background:transparent` / `font-family:inherit` / `text-align:left` / `color:inherit` / `cursor:pointer`);**刻意不加任何 hover 规则**,并在注释里写明「清单行原有的 `&:hover` 背景是上一轮就有的,本次没有新增」 |
+| `client/locales/index.ts` | 中英文各加 `openFile` 一条 |
+
+### 14.3 验证
+
+| 项 | 结果 |
+|---|---|
+| 新增测试 | `client/capabilities/index.test.ts`(7:未安装 / 新内核有服务 / 旧内核无服务 / 注册表抛错 / 缺 reflect / disposer / 旧实例 disposer 不误清新实例);`client/utils/open-file.test.ts`(7:可用路径、**旧内核即使有 `openFile` 也一次都不调用**、缺 `openFile`、脏字段、rejected promise 静默、同步抛错静默、路径原样透传) |
+| cssr 测试 | 新增一条钉住「只加按钮基座、**没有** `__title--link:hover` / `__file--open:hover`」 |
+| 包内 / 根全量 | **13 文件 / 93 用例**;根全量见 §14.6(写于本轮中途,最终数见 14.6) |
+| bundle 审计 | 模块请求仍只有 `react` / `react/jsx-runtime` / `dsh-tauri/client` / `dsh-tauri-ui/client`,`@deepseek-ai/` **0 次**;产物内确认调用形态为 `j!==void 0&&M!==void 0 ? <button className="…__title--link" onClick={()=>j(M)}> : <span>`,CSS 里无新增 hover 规则 |
+
+### 14.4 诚实记录
+
+- 「旧核心静默」是用**能力探测**实现的,不是运行时开关:若某个更老/更新的内核同样没有
+ `sidebarRight`,行为一样是静默;若某内核提供了该服务,则会打开侧边栏(这才是需求语义)。
+- 打开失败被静默吞掉(含 rejected promise):卡片没有错误展示面,且打开文件只是便利功能。
+ 若日后要给出失败反馈,应在 store 里加一条错误态,而不是在这里 `console` 输出。
+- 本轮**未**恢复 hover 换行(`TODO(view-changes-hover)` 仍保留),也没有给可点元素加下划线等
+ hover 视觉——需求明确「不要加 hover 样式」。
+
+### 14.5 验收反馈的修正
+
+| 反馈 | 原因 | 修正 |
+|---|---|---|
+| 单文件与多文件的标题样式不一样 | **真 bug**:`__title--link` 的基座里写了 `font-size/font-weight/line-height: inherit`,而该规则排在 `__title` **之后**,于是把标题的 13px/600 覆盖成了卡片根的 12px/常规字重 | 基座**只保留 `font-family: inherit`**(按钮不继承字体族;其余排印属性交给 `__title`);新增 cssr 用例钉住「`--link` 块内不得出现 font-size/font-weight/line-height」,注释里写明原因 |
+| 删除归档 `archiving/dsh-tauri-turnrewind-ts` | 该 demo 只用于参考与提取清单(§13.0),清单已落进文档,代码本身不再有价值,留着只会被误当实现参考 | `git rm -r archiving/`;清掉 `eslint.config.mjs` 里随之失效的 `'archiving'` ignore;文档里三处指向该目录的路径改为「已删除的旧架构 demo」 |
+
+### 14.6 本轮验证
+
+| 项 | 结果 |
+|---|---|
+| `npx vitest run packages/dsh-tauri-turnrewind` | **13 文件 / 94 用例**全通过 |
+| `npx vitest run`(根全量) | **35 文件 / 254 用例**全通过(删除 `archiving/` 后无任何引用断裂) |
+| `npx tsc --noEmit` / `eslint` | 通过 / 0 error 0 warning |
+| 部署 | 按需求**不再执行 `pnpm build:plugins`**(dev 常开,改由重启应用加载);已部署产物的模块请求与 `@deepseek-ai/` 计数在 §14.3 记录在案 |
+
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 8c22e836..671a8f35 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -7,7 +7,6 @@ export default antfu({
react: true,
ignores: [
'AGENTS.*',
- 'archiving',
'docs',
],
}, {
diff --git a/packages/dsh-tauri-turnrewind/README.md b/packages/dsh-tauri-turnrewind/README.md
index 2852e667..c4c5c610 100644
--- a/packages/dsh-tauri-turnrewind/README.md
+++ b/packages/dsh-tauri-turnrewind/README.md
@@ -11,7 +11,7 @@ DSH 桌面端的 **turn 级工作区撤销**:每一轮对话结束时,在对
- 对用户仓库**全程只读**:不碰 HEAD / 分支 / index / stash / 提交历史。
设计与决策记录:[`docs/plugins/11.优化计划.turnrewind实现.md`](../../docs/plugins/11.优化计划.turnrewind实现.md)
-(含调研结论、与归档 demo 的差异、双内核适配矩阵)。
+(含调研结论、与已删除的旧架构 demo 的差异、双内核适配矩阵)。
## 交互
@@ -42,13 +42,18 @@ DSH 桌面端的 **turn 级工作区撤销**:每一轮对话结束时,在对
|---|---|
| `撤销 ↶` | **真功能**:撤销该轮的文件改动;**撤销成功后按钮消失**,只留「已撤销」徽标 |
| 「再显示 N 个文件 ⌄」/「收起文件 ⌃」 | 真功能:展开 / 收起(清单默认 3 行,展开后底部仍有「收起文件」可回到 3 行) |
+| 单文件标题 / 清单行点击打开文件 | **真功能**:在**应用内右侧边栏**打开该文件的文本预览页签(同官方 `producedChip`)。仅在具备该能力的内核上生效,见下 |
| `+` 图标块(文件) | **占位**(无点击处理,`data-placeholder` 标注) |
| 单文件 / 多文件标题 hover 的「查看更改 ↗」 | **暂时整体停用**(源码 `TODO(view-changes-hover)` 保留实现;恢复时单文件与多文件的 `__head` 都要生效) |
-| 单文件标题 / 清单行点击打开文件 | **暂时停用**(源码 `TODO(open-file)` 保留实现;当前卡片只显示 `+xx -x`) |
| `审核` | **暂时整体隐藏**(源码 `TODO(review-action)` 保留按钮实现) |
- 单文件:标题即文件名、不渲染清单;多文件:标题是文件数、副行是总计(绿 `+N` / 红 `-M`)。
-- 文件清单最多三行,其余折叠;行 hover 高亮;本轮删除(D)的文件整行弱化。
+- **打开文件按内核能力分流**:新核心(`0.1.5-rc.1`,有应用内右侧边栏)→ 点标题 / 清单行
+ 在侧边栏打开预览页签;旧核心(`0.1.2-rc.1`,`openFile` 会把路径交给宿主/系统打开)→
+ **完全静默**:标题与清单行渲染成不可点的普通元素,不调用 `openFile`(不给假交互)。
+ 判定不看版本号,只看有没有 `sidebarRight` 服务(见 client/capabilities)。
+- 本轮**只开放功能,没有新增任何 hover 样式**;清单行原有的 hover 背景高亮是上一轮视觉对齐时就有的。
+- 文件清单最多三行,其余折叠;本轮删除(D)的文件整行弱化。
- **已撤销的 turn**:只剩「已撤销」徽标与文件名/清单行,不再有撤销按钮与审核。
- 该轮没有任何文件变化 → 不出现卡片。
- 撤销成功后同一 turn 不能重复撤销。
@@ -113,7 +118,7 @@ $DSH_HOME/dsh-tauri-turnrewind/
其「点文件名在右侧栏预览」的行为随之消失(需求已确认接受)。若之后要保留点击,
把文件行接到 `TurnTailOwnerProps.openFile` 即可(一行)。
- 未做:redo、父对话递归撤销、保留策略设置面、恢复围栏、撤销后给模型的一次性提示注入。
- 从归档 demo 提取但**按需求方裁决延后**的项(敏感文件提示、弹窗焦点陷阱、账本版本备份、
+ 从旧架构 demo 提取(该 demo 已按需求删除)但**按需求方裁决延后**的项(敏感文件提示、弹窗焦点陷阱、账本版本备份、
工作区漂移绑定、中断撤销日志等)记录在
[`docs/plugins/11.优化计划.turnrewind实现.md`](../../docs/plugins/11.优化计划.turnrewind实现.md) §13.3。
- **运行中提示条的取数成本**:宿主在 turn 进行期间每 1.5s 跑一次 `git add --all` +
@@ -161,6 +166,22 @@ ModuleLoader 的 factory 里运行,模块表只认识当前内核实际装载
owner 份额里读到 `running: false` 时既提前停轮询、也立刻整条隐藏(字段缺失按「可能在跑」处理),
因此内核调整会话快照字段也不会让提示条失效。会话结束后只剩 turn 尾部的变更卡片。
+### 「打开文件」的内核差异(本轮新增的唯一一处行为分流)
+
+`conversation.chat.turnTail` 的 owner props 在**两个内核上都**带 `openFile`,但语义不同:
+
+| 内核 | `openFile(path)` 实际做的事 | 本插件的行为 |
+|---|---|---|
+| `0.1.5-rc.1` | `ctx.sidebarRight.openResource(fileAddress(sessionId, cwd, path))` —— 应用内右侧边栏文本预览页签 | **调用它**(同官方 `producedChip`) |
+| `0.1.2-rc.1` | `ctx.remote.session.openWorkspacePath({ path })` —— 交给宿主/系统打开该路径 | **不调用**(静默,渲染成不可点元素) |
+
+判据因此不是「有没有 `openFile`」,也不是版本号,而是**有没有 `sidebarRight` 服务**
+(新内核由 `dsh-client-ui-sidebar-right` 经 `ctx.reflect.provide('sidebarRight', …)` 发布;
+旧内核连这个包都没有)。探测在**点击那一刻**做——`sidebarRight` 由另一个客户端插件发布,
+apply 顺序不保证它已就位;探测方式是 `ctx.reflect.get('sidebarRight')`(cordis 的 reflect
+直接查注册表,不受 inject 守卫限制),因此本插件**不把 `sidebarRight` 写进 `inject`**:
+声明式依赖会让旧内核上的插件加载直接失败。内核再漂移也只是退化成「不可点」,不会误开系统程序。
+
## 开发
```powershell
@@ -178,4 +199,6 @@ CRLF/属性往返对称(恢复后与 before 快照树逐字节等价)、冲
(prune 只清不可达对象、超限整仓重建 + 代数轮换、排除清单复检、不碰用户仓库)、
工作区队列(FIFO 不重叠 / 跨工作区不阻塞 / 队尾出队)、
账本原子写与保留淘汰、卡片状态机与计数/文件名/原因码纯函数、
-卡片与提示条的 css-render 形态(hover 换行、配色、几何、提示行分级)。
+**打开文件的内核能力判据**(无 `sidebarRight` 时绝不调用 `openFile`;同步抛错 / rejected
+promise 都静默;disposer 清理)、
+卡片与提示条的 css-render 形态(hover 换行、配色、几何、提示行分级、按钮基座且无新增 hover)。
diff --git a/packages/dsh-tauri-turnrewind/src/client/capabilities/index.test.ts b/packages/dsh-tauri-turnrewind/src/client/capabilities/index.test.ts
new file mode 100644
index 00000000..b7a8349b
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind/src/client/capabilities/index.test.ts
@@ -0,0 +1,74 @@
+/**
+ * client/capabilities/index.test.ts — 「打开文件」的内核能力判据。
+ *
+ * 守的是一条需求硬约束:**旧内核必须静默**(它同样派发 `openFile`,但会把路径交给
+ * 宿主/系统去打开)。判据是「有没有 `sidebarRight` 服务」,不是版本号。
+ */
+
+import type { ClientContext } from 'dsh-tauri/client'
+import { afterEach, describe, expect, it } from 'vitest'
+import { hasSidebarPreview, registerCapabilities } from './index'
+
+/** 最小上下文替身:只提供能力探测真正读到的 `reflect.get`。 */
+function contextWith(service: unknown, options: { throws?: boolean } = {}): ClientContext {
+ return {
+ reflect: {
+ get: () => {
+ if (options.throws === true)
+ throw new Error('registry unavailable')
+ return service
+ },
+ provide: () => () => {},
+ },
+ } as unknown as ClientContext
+}
+
+afterEach(() => {
+ // 每个用例都从「尚未安装」的干净状态开始:卸载即清引用。
+ registerCapabilities(contextWith(undefined))()
+})
+
+describe('hasSidebarPreview', () => {
+ it('未安装上下文时按「没有该能力」处理(绝不误开外部程序)', () => {
+ registerCapabilities(contextWith(undefined))()
+ expect(hasSidebarPreview()).toBe(false)
+ })
+
+ it('新内核:reflect 里有 sidebarRight 服务 → 可用', () => {
+ registerCapabilities(contextWith({ openResource: () => {} }))
+ expect(hasSidebarPreview()).toBe(true)
+ })
+
+ it('旧内核:没有 sidebarRight 服务 → 不可用(静默)', () => {
+ // 旧内核的 reflect 里没有这个键,get 返回 undefined。
+ registerCapabilities(contextWith(undefined))
+ expect(hasSidebarPreview()).toBe(false)
+ })
+
+ it('注册表读取抛错时按不可用处理,不冒泡', () => {
+ registerCapabilities(contextWith(undefined, { throws: true }))
+ expect(hasSidebarPreview()).toBe(false)
+ })
+
+ it('缺少 reflect 的壳也不会崩', () => {
+ registerCapabilities({} as unknown as ClientContext)
+ expect(hasSidebarPreview()).toBe(false)
+ })
+
+ it('disposer 清掉引用后回到不可用', () => {
+ const ctx = contextWith({ openResource: () => {} })
+ const dispose = registerCapabilities(ctx)
+ expect(hasSidebarPreview()).toBe(true)
+ dispose()
+ expect(hasSidebarPreview()).toBe(false)
+ })
+
+ it('disposer 只在仍是自己那次安装时才清引用(避免卸载旧实例清掉新实例)', () => {
+ const first = contextWith({ openResource: () => {} })
+ const second = contextWith({ openResource: () => {} })
+ const disposeFirst = registerCapabilities(first)
+ registerCapabilities(second)
+ disposeFirst()
+ expect(hasSidebarPreview()).toBe(true)
+ })
+})
diff --git a/packages/dsh-tauri-turnrewind/src/client/capabilities/index.ts b/packages/dsh-tauri-turnrewind/src/client/capabilities/index.ts
new file mode 100644
index 00000000..ca6fb431
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind/src/client/capabilities/index.ts
@@ -0,0 +1,57 @@
+/**
+ * client/capabilities/index.ts — 运行时能力探测(跨内核代,不做版本嗅探)。
+ *
+ * 「打开文件」在两个内核代上的含义**完全不同**:
+ *
+ * | 内核 | owner props 的 `openFile(path)` 实际做的事 |
+ * |---|---|
+ * | `0.1.5-rc.1` | `ctx.sidebarRight.openResource(fileAddress(...))` —— 在**应用内右侧边栏**打开文本预览页签 |
+ * | `0.1.2-rc.1` | `ctx.remote.session.openWorkspacePath({ path })` —— 交给**宿主/系统**去打开该路径 |
+ *
+ * 需求是「像官方新核心那样打开侧边栏的文件,旧核心静默(不打开文件)」。两者都派发
+ * `openFile`,因此**不能靠 `openFile` 是否存在**来区分;判据取「右侧边栏能力是否存在」:
+ * 新内核由 `dsh-client-ui-sidebar-right` 经 `ctx.reflect.provide('sidebarRight', …)` 发布,
+ * 旧内核连这个包都没有。用能力探测而不是版本号判断,内核再漂移也不会误开系统程序。
+ *
+ * 探测在**点击那一刻**做(而不是 apply 时):`sidebarRight` 由另一个客户端插件发布,
+ * apply 顺序不保证它已经就位。
+ */
+
+import type { ClientContext } from 'dsh-tauri/client'
+import { TURNREWIND_SIDEBAR_RIGHT_SERVICE } from '../constants'
+
+/** 已安装的上下文(apply 时注入;未安装 = 尚无能力信息,按「没有」处理)。 */
+let context: ClientContext | undefined
+
+/**
+ * 安装能力探测所需的上下文。
+ * @param ctx - 客户端根上下文。
+ * @returns 卸载时清除引用的 disposer(避免插件卸载后残留旧上下文)。
+ */
+export function registerCapabilities(ctx: ClientContext): () => void {
+ context = ctx
+ return () => {
+ if (context === ctx)
+ context = undefined
+ }
+}
+
+/**
+ * 当前内核是否具备「应用内右侧边栏预览」能力。
+ *
+ * 用 `reflect.get` 读服务(cordis 的 reflect 直接查注册表,不受 inject 守卫限制),
+ * 因此本插件无需 `inject: ['sidebarRight']`——那会让旧内核上的插件加载直接失败。
+ * @returns 有 `sidebarRight` 服务时为 true。
+ */
+export function hasSidebarPreview(): boolean {
+ const reflect = context?.reflect
+ if (reflect === undefined || typeof reflect.get !== 'function')
+ return false
+ try {
+ return reflect.get(TURNREWIND_SIDEBAR_RIGHT_SERVICE) !== undefined
+ }
+ catch {
+ // 服务注册表在极端时序下可能抛错:按「没有该能力」处理,绝不因此报错。
+ return false
+ }
+}
diff --git a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.test.ts b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.test.ts
index 17a3905f..bc04e32b 100644
--- a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.test.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.test.ts
@@ -30,12 +30,33 @@ describe('turn-changes-card.cssr(视觉对齐官方 deliverables 行)', () =
})
it('hover「查看更改」当前整体停用:无 hover 换行规则,提示默认不占位', () => {
- // 需求:hover 效果与打开文件暂时全部停用,只显示 +xx -x(恢复见 CSSR 内 TODO 注释)。
+ // 需求:hover 效果暂时停用,只显示 +xx -x(恢复见 CSSR 内 TODO 注释)。
expect(css).not.toMatch(/\.dshp-turnrewind__card--single:hover/)
expect(css).not.toMatch(/\.dshp-turnrewind__card:hover/)
expect(css).toMatch(/\.dshp-turnrewind__hint\s*\{[^}]*display: none/)
})
+ it('「打开文件」开放后只加按钮基座,不加任何 hover 样式', () => {
+ // 单文件标题变成按钮:基座重置把按钮视觉拉回纯文本。
+ expect(css).toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*border: none/)
+ expect(css).toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*background: transparent/)
+ expect(css).toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*font-family: inherit/)
+ // 清单行的 `--open` 只负责指针样式(可点那一支),且**没有** hover 规则。
+ expect(css).toMatch(/\.dshp-turnrewind__file--open\s*\{[^}]*cursor: pointer/)
+ expect(css).not.toMatch(/\.dshp-turnrewind__title--link:hover/)
+ expect(css).not.toMatch(/\.dshp-turnrewind__file--open:hover/)
+ })
+
+ it('单文件标题按钮的排印与多文件标题一致(基座不得覆盖 __title 的字号/字重/行高)', () => {
+ // 真 bug 回归:`--link` 规则排在 `__title` 之后,若这里写 font-size/font-weight/
+ // line-height: inherit,会把标题退回卡片根的 12px + 常规字重,单文件与多文件就不一致了。
+ expect(css).toMatch(/\.dshp-turnrewind__title\s*\{[^}]*font-size: 13px/)
+ expect(css).toMatch(/\.dshp-turnrewind__title\s*\{[^}]*font-weight: 600/)
+ expect(css).not.toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*font-size/)
+ expect(css).not.toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*font-weight/)
+ expect(css).not.toMatch(/\.dshp-turnrewind__title--link\s*\{[^}]*line-height/)
+ })
+
it('文件行:hover 高亮;本轮删除的文件整行弱化', () => {
expect(css).toMatch(/\.dshp-turnrewind__file:hover\s*\{[^}]*background: var\(--dsw-alias-interactive-bg-hover/)
expect(css).toMatch(/\.dshp-turnrewind__file--deleted\s*\{[^}]*color: var\(--dsw-alias-label-tertiary/)
diff --git a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.ts b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.ts
index 37d71a2f..1849f3ff 100644
--- a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.cssr.ts
@@ -85,6 +85,29 @@ export default b('turnrewind', {
],
*/
),
+ /*
+ 「打开文件」已开放:单文件标题会被渲染成 `<button class="__title--link">`
+ (多文件清单行同理,见 `e('file')`)。这里只做**按钮基座重置**,使按钮的视觉与
+ 多文件的纯文本标题**完全一致**——刻意**不加任何 hover 规则**(需求:只开放功能、
+ 不加 hover 样式)。恢复 hover 换行时的写法见 `e('card')` 里的 TODO(view-changes-hover)。
+
+ 注意:字号/字重/行高**故意不写**。`__title`(同一个元素上)已经给了 13px/600/18px,
+ 这里再写 `font-size: inherit` 之类反而会因为规则在后面而**覆盖掉**它们,
+ 按钮于是退回卡片根的 12px/常规字重——单文件与多文件标题就会看起来不一样。
+ 只需要 `font-family: inherit`:按钮不会继承字体族(其余排印属性由 `__title` 决定)。
+ */
+ e('title--link', {
+ display: 'block',
+ minWidth: '0',
+ maxWidth: '100%',
+ padding: '0',
+ border: 'none',
+ background: 'transparent',
+ fontFamily: 'inherit',
+ textAlign: 'left',
+ color: 'inherit',
+ cursor: 'pointer',
+ }),
e('sub', {
display: 'flex',
alignItems: 'center',
@@ -157,6 +180,12 @@ export default b('turnrewind', {
e('files', {
borderTop: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.18))',
}),
+ /*
+ 清单行同时服务两种渲染:具备打开能力时是 `<button>`,否则是 `<div>`。
+ 下面这几条是按钮基座重置(对 `<div>` 无副作用),视觉与原来的行完全一致;
+ **刻意不加 hover 规则**——保留的 `&:hover` 背景高亮是上一轮视觉对齐时就有的,
+ 本次开放点击没有新增任何 hover 样式。
+ */
e('file', {
boxSizing: 'border-box',
display: 'flex',
@@ -164,18 +193,20 @@ export default b('turnrewind', {
gap: '10px',
width: '100%',
padding: '7px 10px',
+ border: 'none',
+ background: 'transparent',
+ fontFamily: 'inherit',
fontSize: '13px',
lineHeight: '18px',
+ textAlign: 'left',
+ color: 'inherit',
}, [
c('&:hover', { background: 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.06))' }),
// 本 turn 删除的文件整行弱化:它们已不在工作区里。
m('deleted', { color: 'var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary))' }),
+ // 只有可点的那一支才带 `--open`(按钮指针样式;不可点的那支渲染成 <div>)。
+ m('open', { cursor: 'pointer' }),
]),
- /*
- TODO(open-file): 清单行改为 <button> 打开文件时,在 `e('file', …)` 里补回按钮基座重置:
- `border: 'none'`、`background: 'transparent'`、`font: 'inherit'`、
- `textAlign: 'left'`、`color: 'inherit'`、`cursor: 'pointer'`。
- */
e('file-path', {
flex: '1',
minWidth: 0,
diff --git a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.tsx b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.tsx
index 85fe2578..3d1f5605 100644
--- a/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.tsx
+++ b/packages/dsh-tauri-turnrewind/src/client/components/turn-changes-card.tsx
@@ -1,5 +1,5 @@
import type { ReactElement } from 'react'
-import type { TurnChangesCardProps } from '../types'
+import type { TurnChangesCardProps, TurnFileChange } from '../types'
import { ArrowRotateLeft, ChevronDown, ChevronUp, Icon, SquarePlus, useMountStyle } from 'dsh-tauri-ui/client'
/**
* turn-changes-card.tsx — 一轮结束时渲染的变更卡片(视觉对齐官方 deliverables 行)。
@@ -7,16 +7,23 @@ import { ArrowRotateLeft, ChevronDown, ChevronUp, Icon, SquarePlus, useMountStyl
* 职责拆分:槽位注册在 register/turn-tail.ts,数据在 store/,样式在 .cssr.ts,
* 纯函数判定与格式化在 utils/format.ts(本文件只做组合与交互)。
*
- * 交互边界(需求明确):只有「撤销」是真功能;`📝 文件`(图标块)、
- * 「查看更改」(单文件卡片 hover 出现)、「审核」三者一律为占位
- * (无点击处理,用 data-placeholder 标明,便于测试钉住)。
- * 「再显示 N 个文件」是真实功能(展开/收起)。
+ * 交互边界(需求明确):
+ * - **真功能**:「撤销」、「再显示 N 个文件 / 收起文件」、**点击文件打开**;
+ * - **占位**:`📝 文件`(图标块)无点击处理(`data-placeholder` 标注);
+ * 「审核」整体隐藏(`TODO(review-action)`);
+ * hover 的「查看更改」整体停用(`TODO(view-changes-hover)`,本次开放打开功能**未**附带 hover 视觉)。
+ *
+ * 「点击文件打开」按内核能力分流:新核心经 owner props 的 `openFile` 在应用内右侧边栏
+ * 打开预览页签;旧核心虽然也派发 `openFile`(会交给宿主/系统打开),但需求要求那里
+ * **静默**,因此只在探测到右侧边栏能力时才把标题 / 清单行渲染成可点元素
+ * (见 client/capabilities/index.ts 与 client/utils/open-file.ts)。
*
* 单文件与多文件的差异:单文件时标题就是文件名、不渲染清单,
- * hover 时副行的计数换成「查看更改 ↗」;多文件时标题是文件数、
+ * hover 时副行的计数换成「查看更改 ↗」(当前停用);多文件时标题是文件数、
* 副行固定显示总计数,清单最多三行。
*/
import { useEffect, useState } from 'react'
+import { hasSidebarPreview } from '../capabilities'
import {
TURNREWIND_CARD_STYLE_ID,
TURNREWIND_COUNTS_STYLE_ID,
@@ -28,6 +35,7 @@ import { text, useLocale } from '../locales'
import { ensureSummary, requestUndo, retrySummaryForTurn, useTurnrewindSession } from '../store'
import countsStyle from '../styles/counts.cssr'
import { cardTitle, fileListWindow, formatCounts, formatTotals, reasonKey, resolveCardState } from '../utils/format'
+import { fileOpenHandler } from '../utils/open-file'
import { ChangeCounts } from './change-counts'
import { GitRequiredDialog } from './git-required-dialog'
import cardStyle from './turn-changes-card.cssr'
@@ -101,20 +109,6 @@ export function TurnChangesCard(props: TurnChangesCardProps): ReactElement | nul
const skippedOversized = record?.skippedOversized ?? []
const skippedNestedRepos = record?.skippedNestedRepos ?? []
- /*
- TODO(open-file): 「点击打开文件」暂时停用(需求方要求),当前卡片只展示 +xx -x。
- 恢复步骤:
- 1. 取回框架派发的 openFile(turnTail 的 owner 份额自带,相对路径按会话 cwd 解析);
- 2. 单文件卡片把标题渲染成 <button class="__title--link">、多文件清单把每一行渲染成
- <button class="__file">,onClick 调 openFile(path);
- 3. cssr 里把 __title--link 与 __file 的按钮基座重置/指针样式一并恢复
- (`__file` 现在渲染成 <div>,那些重置已注释)。
- 内核对缺席的 openFile 必须优雅降级(渲染纯文本 / <div>,不报错、不白屏)。
-
- const openFile = typeof props.openFile === 'function' ? props.openFile : undefined
- const singlePath = single ? files[0]?.path : undefined
- */
-
const onUndo = (): void => {
if (gitRequired) {
setDialogOpen(true)
@@ -125,6 +119,59 @@ export function TurnChangesCard(props: TurnChangesCardProps): ReactElement | nul
void requestUndo(sessionId, turn)
}
+ /*
+ 「打开文件」:只在**具备应用内右侧边栏能力**的内核上生效(新核心 = 侧边栏预览页签)。
+ 旧核心虽然也派发 openFile,但它会把路径交给宿主/系统去打开,需求要求那里保持静默;
+ 判据与理由见 client/capabilities/index.ts 与 client/utils/open-file.ts。
+ 能力缺席时标题与清单行渲染成不可点的普通元素(不给「点了没反应」的假交互)。
+ */
+ const onOpenFile = fileOpenHandler({ openFile: props.openFile, sidebarPreview: hasSidebarPreview() })
+ const singlePath = single ? files[0]?.path : undefined
+ const openLabel = (path: string): string => text('openFile', { name: path })
+
+ /**
+ * 清单行:具备打开能力时渲染成按钮,否则是不可点的普通行——
+ * 不给「点了没反应」的假交互(旧内核上就是这一支)。
+ */
+ const renderFileRow = (file: TurnFileChange): ReactElement => {
+ const deleted = file.status === 'D' ? ' dshp-turnrewind__file--deleted' : ''
+ const className = `dshp-turnrewind__file${deleted}${onOpenFile === undefined ? '' : ' dshp-turnrewind__file--open'}`
+ const label = `${file.path} ${formatCounts(file, text('binary'))}`
+ const content = (
+ <>
+ <span className="dshp-turnrewind__file-path">{file.path}</span>
+ <span className="dshp-turnrewind__file-counts">
+ <ChangeCounts
+ insertions={file.insertions}
+ deletions={file.deletions}
+ binary={file.binary}
+ binaryLabel={text('binary')}
+ />
+ </span>
+ </>
+ )
+ if (onOpenFile === undefined) {
+ return (
+ <div key={file.path} className={className} data-status={file.status} title={label}>
+ {content}
+ </div>
+ )
+ }
+ return (
+ <button
+ key={file.path}
+ type="button"
+ className={className}
+ data-status={file.status}
+ title={label}
+ aria-label={openLabel(file.path)}
+ onClick={() => onOpenFile(file.path)}
+ >
+ {content}
+ </button>
+ )
+ }
+
return (
<div className="dshp-turnrewind">
<div
@@ -137,7 +184,19 @@ export function TurnChangesCard(props: TurnChangesCardProps): ReactElement | nul
<Icon as={SquarePlus} size={18} />
</span>
<div className="dshp-turnrewind__meta">
- <span className="dshp-turnrewind__title" title={title}>{title}</span>
+ {onOpenFile !== undefined && singlePath !== undefined
+ ? (
+ <button
+ type="button"
+ className="dshp-turnrewind__title dshp-turnrewind__title--link"
+ title={singlePath}
+ aria-label={openLabel(singlePath)}
+ onClick={() => onOpenFile(singlePath)}
+ >
+ {title}
+ </button>
+ )
+ : <span className="dshp-turnrewind__title" title={title}>{title}</span>}
<span className="dshp-turnrewind__sub">
{record !== null
? (
@@ -152,7 +211,9 @@ export function TurnChangesCard(props: TurnChangesCardProps): ReactElement | nul
</span>
{/*
TODO(view-changes-hover): hover 显示「查看更改」暂时整体停用(需求方要求),
- 当前只显示 +xx -x。恢复时注意三条:
+ 当前只显示 +xx -x。注意:「打开文件」已单独开放(点击标题 / 清单行即可),
+ 但**没有**因此加回任何 hover 视觉——恢复本项时要保持这两件事彼此独立。
+ 恢复时注意三条:
1. 单文件与**多文件**的 __head 都要有该 hover 效果(不再用 single 条件限定);
2. 重新从 dsh-tauri-ui/client 引入 ArrowUpRight 图标;
3. cssr 里把 `.dshp-turnrewind__card:hover` 下的
@@ -200,28 +261,7 @@ export function TurnChangesCard(props: TurnChangesCardProps): ReactElement | nul
{window.visible.length > 0 && (
<div className="dshp-turnrewind__files">
- {window.visible.map(file => (
- <div
- key={file.path}
- className={`dshp-turnrewind__file${file.status === 'D' ? ' dshp-turnrewind__file--deleted' : ''}`}
- data-status={file.status}
- title={`${file.path} ${formatCounts(file, text('binary'))}`}
- >
- <span className="dshp-turnrewind__file-path">{file.path}</span>
- <span className="dshp-turnrewind__file-counts">
- <ChangeCounts
- insertions={file.insertions}
- deletions={file.deletions}
- binary={file.binary}
- binaryLabel={text('binary')}
- />
- </span>
- </div>
- ))}
- {/*
- TODO(open-file): 清单行改为可点击打开文件时,把上面的 <div> 换成
- <button class="__file" onClick={() => openFile(file.path)}>(见文件顶部 TODO(open-file))。
- */}
+ {window.visible.map(file => renderFileRow(file))}
</div>
)}
diff --git a/packages/dsh-tauri-turnrewind/src/client/constants/index.ts b/packages/dsh-tauri-turnrewind/src/client/constants/index.ts
index f1ec3053..41ea99e8 100644
--- a/packages/dsh-tauri-turnrewind/src/client/constants/index.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/constants/index.ts
@@ -46,6 +46,15 @@ export const TURNREWIND_COUNTS_STYLE_ID = `${TURNREWIND_PLUGIN_NAME}/ChangeCount
export const TURNREWIND_EFFECT_TURN_TAIL = `${TURNREWIND_PLUGIN_NAME}: turn tail slot`
export const TURNREWIND_EFFECT_RUNNING_CHIP = `${TURNREWIND_PLUGIN_NAME}: running chip slot`
export const TURNREWIND_EFFECT_LOCALE = `${TURNREWIND_PLUGIN_NAME}: locale`
+export const TURNREWIND_EFFECT_CAPABILITIES = `${TURNREWIND_PLUGIN_NAME}: capabilities`
+
+/**
+ * 「应用内右侧边栏」服务名(新内核由 `dsh-client-ui-sidebar-right` 发布)。
+ *
+ * 只做**运行时探测**(`ctx.reflect.get`),绝不写进 `dsh.client.inject`:
+ * 旧内核没有这个服务,声明式依赖会让插件在那边的加载直接失败。
+ */
+export const TURNREWIND_SIDEBAR_RIGHT_SERVICE = 'sidebarRight'
/** 卡片默认展示的文件行数(其余折叠到「再显示 N 个文件」)。 */
export const TURNREWIND_VISIBLE_FILE_ROWS = 3
diff --git a/packages/dsh-tauri-turnrewind/src/client/index.ts b/packages/dsh-tauri-turnrewind/src/client/index.ts
index d6c4b0d8..459c6a94 100644
--- a/packages/dsh-tauri-turnrewind/src/client/index.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/index.ts
@@ -3,12 +3,13 @@
*
* 四项装配(全部经 ctx.effect,卸载即释放):
* 1. locale:注册 zh/en 字典并把语言切换桥接到 uSES rev;
- * 2. 槽位 A:`conversation.chat.turnTail`(chain,priority -1)注册变更卡片 ——
- * 每轮结束处显示「已编辑 N 个文件 / +N -M / 文件清单 / 撤销 / 审核」,
+ * 2. 能力:装入运行时能力探测所需的上下文(「打开文件」是否可用的判据);
+ * 3. 槽位 A:`conversation.chat.turnTail`(chain,priority -1)注册变更卡片 ——
+ * 每轮结束处显示「已编辑 N 个文件 / +N -M / 文件清单 / 撤销」,
* 并以同样的优先级替换官方 “Files changed” 行;
- * 3. 槽位 B:`conversation.input.dock`(list)注册运行中提示条 ——
+ * 4. 槽位 B:`conversation.input.dock`(list)注册运行中提示条 ——
* 输入框上方实时显示「N 个文件已更改 +N -M」,turn 结束后消失;
- * 4. 样式:各组件 `useMountStyle` 自挂自卸,无需全局样式 effect。
+ * 5. 样式:各组件 `useMountStyle` 自挂自卸,无需全局样式 effect。
*
* 依赖纪律(跨内核代硬约束,见 docs/plugins/11.优化计划.turnrewind实现.md §2.4-B):
* 本文件与整个 client/ 目录**不静态引用任何 `@deepseek-ai/*` 包**——client bundle
@@ -19,7 +20,9 @@
import type { ClientContext } from 'dsh-tauri/client'
import { compat } from 'dsh-tauri/client'
+import { registerCapabilities } from './capabilities'
import {
+ TURNREWIND_EFFECT_CAPABILITIES,
TURNREWIND_EFFECT_LOCALE,
TURNREWIND_EFFECT_RUNNING_CHIP,
TURNREWIND_EFFECT_TURN_TAIL,
@@ -50,11 +53,15 @@ export const name = TURNREWIND_PLUGIN_NAME
export const inject = ['slots', 'locale']
/**
- * 插件体:安装文案、变更卡片与运行中提示条。
+ * 插件体:安装文案、能力探测、变更卡片与运行中提示条。
+ *
+ * 「打开文件」按内核能力分流(新核心 → 侧边栏预览;旧核心 → 静默),
+ * 能力探测所需的上下文由 {@link registerCapabilities} 装好(见 client/capabilities)。
* @param ctx - 客户端根上下文。
*/
export function apply(ctx: ClientContext): void {
const cx = compat(ctx)
+ ctx.effect(() => registerCapabilities(cx), TURNREWIND_EFFECT_CAPABILITIES)
ctx.effect(() => registerLocale(cx), TURNREWIND_EFFECT_LOCALE)
ctx.effect(() => registerTurnChangesCard(cx), TURNREWIND_EFFECT_TURN_TAIL)
ctx.effect(() => registerRunningChangesChip(cx), TURNREWIND_EFFECT_RUNNING_CHIP)
diff --git a/packages/dsh-tauri-turnrewind/src/client/locales/index.ts b/packages/dsh-tauri-turnrewind/src/client/locales/index.ts
index a169a5c2..628d3927 100644
--- a/packages/dsh-tauri-turnrewind/src/client/locales/index.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/locales/index.ts
@@ -45,6 +45,7 @@ const DICT_ZH = {
unsafePathReason: '目标路径上有符号链接或非空目录,出于安全考虑拒绝撤销。',
skippedOversized: '{count} 个超大文件未纳入快照,撤销不会改动它们',
skippedNestedRepos: '{count} 个嵌套仓库已跳过,撤销不会改动其内部文件',
+ openFile: '打开 {name}',
} as const satisfies Record<LocaleKey, string>
/** en 字典,与 zh 键集完全一致(locale 运行时强制双语平衡)。 */
@@ -75,6 +76,7 @@ const DICT_EN: Record<LocaleKey, string> = {
unsafePathReason: 'A symbolic link or a non-empty directory sits on the target path, so the undo was refused for safety.',
skippedOversized: '{count} oversized file(s) were not captured — undoing will not touch them',
skippedNestedRepos: '{count} nested repository/repositories skipped — undoing will not touch their contents',
+ openFile: 'Open {name}',
}
/** 活跃语言 id(module 级缓存,apply 时初始化并由订阅推进)。 */
diff --git a/packages/dsh-tauri-turnrewind/src/client/types/index.ts b/packages/dsh-tauri-turnrewind/src/client/types/index.ts
index 423ca2e5..4de37d21 100644
--- a/packages/dsh-tauri-turnrewind/src/client/types/index.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/types/index.ts
@@ -2,6 +2,10 @@
* client/types/index.ts — 客户端共享类型(宿主协议投影 + 卡片状态 + 组件 props)。
*/
+import type { FileOpener } from '../utils/open-file'
+
+export type { FileOpener } from '../utils/open-file'
+
/** 单文件变更状态:本 turn 新增 / 修改 / 删除。 */
export type TurnFileStatus = 'A' | 'M' | 'D'
@@ -94,8 +98,13 @@ export type TurnCardState
export interface TurnTailOwnerProps {
turn?: { turn?: number } | undefined
seq?: number | undefined
- /** 框架提供的文件打开入口(相对路径按会话 cwd 解析)。 */
- openFile?: ((path: string) => void) | undefined
+ /**
+ * 框架提供的文件打开入口(相对路径按会话 cwd 解析)。**两个内核都派发它,但语义不同**:
+ * `0.1.5-rc.1` 在应用内右侧边栏打开预览页签,`0.1.2-rc.1` 交给宿主/系统打开该路径。
+ * 因此本插件只在**探测到右侧边栏能力**时才调用(见 client/capabilities 与
+ * client/utils/open-file.ts),旧内核上保持静默。
+ */
+ openFile?: FileOpener | undefined
}
/** 卡片组件收到的完整 props:owner 份额 + chain `matched` + 注册 inject 份额。 */
@@ -141,3 +150,4 @@ export type LocaleKey
| 'unsafePathReason'
| 'skippedOversized'
| 'skippedNestedRepos'
+ | 'openFile'
diff --git a/packages/dsh-tauri-turnrewind/src/client/utils/open-file.test.ts b/packages/dsh-tauri-turnrewind/src/client/utils/open-file.test.ts
new file mode 100644
index 00000000..9662a596
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind/src/client/utils/open-file.test.ts
@@ -0,0 +1,63 @@
+/**
+ * client/utils/open-file.test.ts — 「点击文件打开」的决策与静默边界。
+ *
+ * 核心断言:**旧内核(无侧边栏能力)即使拿到了 `openFile` 也绝不能被调用**。
+ */
+
+import { describe, expect, it, vi } from 'vitest'
+import { fileOpenHandler } from './open-file'
+
+describe('fileOpenHandler', () => {
+ it('新内核(有侧边栏能力 + 有 openFile)→ 返回可点处理器', () => {
+ const openFile = vi.fn()
+ const handler = fileOpenHandler({ openFile, sidebarPreview: true })
+ expect(handler).toBeTypeOf('function')
+ handler?.('src/a.ts')
+ expect(openFile).toHaveBeenCalledWith('src/a.ts')
+ })
+
+ it('旧内核(有 openFile 但无侧边栏能力)→ 不可点,且**一个字节都不调用**', () => {
+ const openFile = vi.fn()
+ expect(fileOpenHandler({ openFile, sidebarPreview: false })).toBeUndefined()
+ expect(openFile).not.toHaveBeenCalled()
+ })
+
+ it('框架没派发 openFile → 不可点', () => {
+ expect(fileOpenHandler({ sidebarPreview: true })).toBeUndefined()
+ expect(fileOpenHandler({ openFile: undefined, sidebarPreview: true })).toBeUndefined()
+ })
+
+ it('openFile 不是函数(壳提供了脏字段)→ 不可点', () => {
+ expect(fileOpenHandler({ openFile: 'open' as never, sidebarPreview: true })).toBeUndefined()
+ })
+
+ it('openFile 返回 rejected promise → 静默吞掉,不产生未处理 rejection', async () => {
+ const handler = fileOpenHandler({
+ openFile: () => Promise.reject(new Error('path open failed')),
+ sidebarPreview: true,
+ })
+ expect(handler).toBeTypeOf('function')
+ handler?.('src/a.ts')
+ // 让微任务队列跑完:若有未处理 rejection,vitest 会在这里报出来。
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+
+ it('openFile 同步抛错 → 静默吞掉(卡片没有错误面,打开失败不该打断会话)', () => {
+ const handler = fileOpenHandler({
+ openFile: () => {
+ throw new Error('boom')
+ },
+ sidebarPreview: true,
+ })
+ expect(() => handler?.('src/a.ts')).not.toThrow()
+ })
+
+ it('路径原样透传(相对路径由框架按会话 cwd 解析)', () => {
+ const openFile = vi.fn()
+ const handler = fileOpenHandler({ openFile, sidebarPreview: true })
+ handler?.('packages/a/b.ts')
+ handler?.('C:\\Other\\file.txt')
+ expect(openFile.mock.calls).toEqual([['packages/a/b.ts'], ['C:\\Other\\file.txt']])
+ })
+})
diff --git a/packages/dsh-tauri-turnrewind/src/client/utils/open-file.ts b/packages/dsh-tauri-turnrewind/src/client/utils/open-file.ts
new file mode 100644
index 00000000..61ca900c
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind/src/client/utils/open-file.ts
@@ -0,0 +1,46 @@
+/**
+ * client/utils/open-file.ts — 「点击文件打开」的纯决策 + 受保护的调用。
+ *
+ * 决策规则(需求:新核心打开侧边栏的文件,旧核心静默):
+ *
+ * 1. 框架没有派发 `openFile`(旧内核之外的壳、或未来的契约变化)→ 不可点;
+ * 2. 当前内核没有应用内右侧边栏能力 → 不可点。**这一条是关键**:旧内核也派发
+ * `openFile`,但它会把路径交给宿主/系统去打开,不是我们要的行为;
+ * 3. 两条都满足才返回可用的点击处理器。
+ *
+ * 拆成纯函数是为了能直接单测「旧内核绝不打开」这条不变量(不依赖 DOM 环境)。
+ */
+
+/** 文件打开入口的框架契约(owner props 的 `openFile`)。 */
+export type FileOpener = (path: string) => void | Promise<unknown>
+
+/** 决策输入。 */
+export interface FileOpenContext {
+ /** 框架派发的 `openFile`(可能缺席)。 */
+ openFile?: FileOpener | undefined
+ /** 当前内核是否具备应用内右侧边栏预览能力(见 client/capabilities)。 */
+ sidebarPreview: boolean
+}
+
+/**
+ * 解析出可用的点击处理器;不可用时返回 `undefined`(调用方据此渲染成**不可点**的元素,
+ * 而不是渲染一个点了没反应的按钮)。
+ * @param context - 框架派发的 `openFile` 与当前内核能力。
+ * @returns 点击处理器,或 `undefined`。
+ */
+export function fileOpenHandler(context: FileOpenContext): ((path: string) => void) | undefined {
+ const { openFile, sidebarPreview } = context
+ if (!sidebarPreview || typeof openFile !== 'function')
+ return undefined
+ const open = openFile
+ return (path: string): void => {
+ // 打开文件只是便利功能:失败不影响撤销,卡片也没有错误面可挂,因此这里静默。
+ // 同时兜住同步抛错与返回 rejected promise 两种失败形态,避免未处理的 rejection。
+ try {
+ void Promise.resolve(open(path)).catch(() => undefined)
+ }
+ catch {
+ /* 同步抛错:同上,静默 */
+ }
+ }
+}