Skip to content

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

feat(turnrewind): /undo --doctor read-only diagnostics

yingtianland5471b78c104
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
index 7174992f..9da36dcb 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
@@ -20,6 +20,7 @@ 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,
@@ -54,7 +55,7 @@ import {
import { purgeWorkspace } from './service/maintenance'
import { planDrift } from './service/planner'
import { enforceRetention } from './service/retention'
-import { applyUndo, buildPlanEntries, executeUndoRestore, turnRefsExist, workspaceForAgent, workspaceHasActiveTurn, workspaceIssue, workspaceKeyFor } from './service/undo'
+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 一致)。 */
@@ -739,8 +740,13 @@ export function apply(ctx: HostApplyContext): void {
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]' },
+ 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.
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts
new file mode 100644
index 00000000..64ff9afe
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/doctor.ts
@@ -0,0 +1,125 @@
+/**
+ * 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.join('\n')
+}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
index 261a9f5e..b75f95ff 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/git-snapshot.ts
@@ -127,7 +127,8 @@ export function runGit(
})
}
-async function runGitText(repoDir: string, workspaceDir: string, args: string[], extraEnv: Record<string, string> = {}): Promise<string> {
+/** 导出给 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')
}
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
index 7f379547..b06548b3 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
@@ -197,7 +197,7 @@ export interface UndoOutcome {
text: string
}
-/** 解析 /undo 的输入行(turn id / 预览与冲突策略 / 两阶段 confirm/cancel)。 */
+/** 解析 /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
@@ -208,6 +208,7 @@ export function parseUndoInput(rawInput: string): UndoInput | { error: string }
let redo = false
let confirm = false
let cancel = false
+ let doctor = false
for (const part of parts) {
if (part === '--dry-run')
dryRun = true
@@ -223,6 +224,8 @@ export function parseUndoInput(rawInput: string): UndoInput | { error: string }
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)
@@ -234,13 +237,15 @@ export function parseUndoInput(rawInput: string): UndoInput | { error: string }
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 }
+ return { turnId, dryRun, preview, skipConflicts, force, redo, confirm, cancel, doctor }
}
export function assertSessionOwner(target: TurnRow, agent: { session: { id: string } }): UndoOutcome | undefined {
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
index 86acebcd..7057c123 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts
@@ -86,6 +86,8 @@ export interface UndoInput {
redo?: boolean
confirm?: boolean
cancel?: boolean
+ /** 只读诊断:/undo --doctor(不能与其他选项组合)。 */
+ doctor: boolean
}
/** 命令/路由共用的执行结果形状。 */
diff --git a/packages/dsh-tauri-turnrewind-ts/test/doctor.test.js b/packages/dsh-tauri-turnrewind-ts/test/doctor.test.js
new file mode 100644
index 00000000..15f72736
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/test/doctor.test.js
@@ -0,0 +1,63 @@
+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')
+ try {
+ await initGitWorkspace(workspace)
+ await writeFile(join(workspace, 'a.txt'), 'one')
+ await commitAll(workspace, 'initial')
+ const dataRoot = join(root, 'data')
+ const 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', before.commit)
+ 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)
+ db.close()
+ }
+ finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})