Skip to content

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

fix(turnrewind): guard unsafe workspaces and surface unavailable notices

yingtianlan3d0a59b22f5a
diff --git a/docs/TURN_REWIND.md b/docs/TURN_REWIND.md
index 068a2b25..2cc5259c 100644
--- a/docs/TURN_REWIND.md
+++ b/docs/TURN_REWIND.md
@@ -149,6 +149,8 @@ $DSH_HOME/turnrewind/
私有 Git 仓库和账本都必须位于 `$DSH_HOME`,不可写入用户项目的 Git 工作树,也不可让内部快照出现在用户当前分支中。
+> 当前原型直接把 `ledger.sqlite` 与 `snapshots/` 放在 `$DSH_HOME` 根目录(兼容已发布给早期用户的本地数据);迁移到本节的 `turnrewind/` 子布局需要一次性数据搬迁,随首个正式版本一起做。
+
### 4.2 私有 Git 快照仓库
对于每个 `workspaceKey`,插件在 `$DSH_HOME/turnrewind/snapshots/<workspace-hash>.git` 维护一个独立 Git 仓库。它只保存工作区文件快照,不改变用户项目仓库的 `HEAD`、当前分支、index、stash 或提交历史。
@@ -233,6 +235,17 @@ operation_paths(operation_id, path, expected_current_digest,
若扫描失败、被取消或有未授权路径,turn 必须标记 `reversible = false` 或 `partiallyReversible = true`,并附带明确原因。
+### 5.3 工作区资格守卫(已落地)
+
+首个原型曾对任意工作区直接建立全量基线:一位 QQ 机器人用户的会话默认工作目录是家目录(约 250 GB),首个 `git add --all` 级别的基线快照直接耗尽磁盘。OpenCode 的对照实现给出了两条可借鉴的约束:它对非 Git 工作区完全不启用快照;对 Git 工作区也只枚举 `git status` 语义下的变更路径、通过共享用户对象库(`objects/info/alternates`)和复制用户 index 白拿基线,并对未跟踪大文件设置单文件上限。
+
+在引入 OpenCode 式增量基线(见 Phase 4)之前,快照前必须先通过两层资格检查,不合格的 turn 记为 `skipped`(`reversible = 0`)并如实向用户说明原因,绝不为它建立「看似可撤销」的记录:
+
+1. **系统目录直接拒绝**:家目录本身、家目录的祖先、任何盘符根目录;
+2. **预算预扫描**(元数据遍历、超限即中止):文件数、总大小、单文件大小(与恢复读取上限一致)三重上限,`.git`/`node_modules` 等排除目录不计入;上限可通过环境变量调整。
+
+预扫描是同步、带早停的元数据遍历,只发生在 turn 领取时;即使面对 250 GB 目录,代价也是一次有界的扫描而不是全量哈希。配套提供 `purge-workspace` 维护命令,用于清掉旧版本在错误工作区上生成的快照仓库与账本记录。
+
## 6. 撤销语义
### 6.1 默认单回合 Undo
@@ -550,6 +563,8 @@ Agent 文本回复成功不是「可撤销」的判断标准;只有结算扫
### Phase 4:性能、容量与 Worktree 联动
- 大仓库索引优化、排除规则;
+- Git 仓库工作区的增量基线(参考 OpenCode:共享用户仓库 object database、按 `git status` 语义只 stage 变更路径、未跟踪大文件写入快照仓库 `info/exclude`);
+- 快照/恢复全链路异步化,避免阻塞 Host 事件循环;
- 配额与 GC;
- worktree 专用恢复域与 UI 状态;
- 诊断页和可导出审计。
diff --git a/plugins/dsh-tauri-turnrewind/README.md b/plugins/dsh-tauri-turnrewind/README.md
index 12054096..4df7e07a 100644
--- a/plugins/dsh-tauri-turnrewind/README.md
+++ b/plugins/dsh-tauri-turnrewind/README.md
@@ -9,7 +9,9 @@
这是 Host MVP 原型,当前实现:
- 为已领取的 Agent turn 建立私有 Git 快照;
-- 将快照映射记录到 `$DSH_HOME/turnrewind/ledger.sqlite`;
+- 将快照映射记录到 `$DSH_HOME/ledger.sqlite`;
+- **工作区资格守卫**:家目录、家目录的祖先、盘根目录,以及超过快照预算(文件数 / 总大小 / 单文件大小)的目录不做快照,turn 记为 `skipped` 并向 `/undo` 说明原因(见「工作区资格与快照预算」);
+- **不可用弹窗**:客户端半(`lib/client.js`)通过 `turnrewind` 会话投影检测到不可用提示时,在 Web UI 内弹出模态对话框(中英双语、每个浏览器只弹一次);
- 注册人类命令 `/undo`;
- `/undo` 只处理当前会话最新的单个可恢复 turn;
- `/undo --dry-run` 只输出预检计划,不修改文件;
@@ -57,6 +59,35 @@
父对话递归撤销、redo、消息旁 Undo 按钮和设置页模式切换尚未实现。
+## 工作区资格与快照预算
+
+快照的第一版实现会对任意工作区做全量基线,曾有用户在 QQ 机器人会话(默认工作目录是家目录、约 250 GB 内容)上触发 `git add --all` 级别的灾难。现在 turn 开始前会先做资格检查,不合格的工作区**不建快照、不产生可撤销 turn**,并在账本中记为 `skipped`(`/undo` 会显示原因)。两层检查:
+
+1. **系统目录直接拒绝**:家目录本身、家目录的祖先目录(如 `C:\Users`、`C:\`)、以及任何盘符根目录。这类目录无论多小都不做快照。
+2. **预算预扫描**(带元数据的快速遍历,超限立即中止):
+ - 文件数上限:默认 50,000(环境变量 `TURNREWIND_MAX_FILES`);
+ - 总大小上限:默认 1 GiB(环境变量 `TURNREWIND_MAX_BYTES`);
+ - 单文件上限:64 MB(与恢复读取上限一致,超限文件永远无法恢复,因此整个工作区拒绝快照);
+ - `.git`、`node_modules`、`dist`、`build`、`coverage`、`.turnrewind` 目录不计入预算。
+
+被拒绝的 turn 仍正常执行,只是不提供 undo。同时该会话会收到一条一次性提示(`[Turn rewind unavailable]`),说明工作区被拒绝的原因;每个会话只提示一次,后续 turn 不再重复打扰。提示会以两种形态呈现:
+
+1. **会话内消息**:插件来源的上下文注入消息,模型和用户都可见、可审计;
+2. **Web UI 弹窗**:宿主端 `turnrewind` 会话投影(`lib/core/dialog-projection.js`)把提示折叠进会话列表快照,客户端半(`lib/client.js`)从 `sessions.list` 的 `projectionValues.turnrewind` 读到后弹出模态对话框,按提示 id 在 `localStorage` 去重——同一浏览器每条提示只弹一次,重装/换浏览器会重弹一次。
+
+若确有合法的大工作区需要 undo,可通过环境变量放宽预算,自行承担快照耗时与磁盘占用。
+
+### 清理已膨胀的快照数据
+
+如果某个工作区在旧版本下已经生成过巨大快照,先停止 DSH Host 进程,再执行:
+
+```powershell
+node plugins\dsh-tauri-turnrewind\lib\purge-workspace.js "C:\Users\<user>" # release 数据目录 ~/.dsh
+node plugins\dsh-tauri-turnrewind\lib\purge-workspace.js "C:\Users\<user>" --home "$env:USERPROFILE\.dsh.dev" # debug
+```
+
+该命令删除该工作区对应的私有快照仓库(`$DSH_HOME/snapshots/<hash>.git`)及其全部账本记录(turns / operations / notices / workspaces),其他工作区的数据不受影响。
+
## Undo 的工作区范围
Undo 的范围是:
@@ -221,13 +252,13 @@ notice 只消费一次。下一次模型 step 后不会重复注入。
快照存放在插件私有目录:
```text
-$DSH_HOME/turnrewind/snapshots/<workspace-hash>.git
+$DSH_HOME/snapshots/<workspace-hash>.git
```
账本存放在:
```text
-$DSH_HOME/turnrewind/ledger.sqlite
+$DSH_HOME/ledger.sqlite
```
插件不会调用用户项目的:
@@ -299,7 +330,9 @@ pnpm exec vitest run plugins/dsh-tauri-turnrewind/test --testTimeout=30000
这是实验版本,正式启用前仍需要:
- 接入受控的宿主 sandbox/Tauri bridge;
-- 完成真实 DSH lifecycle integration tests;
+- 完成 DSH lifecycle integration tests;
+- 快照/扫描改为异步执行(当前 `spawnSync` 会阻塞 Host 事件循环);
+- 完善 Git 仓库工作区的增量基线(参考 OpenCode:共享用户对象库 + 仅 stage 变更路径);
- 完善多 workspace 并发锁;
- 实现父对话递归 undo;
- 实现 redo 和冲突处理 UI;
diff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.js
new file mode 100644
index 00000000..58898675
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/client.js
@@ -0,0 +1,185 @@
+// Client half of dsh-tauri-turnrewind: raises an in-app dialog when the
+// current session carries an unsupported-workspace heads-up from the host.
+// Hand-wrapped in the dsh client ModuleLoader format (no build step): the web
+// app evaluates this file and registers the module under the plugin name.
+if (globalThis.__ModuleLoader__) {
+ globalThis.__ModuleLoader__.load({ id: 'dsh-tauri-turnrewind', factory: () => {
+ const module = { exports: {} }
+ const exports = module.exports
+
+ const inject = ['sessions', 'locale']
+
+ const NS = 'dsh-tauri-turnrewind'
+ const SEEN_KEY = 'turnrewind.seenUnsupportedNotices'
+ const MAX_SEEN = 100
+
+ const dictionaries = {
+ zh: {
+ title: '撤销功能在此工作区不可用',
+ intro: '当前会话的工作区不支持文件撤销。对话照常运行,但本工作区内的文件改动无法用 /undo 撤销。',
+ reason: '原因',
+ ok: '知道了',
+ },
+ en: {
+ title: 'Undo is unavailable in this workspace',
+ intro: 'File undo is disabled for this session\'s workspace. Turns still run normally, but changes in this workspace cannot be reverted with /undo.',
+ reason: 'Reason',
+ ok: 'Got it',
+ },
+ }
+
+ function readSeen() {
+ try {
+ const raw = globalThis.localStorage.getItem(SEEN_KEY)
+ const list = raw ? JSON.parse(raw) : []
+ return Array.isArray(list) ? list : []
+ }
+ catch {
+ return []
+ }
+ }
+
+ function markSeen(id) {
+ try {
+ const seen = readSeen().filter(entry => entry !== id)
+ seen.push(id)
+ globalThis.localStorage.setItem(SEEN_KEY, JSON.stringify(seen.slice(-MAX_SEEN)))
+ }
+ catch {
+ // Storage may be unavailable; the dialog just re-shows next reload.
+ }
+ }
+
+ let dialog
+
+ function palette() {
+ const dark = globalThis.matchMedia?.('(prefers-color-scheme: dark)')?.matches ?? false
+ return dark
+ ? { card: '#1f2937', text: '#f9fafb', muted: '#9ca3af', box: '#111827', boxBorder: '#374151', backdrop: 'rgba(2, 6, 23, 0.6)', button: '#6366f1', buttonText: '#ffffff' }
+ : { card: '#ffffff', text: '#111827', muted: '#6b7280', box: '#f3f4f6', boxBorder: '#e5e7eb', backdrop: 'rgba(15, 23, 42, 0.45)', button: '#4f46e5', buttonText: '#ffffff' }
+ }
+
+ function ensureDialog() {
+ if (dialog)
+ return dialog
+ const colors = palette()
+ const backdrop = document.createElement('div')
+ backdrop.setAttribute('role', 'presentation')
+ Object.assign(backdrop.style, {
+ display: 'none',
+ position: 'fixed',
+ inset: '0',
+ zIndex: '2147483000',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: colors.backdrop,
+ })
+
+ const card = document.createElement('div')
+ card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
+ Object.assign(card.style, {
+ maxWidth: '440px',
+ width: 'calc(100vw - 48px)',
+ boxSizing: 'border-box',
+ background: colors.card,
+ color: colors.text,
+ borderRadius: '12px',
+ padding: '20px 22px',
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ lineHeight: '1.6',
+ boxShadow: '0 20px 50px rgba(0, 0, 0, 0.3)',
+ })
+
+ const title = document.createElement('div')
+ Object.assign(title.style, { fontSize: '15px', fontWeight: '600', marginBottom: '10px' })
+
+ const intro = document.createElement('div')
+
+ const reasonLabel = document.createElement('div')
+ Object.assign(reasonLabel.style, { marginTop: '12px', color: colors.muted, fontSize: '12px' })
+
+ const reasonBox = document.createElement('div')
+ Object.assign(reasonBox.style, {
+ marginTop: '6px',
+ padding: '8px 10px',
+ borderRadius: '8px',
+ background: colors.box,
+ border: `1px solid ${colors.boxBorder}`,
+ wordBreak: 'break-all',
+ whiteSpace: 'pre-wrap',
+ maxHeight: '160px',
+ overflowY: 'auto',
+ })
+
+ const actions = document.createElement('div')
+ Object.assign(actions.style, { marginTop: '16px', textAlign: 'right' })
+ const button = document.createElement('button')
+ button.type = 'button'
+ Object.assign(button.style, {
+ background: colors.button,
+ color: colors.buttonText,
+ border: 'none',
+ borderRadius: '8px',
+ padding: '6px 18px',
+ fontSize: '13px',
+ cursor: 'pointer',
+ })
+ actions.appendChild(button)
+
+ card.append(title, intro, reasonLabel, reasonBox, actions)
+ backdrop.appendChild(card)
+ document.body.appendChild(backdrop)
+
+ function hide() {
+ backdrop.style.display = 'none'
+ }
+ button.addEventListener('click', hide)
+ backdrop.addEventListener('click', (event) => {
+ if (event.target === backdrop)
+ hide()
+ })
+
+ dialog = { backdrop, title, intro, reasonLabel, reasonBox, button }
+ return dialog
+ }
+
+ function showDialog(t, notices) {
+ const el = ensureDialog()
+ el.title.textContent = t('title')
+ el.intro.textContent = t('intro')
+ el.reasonLabel.textContent = t('reason')
+ el.reasonBox.textContent = notices.map(notice => notice.reason || notice.id).join('\n')
+ el.button.textContent = t('ok')
+ el.backdrop.style.display = 'flex'
+ }
+
+ function apply(ctx) {
+ ctx.effect(() => ctx.locale.register(NS, dictionaries), 'turnrewind locale')
+ const t = ctx.locale.bind(NS)
+ // Read through the service store, not the ctx.sessions property proxy:
+ // the host session service merges a different member under the same name.
+ const sessions = ctx.get('sessions')
+ ctx.effect(() => {
+ const unsubscribe = sessions.list.subscribe(() => {
+ const state = sessions.list.getSnapshot()
+ const summary = state.current !== undefined ? state.byId[state.current] : undefined
+ const value = summary?.projectionValues?.turnrewind
+ const notices = Array.isArray(value?.notices) ? value.notices : []
+ const fresh = notices.filter(notice => notice && typeof notice.id === 'string' && !readSeen().includes(notice.id))
+ if (fresh.length === 0)
+ return
+ for (const notice of fresh) markSeen(notice.id)
+ showDialog(t, fresh)
+ })
+ return () => {
+ unsubscribe()
+ }
+ }, 'turnrewind dialog runner')
+ }
+
+ Object.assign(exports, { apply, inject })
+ return module.exports
+ } })
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js b/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js
new file mode 100644
index 00000000..9e4217f4
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/core/dialog-projection.js
@@ -0,0 +1,61 @@
+/**
+ * The `turnrewind` session projection: folds the session log and surfaces the
+ * unsupported-workspace heads-up messages this plugin injected, so the client
+ * half can raise a dialog from the session list snapshot it already receives.
+ * Pure and unit-tested; registration is the only effect in index.js.
+ */
+
+export const UNSUPPORTED_MARKER = '[Turn rewind unavailable]'
+
+const MAX_TRACKED_NOTICES = 20
+
+/**
+ * Extract the dialog payload from one committed session event.
+ * Matches the injected message by plugin source first, falling back to the
+ * text marker in case a host version drops the source field.
+ */
+export function extractUnsupportedNotice(event) {
+ if (event?.type !== 'user/message')
+ return undefined
+ const message = event.data
+ const text = Array.isArray(message?.content)
+ ? message.content.find(part => part?.type === 'text')?.text
+ : undefined
+ const source = message?.source
+ const matched = (source?.plugin === 'dsh-tauri-turnrewind' && source?.form === 'undo-unavailable-notice')
+ || (typeof text === 'string' && text.startsWith(UNSUPPORTED_MARKER))
+ if (!matched || typeof message?.id !== 'string')
+ return undefined
+ const reason = typeof text === 'string' ? /^Reason: (.+)$/mu.exec(text)?.[1] : undefined
+ return { id: message.id, reason: reason ?? '' }
+}
+
+function parseNoticesValue(value) {
+ if (typeof value !== 'object' || value === null || !Array.isArray(value.notices))
+ throw new Error('TURNREWIND_PROJECTION_SHAPE: expected { notices: Array<{ id, reason }> }')
+ return value
+}
+
+/**
+ * Build the `turnrewind` projection unit. Registered on
+ * `ctx.sessionProjections`; the registry requires `.parse` validators (zod in
+ * other plugins) — hand-rolled ones keep this plugin dependency-free.
+ */
+export function createDialogProjection() {
+ return {
+ key: 'turnrewind',
+ stateVersion: 1,
+ stateSchema: { parse: parseNoticesValue },
+ init: () => ({ notices: [] }),
+ apply(state, event) {
+ const notice = extractUnsupportedNotice(event)
+ if (!notice || state.notices.some(existing => existing.id === notice.id))
+ return state
+ return { notices: [...state.notices, notice].slice(-MAX_TRACKED_NOTICES) }
+ },
+ wire: {
+ viewSchema: { parse: parseNoticesValue },
+ view: state => ({ notices: state.notices }),
+ },
+ }
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/guard.js b/plugins/dsh-tauri-turnrewind/lib/core/guard.js
new file mode 100644
index 00000000..961459e1
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/core/guard.js
@@ -0,0 +1,141 @@
+import { lstatSync, readdirSync, realpathSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join, parse, relative, resolve, sep } from 'node:path'
+import process from 'node:process'
+import { MAX_FILE_BYTES } from './git-snapshot.js'
+
+const DEFAULT_MAX_FILES = 50_000
+const DEFAULT_MAX_TOTAL_BYTES = 1024 ** 3
+
+// Mirror the directory part of the snapshot excludes so the guard measures what
+// `git add` would actually ingest instead of the raw tree.
+const SKIP_DIR_NAMES = new Set(['.git', 'node_modules', 'dist', 'build', 'coverage', '.turnrewind'])
+
+const OVERSIZED_SAMPLE_LIMIT = 5
+
+function envCount(name, fallback) {
+ const raw = process.env[name]
+ if (!raw)
+ return fallback
+ const value = Number(raw)
+ return Number.isInteger(value) && value > 0 ? value : fallback
+}
+
+function normalizeDir(path) {
+ const resolved = resolve(path)
+ try {
+ return realpathSync(resolved)
+ }
+ catch {
+ // Missing or unreadable paths still need a deterministic comparison key.
+ return resolved
+ }
+}
+
+function foldCase(path) {
+ return process.platform === 'win32' ? path.toLowerCase() : path
+}
+
+export function defaultBudget() {
+ return {
+ maxFiles: envCount('TURNREWIND_MAX_FILES', DEFAULT_MAX_FILES),
+ maxTotalBytes: envCount('TURNREWIND_MAX_BYTES', DEFAULT_MAX_TOTAL_BYTES),
+ maxFileBytes: MAX_FILE_BYTES,
+ }
+}
+
+export function isSystemSensitiveWorkspace(workspaceDir) {
+ const workspace = foldCase(normalizeDir(workspaceDir))
+ const home = foldCase(normalizeDir(homedir()))
+ if (workspace === home)
+ return true
+ // An ancestor of the home directory would snapshot every user profile
+ // including the DSH data dir itself, so refuse it alongside the home dir.
+ if (home.startsWith(`${workspace}${sep}`))
+ return true
+ return parse(workspace).root === workspace
+}
+
+class BudgetAbort extends Error {}
+
+/**
+ * Metadata-only walk that aborts as soon as a budget is exceeded, so even a
+ * 250 GB home directory costs at most one bounded scan instead of a full
+ * `git add` baseline.
+ */
+export function scanWithinBudget(workspaceDir, budget = defaultBudget()) {
+ const root = resolve(workspaceDir)
+ const state = { files: 0, bytes: 0, oversized: [] }
+
+ const visit = (dir) => {
+ let entries
+ try {
+ entries = readdirSync(dir, { withFileTypes: true })
+ }
+ catch {
+ // Subtrees that cannot be listed are equally unusable for snapshots.
+ return
+ }
+ for (const entry of entries) {
+ if (entry.isDirectory()) {
+ if (!SKIP_DIR_NAMES.has(entry.name))
+ visit(join(dir, entry.name))
+ continue
+ }
+ // Symlinks and junctions are never followed, mirroring restorePath.
+ if (!entry.isFile())
+ continue
+ const path = join(dir, entry.name)
+ const info = lstatSync(path, { throwIfNoEntry: false })
+ if (!info)
+ continue
+ state.files += 1
+ state.bytes += info.size
+ if (info.size > budget.maxFileBytes && state.oversized.length < OVERSIZED_SAMPLE_LIMIT)
+ state.oversized.push(relative(root, path))
+ if (state.files > budget.maxFiles || state.bytes > budget.maxTotalBytes)
+ throw new BudgetAbort()
+ }
+ }
+
+ try {
+ visit(root)
+ }
+ catch (error) {
+ if (!(error instanceof BudgetAbort))
+ throw error
+ }
+
+ const reason = state.files > budget.maxFiles
+ ? `file count ${state.files} exceeds the limit ${budget.maxFiles}`
+ : state.bytes > budget.maxTotalBytes
+ ? `total size ${state.bytes} bytes exceeds the limit ${budget.maxTotalBytes}`
+ : state.oversized.length > 0
+ ? `files larger than ${budget.maxFileBytes} bytes can never be restored: ${state.oversized.join(', ')}`
+ : undefined
+ return {
+ files: state.files,
+ bytes: state.bytes,
+ oversized: state.oversized,
+ ok: reason === undefined,
+ reason,
+ }
+}
+
+export function assessWorkspace(workspaceDir) {
+ const workspace = resolve(workspaceDir)
+ if (isSystemSensitiveWorkspace(workspace)) {
+ return {
+ eligible: false,
+ reason: `TURNREWIND_WORKSPACE_UNSUPPORTED: ${workspace} is a system directory (the home directory, one of its ancestors, or a drive root)`,
+ }
+ }
+ const scan = scanWithinBudget(workspace)
+ if (!scan.ok) {
+ return {
+ eligible: false,
+ reason: `TURNREWIND_WORKSPACE_TOO_LARGE: ${workspace} exceeds the snapshot budget (${scan.reason})`,
+ }
+ }
+ return { eligible: true, files: scan.files, bytes: scan.bytes }
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
index 843be977..34cfa4e0 100644
--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js
@@ -1,3 +1,4 @@
+import { randomUUID } from 'node:crypto'
import { mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { DatabaseSync } from 'node:sqlite'
@@ -43,6 +44,8 @@ const SCHEMA = `
target_turn_id TEXT NOT NULL,
turns_json TEXT NOT NULL DEFAULT '[]',
paths_json TEXT NOT NULL,
+ kind TEXT NOT NULL DEFAULT 'rewind',
+ reason TEXT,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
claimed_at TEXT
@@ -68,6 +71,18 @@ export function openLedger(rootDir) {
catch {
// Column already exists.
}
+ try {
+ db.exec('ALTER TABLE rewind_notices ADD COLUMN kind TEXT NOT NULL DEFAULT \'rewind\'')
+ }
+ catch {
+ // Column already exists.
+ }
+ try {
+ db.exec('ALTER TABLE rewind_notices ADD COLUMN reason TEXT')
+ }
+ catch {
+ // Column already exists.
+ }
db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)
return db
}
@@ -102,6 +117,31 @@ export function settleNoopTurn(db, turnId, afterRef) {
.run(new Date().toISOString(), afterRef, 'no file changes', turnId)
}
+export function recordSkippedTurn(db, turn, reason) {
+ db.exec('BEGIN')
+ try {
+ db.prepare(`
+ INSERT OR REPLACE INTO turns(turn_id, session_id, parent_turn_id, workspace_key, status, started_at, reversible, error)
+ VALUES (?, ?, NULL, ?, 'skipped', ?, 0, ?)
+ `).run(turn.turnId, turn.sessionId, turn.workspaceKey, turn.startedAt, reason)
+ // Queue one heads-up per session and workspace; repeated skips stay silent.
+ const existing = db.prepare(`
+ SELECT 1 FROM rewind_notices WHERE session_id = ? AND workspace_key = ? AND kind = 'unsupported' LIMIT 1
+ `).get(turn.sessionId, turn.workspaceKey)
+ if (!existing) {
+ db.prepare(`
+ INSERT INTO rewind_notices(notice_id, session_id, workspace_key, target_turn_id, turns_json, paths_json, kind, reason, status, created_at)
+ VALUES (?, ?, ?, 'workspace-unsupported', '[]', '[]', 'unsupported', ?, 'pending', ?)
+ `).run(randomUUID(), turn.sessionId, turn.workspaceKey, reason, new Date().toISOString())
+ }
+ db.exec('COMMIT')
+ }
+ catch (error) {
+ db.exec('ROLLBACK')
+ throw error
+ }
+}
+
export function failTurn(db, turnId, error) {
db.prepare(`UPDATE turns SET status = 'failed', settled_at = ?, reversible = 0, error = ? WHERE turn_id = ?`)
.run(new Date().toISOString(), String(error), turnId)
diff --git a/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js b/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
new file mode 100644
index 00000000..25116d68
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/core/maintenance.js
@@ -0,0 +1,50 @@
+import { existsSync, rmSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join, resolve } from 'node:path'
+import process from 'node:process'
+import { workspaceHash } from './git-snapshot.js'
+import { openLedger } from './ledger.js'
+
+export function resolveRootDir(explicit) {
+ if (explicit)
+ return resolve(explicit)
+ return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
+}
+
+/**
+ * Remove every piece of turnrewind data bound to one workspace: the private
+ * snapshot repository on disk and all ledger rows that reference it. Used to
+ * recover from workspaces that were snapshotted before the eligibility guard
+ * existed (for example a 250 GB home directory).
+ */
+export function purgeWorkspace(rootDir, workspaceDir) {
+ const workspaceKey = resolve(workspaceDir).toLowerCase()
+ const repoDir = join(rootDir, 'snapshots', `${workspaceHash(workspaceDir)}.git`)
+ const summary = { rootDir, repoDir, repoExisted: false, ledger: undefined }
+
+ const ledgerPath = join(rootDir, 'ledger.sqlite')
+ if (existsSync(ledgerPath)) {
+ const db = openLedger(rootDir)
+ try {
+ db.exec('BEGIN')
+ const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceKey)
+ const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceKey)
+ const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceKey)
+ const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceKey)
+ db.exec('COMMIT')
+ summary.ledger = {
+ operations: operations.changes,
+ notices: notices.changes,
+ turns: turns.changes,
+ workspaces: workspaces.changes,
+ }
+ }
+ finally {
+ db.close()
+ }
+ }
+
+ summary.repoExisted = existsSync(repoDir)
+ rmSync(repoDir, { recursive: true, force: true })
+ return summary
+}
diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.js
index d34fbaa4..0bf7a19b 100644
--- a/plugins/dsh-tauri-turnrewind/lib/index.js
+++ b/plugins/dsh-tauri-turnrewind/lib/index.js
@@ -2,12 +2,14 @@ import { randomUUID } from 'node:crypto'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import process from 'node:process'
+import { createDialogProjection } from './core/dialog-projection.js'
import { captureSnapshot, createSnapshotStore, currentState, restorePath, snapshotDiff, stateAt } from './core/git-snapshot.js'
-import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'
+import { assessWorkspace } from './core/guard.js'
+import { claimRewindNotices, completeUndoWithNotice, createOperation, failTurn, getLatestSnapshotRef, getLatestTurn, getLatestTurnSummary, getTurn, insertTurn, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn } from './core/ledger.js'
import { classifyUndo } from './core/planner.js'
const name = 'dsh-tauri-turnrewind'
-const inject = ['commands']
+const inject = ['commands', 'sessionProjections']
const ROOT_DIR = process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')
const TURN_ID_RE = /[^\w.-]/gu
@@ -28,6 +30,11 @@ function workspaceKeyFor(path) {
return path.toLowerCase()
}
+function workspaceIssue(workspaceDir) {
+ const assessment = assessWorkspace(workspaceDir)
+ return assessment.eligible ? undefined : assessment.reason
+}
+
function activeKey(sessionId, turn) {
return `${sessionId}:${turn}`
}
@@ -83,6 +90,27 @@ function createRewindNoticeMessage(notice) {
}
}
+function createUnsupportedNoticeMessage(notice) {
+ const text = `[Turn rewind unavailable]\nUndo is disabled for this workspace.\nReason: ${notice.reason}\n\nTurns here still run normally, but their file changes are not recorded, so /undo cannot revert them. Move this session to a normal project directory if you want undoable turns.`
+ return {
+ id: `turnrewind-notice-${notice.notice_id}`,
+ role: 'user',
+ content: [{ type: 'text', text }],
+ source: {
+ kind: 'plugin',
+ plugin: name,
+ form: 'undo-unavailable-notice',
+ sections: [{ name, text }],
+ },
+ }
+}
+
+function createNoticeMessage(notice) {
+ return notice.kind === 'unsupported'
+ ? createUnsupportedNoticeMessage(notice)
+ : createRewindNoticeMessage(notice)
+}
+
function workspaceHasActiveTurn(active, workspaceKey) {
for (const entry of active.values()) {
if (entry.workspaceKey === workspaceKey)
@@ -228,6 +256,9 @@ function apply(ctx) {
const active = new Map()
const workspaceStores = new Map()
const commands = ctx.commands
+ // Client-visible projection: lets the web UI raise the unavailable-dialog
+ // from the session list it already receives, no conversation API needed.
+ ctx.effect(() => ctx.sessionProjections.register(createDialogProjection()), 'turnrewind projection')
function ensureRuntime(agent) {
const workspaceDir = workspaceForAgent(agent)
@@ -263,16 +294,37 @@ function apply(ctx) {
return decision
return {
...decision,
- messages: [...decision.messages, ...notices.map(createRewindNoticeMessage)],
+ messages: [...decision.messages, ...notices.map(createNoticeMessage)],
}
})
ctx.on('agent/inbox/claimed', (payload) => {
+ const sessionId = payload.agent.session.id
+ const key = activeKey(sessionId, payload.turn)
+ const workspaceDir = workspaceForAgent(payload.agent)
+ if (!workspaceDir)
+ return
+ const issue = workspaceIssue(workspaceDir)
+ if (issue) {
+ // Record the refusal and queue a one-time heads-up so the user sees why
+ // this turn will not be undoable instead of discovering it via /undo.
+ try {
+ recordSkippedTurn(ledger, {
+ turnId: key,
+ sessionId,
+ workspaceKey: workspaceKeyFor(workspaceDir),
+ startedAt: new Date().toISOString(),
+ }, issue)
+ }
+ catch (error) {
+ console.error(`turnrewind: failed to record skipped turn ${key}: ${String(error)}`)
+ }
+ console.error(`turnrewind: skipped turn ${key}: ${issue}`)
+ return
+ }
const runtime = ensureRuntime(payload.agent)
if (!runtime)
return
- const sessionId = payload.agent.session.id
- const key = activeKey(sessionId, payload.turn)
if (runtime.undoing) {
console.error(`turnrewind: skipped turn ${key} while an undo is running`)
return
@@ -335,6 +387,12 @@ function apply(ctx) {
description: 'Plan or undo file changes made by the latest Agent turn',
input: { hint: '[turn-id] [--dry-run]' },
handler: (invocation) => {
+ const workspaceDir = workspaceForAgent(invocation.agent)
+ if (!workspaceDir)
+ return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
+ 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 this session has no workspace.' }
diff --git a/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js b/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js
new file mode 100644
index 00000000..c7fde4c2
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/lib/purge-workspace.js
@@ -0,0 +1,40 @@
+import process from 'node:process'
+import { purgeWorkspace, resolveRootDir } from './core/maintenance.js'
+
+function usage() {
+ console.error('Usage: node purge-workspace.js <workspace-dir> [--home <dsh-home>]')
+ console.error('')
+ console.error('Removes the turnrewind snapshot repository and all ledger rows bound to')
+ console.error('one workspace. Stop the DSH host process before running this command.')
+ console.error('Defaults to the release data home (~/.dsh); pass --home or set DSH_HOME')
+ console.error('to target the debug home (~/.dsh.dev).')
+}
+
+function main() {
+ const args = process.argv.slice(2)
+ const positional = []
+ let home
+ for (let index = 0; index < args.length; index += 1) {
+ if (args[index] === '--home') {
+ home = args[index + 1]
+ index += 1
+ continue
+ }
+ positional.push(args[index])
+ }
+ if (positional.length !== 1) {
+ usage()
+ process.exit(1)
+ }
+
+ const rootDir = resolveRootDir(home)
+ const summary = purgeWorkspace(rootDir, positional[0])
+ console.error(`turnrewind root: ${summary.rootDir}`)
+ console.error(`snapshot repo: ${summary.repoDir} (${summary.repoExisted ? 'removed' : 'not found'})`)
+ if (summary.ledger)
+ console.error(`ledger rows removed: ${JSON.stringify(summary.ledger)}`)
+ else
+ console.error('ledger: not found, nothing to purge')
+}
+
+main()
diff --git a/plugins/dsh-tauri-turnrewind/package.json b/plugins/dsh-tauri-turnrewind/package.json
index 37df4034..b248eba3 100644
--- a/plugins/dsh-tauri-turnrewind/package.json
+++ b/plugins/dsh-tauri-turnrewind/package.json
@@ -1,14 +1,26 @@
{
"name": "dsh-tauri-turnrewind",
"type": "module",
- "version": "0.1.0-dev.1",
+ "version": "0.1.0-dev.3",
"description": "Local turn-aware workspace undo for DeepSeek Harness",
+ "exports": {
+ ".": "./lib/index.js",
+ "./client": "./lib/client.js",
+ "./package.json": "./package.json"
+ },
"main": "lib/index.js",
"files": ["README.md", "cordis.patch.yml", "lib"],
"dsh": {
"runtime": "host",
"bundle": {
"patch": "./cordis.patch.yml"
+ },
+ "client": {
+ "platform": "web",
+ "inject": [
+ "@deepseek-ai/dsh-client-runtime",
+ "@deepseek-ai/dsh-client-locale"
+ ]
}
},
"engines": {
diff --git a/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js b/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js
new file mode 100644
index 00000000..0ceb83eb
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/test/dialog-projection.test.js
@@ -0,0 +1,50 @@
+import assert from 'node:assert/strict'
+import { it } from 'vitest'
+import { createDialogProjection, extractUnsupportedNotice } from '../lib/core/dialog-projection.js'
+
+function unsupportedEvent(id, reason, withSource = true) {
+ const text = `[Turn rewind unavailable]\nUndo is disabled for this workspace.\nReason: ${reason}\n\nTurns here still run normally.`
+ const message = { id, role: 'user', content: [{ type: 'text', text }] }
+ if (withSource)
+ message.source = { kind: 'plugin', plugin: 'dsh-tauri-turnrewind', form: 'undo-unavailable-notice', sections: [] }
+ return { type: 'user/message', seq: 1, data: message }
+}
+
+it('extracts unsupported notices from plugin messages with and without source', () => {
+ const withSource = extractUnsupportedNotice(unsupportedEvent('turnrewind-notice-a', 'TURNREWIND_WORKSPACE_UNSUPPORTED: home'))
+ assert.deepEqual(withSource, { id: 'turnrewind-notice-a', reason: 'TURNREWIND_WORKSPACE_UNSUPPORTED: home' })
+ const byText = extractUnsupportedNotice(unsupportedEvent('turnrewind-notice-b', 'TURNREWIND_WORKSPACE_TOO_LARGE: budget', false))
+ assert.deepEqual(byText, { id: 'turnrewind-notice-b', reason: 'TURNREWIND_WORKSPACE_TOO_LARGE: budget' })
+})
+
+it('ignores unrelated session events', () => {
+ assert.equal(extractUnsupportedNotice({ type: 'turn/start', data: { turn: 1 } }), undefined)
+ assert.equal(extractUnsupportedNotice({
+ type: 'user/message',
+ data: { id: 'plain', role: 'user', content: [{ type: 'text', text: '你好' }] },
+ }), undefined)
+ assert.equal(extractUnsupportedNotice(undefined), undefined)
+})
+
+it('folds notices into the view, dedupes by id, and caps the list', () => {
+ const projection = createDialogProjection()
+ let state = projection.init()
+ state = projection.apply(state, unsupportedEvent('notice-1', 'r1'))
+ assert.equal(projection.wire.view(state).notices.length, 1)
+ const unchanged = state
+ state = projection.apply(state, unsupportedEvent('notice-1', 'r1'))
+ assert.equal(state, unchanged)
+ for (let index = 2; index <= 25; index += 1)
+ state = projection.apply(state, unsupportedEvent(`notice-${index}`, `r${index}`))
+ const view = projection.wire.view(state)
+ assert.equal(view.notices.length, 20)
+ assert.equal(view.notices.at(-1).id, 'notice-25')
+ assert.equal(view.notices[0].id, 'notice-6')
+})
+
+it('validates persisted state through the schema face', () => {
+ const projection = createDialogProjection()
+ assert.deepEqual(projection.stateSchema.parse({ notices: [] }), { notices: [] })
+ assert.throws(() => projection.stateSchema.parse({ broken: true }), /TURNREWIND_PROJECTION_SHAPE/)
+ assert.throws(() => projection.wire.viewSchema.parse(null), /TURNREWIND_PROJECTION_SHAPE/)
+})
diff --git a/plugins/dsh-tauri-turnrewind/test/guard.test.js b/plugins/dsh-tauri-turnrewind/test/guard.test.js
new file mode 100644
index 00000000..d77111ad
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/test/guard.test.js
@@ -0,0 +1,111 @@
+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 'node:path'
+import { afterEach, it } from 'vitest'
+import { assessWorkspace, isSystemSensitiveWorkspace, scanWithinBudget } from '../lib/core/guard.js'
+
+const LARGE_BUDGET = { maxFiles: 50_000, maxTotalBytes: 1024 ** 3, maxFileBytes: 64 * 1024 * 1024 }
+
+afterEach(() => {
+ delete process.env.TURNREWIND_MAX_FILES
+ delete process.env.TURNREWIND_MAX_BYTES
+})
+
+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('accepts an ordinary small workspace', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-ok-'))
+ try {
+ await writeFile(join(root, 'a.txt'), 'a')
+ await mkdir(join(root, 'nested'), { recursive: true })
+ await writeFile(join(root, 'nested', 'b.txt'), 'b')
+ const assessment = assessWorkspace(root)
+ assert.equal(assessment.eligible, true)
+ assert.equal(assessment.files, 2)
+ assert.equal(assessment.bytes, 2)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('refuses workspaces over the file-count budget', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-files-'))
+ try {
+ await mkdir(join(root, 'd'), { recursive: true })
+ for (let index = 0; index < 5; index += 1)
+ await writeFile(join(root, 'd', `f${index}.txt`), 'x')
+ const scan = scanWithinBudget(root, { ...LARGE_BUDGET, maxFiles: 3 })
+ assert.equal(scan.ok, false)
+ assert.match(scan.reason, /file count/)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('refuses workspaces over the total-size budget', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-bytes-'))
+ try {
+ await writeFile(join(root, 'big.bin'), '0123456789'.repeat(10))
+ const scan = scanWithinBudget(root, { ...LARGE_BUDGET, maxTotalBytes: 50 })
+ assert.equal(scan.ok, false)
+ assert.match(scan.reason, /total size/)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('refuses files that could never be restored', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-big-'))
+ try {
+ await writeFile(join(root, 'huge.bin'), '0123456789ABCDEF')
+ const scan = scanWithinBudget(root, { ...LARGE_BUDGET, maxFileBytes: 10 })
+ assert.equal(scan.ok, false)
+ assert.match(scan.reason, /larger than 10 bytes/)
+ assert.deepEqual(scan.oversized, ['huge.bin'])
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('ignores excluded directories when measuring the budget', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-skip-'))
+ try {
+ await mkdir(join(root, 'node_modules', 'pkg'), { recursive: true })
+ await mkdir(join(root, '.git'), { recursive: true })
+ for (let index = 0; index < 10; index += 1) {
+ await writeFile(join(root, 'node_modules', 'pkg', `f${index}.txt`), 'x')
+ await writeFile(join(root, '.git', `obj${index}`), 'x')
+ }
+ const scan = scanWithinBudget(root, { ...LARGE_BUDGET, maxFiles: 5 })
+ assert.equal(scan.ok, true)
+ assert.equal(scan.files, 0)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+it('honors TURNREWIND_MAX_FILES via assessWorkspace', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-guard-env-'))
+ try {
+ for (let index = 0; index < 3; index += 1)
+ await writeFile(join(root, `f${index}.txt`), 'x')
+ process.env.TURNREWIND_MAX_FILES = '2'
+ const assessment = assessWorkspace(root)
+ assert.equal(assessment.eligible, false)
+ assert.match(assessment.reason, /TURNREWIND_WORKSPACE_TOO_LARGE/)
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
diff --git a/plugins/dsh-tauri-turnrewind/test/ledger.test.js b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
index 8eda46ce..c8f59e46 100644
--- a/plugins/dsh-tauri-turnrewind/test/ledger.test.js
+++ b/plugins/dsh-tauri-turnrewind/test/ledger.test.js
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { it } from 'vitest'
-import { claimRewindNotices, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, settleInterruptedTurn, settleNoopTurn, settleTurn } from '../lib/core/ledger.js'
+import { claimRewindNotices, completeUndoWithNotice, getLatestSnapshotRef, getLatestTurn, getTurn, insertTurn, openLedger, queueRewindNotice, recordSkippedTurn, settleInterruptedTurn, settleNoopTurn, settleTurn } from '../lib/core/ledger.js'
it('persists turn lifecycle and resumes from the latest durable snapshot', async () => {
const root = await mkdtemp(join(tmpdir(), 'turnrewind-ledger-test-'))
@@ -102,6 +102,33 @@ it('merges multiple pending rewind notices and delivers them once', async () =>
}
})
+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)
diff --git a/plugins/dsh-tauri-turnrewind/test/maintenance.test.js b/plugins/dsh-tauri-turnrewind/test/maintenance.test.js
new file mode 100644
index 00000000..7e378589
--- /dev/null
+++ b/plugins/dsh-tauri-turnrewind/test/maintenance.test.js
@@ -0,0 +1,69 @@
+import assert from 'node:assert/strict'
+import { existsSync } from 'node:fs'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { it } from 'vitest'
+import { workspaceHash } from '../lib/core/git-snapshot.js'
+import { createOperation, getTurn, insertTurn, openLedger, queueRewindNotice, registerWorkspace, settleTurn } from '../lib/core/ledger.js'
+import { purgeWorkspace } from '../lib/core/maintenance.js'
+
+it('purges ledger rows and the snapshot repository for one workspace', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'turnrewind-purge-test-'))
+ const workspace = join(root, 'ws')
+ const workspaceKey = resolve(workspace).toLowerCase()
+ try {
+ const db = openLedger(root)
+ registerWorkspace(db, workspaceKey, workspace, join(root, 'snapshots', 'x.git'))
+ insertTurn(db, {
+ turnId: 'session:1',
+ sessionId: 'session',
+ workspaceKey,
+ startedAt: '2026-01-01T00:00:00.000Z',
+ beforeRef: 'refs/turnrewind/turn-session-1-before',
+ })
+ settleTurn(db, 'session:1', 'refs/turnrewind/turn-session-1-after')
+ createOperation(db, {
+ operationId: 'op-1',
+ kind: 'undo',
+ targetTurnId: 'session:1',
+ requestedAt: '2026-01-01T00:01:00.000Z',
+ })
+ queueRewindNotice(db, {
+ noticeId: 'notice-1',
+ sessionId: 'session',
+ workspaceKey,
+ targetTurnId: 'session:1',
+ paths: ['a.txt'],
+ createdAt: '2026-01-01T00:01:00.000Z',
+ })
+ db.close()
+
+ const repoDir = join(root, 'snapshots', `${workspaceHash(workspace)}.git`)
+ await mkdir(join(repoDir, 'objects'), { recursive: true })
+ await writeFile(join(repoDir, 'HEAD'), 'ref: refs/heads/main\n')
+
+ const summary = purgeWorkspace(root, workspace)
+ assert.equal(summary.repoExisted, true)
+ assert.deepEqual(summary.ledger, { operations: 1, notices: 1, 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, turns: 0, workspaces: 0 })
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})