DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): cross-process workspace lock (P1-1)
yingtianlan9e2c1fbc8e78
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.tsindex 1a9fabc1..7d7f2fcd 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts@@ -50,6 +50,7 @@ import {} from './service/ledger'import { planDrift } from './service/planner'import { applyUndo, buildPlanEntries, executeUndoRestore, turnRefsExist, workspaceForAgent, workspaceHasActiveTurn, workspaceIssue, workspaceKeyFor } from './service/undo'+import { withWorkspaceLock, WorkspaceLockBusyError } from './service/workspace-lock'/** 插件名(诊断元数据,与 shared/constants 的 TURNREWIND_PLUGIN_NAME 一致)。 */export const name = 'dsh-tauri-turnrewind'@@ -144,20 +145,24 @@ async function settleActiveTurn(ledger: Ledger, active: Map<string, ActiveEntry>if (!current || current.runtime.disposed)returntry {- 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+ // 跨进程互斥(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)@@ -367,24 +372,34 @@ export function apply(ctx: HostApplyContext): void {settleDeferred(baseline, { ok: false, reason: 'turnrewind plugin disposed during baseline capture' })return}- await captureSnapshot(runtime.store, beforeRef, `turnrewind before ${key}`, runtime.parentRef)+ // 跨进程互斥(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}- insertTurn(ledger, {- turnId: key,- sessionId,- workspaceKey: runtime.workspaceKey,- startedAt,- beforeRef,- })- entry.baselineReady = truesettleDeferred(baseline, { ok: true })}catch (error) {active.delete(key)- const reason = `TURNREWIND_CAPTURE_FAILED: ${String(error)}`+ 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)@@ -456,14 +471,24 @@ export function apply(ctx: HostApplyContext): void {const conflicts = entries.filter(entry => entry.conflict)if (conflicts.length > 0)return [409, { error: `the workspace changed since the preview (${conflicts.length} conflicted file(s)) — run /undo again to refresh the plan` }]- const message = await executeUndoRestore(planRuntime, {- sessionId,- workspaceKey: row.workspace_key,- target,- paths,- entries,- skipConflicts: false,- })+ 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 = truereturn [200, { ok: true, message }]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.tsindex cd6d9500..de7dc30a 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@@ -355,6 +355,7 @@ export function createSnapshotStore(rootDir: string, workspaceDir: string): Snapconst normalizedWorkspace = source.workspaceDirconst repoDir = join(rootDir, 'snapshots', `${workspaceHash(normalizedWorkspace)}.git`)return {+ rootDir,repoDir,workspaceDir: normalizedWorkspace,sourceGitDir: source.gitDir,diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.tsindex c6d928ae..7b22e84c 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts@@ -11,6 +11,7 @@ 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)@@ -28,37 +29,46 @@ export interface PurgeSummary {/*** 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 ledgerPath = join(rootDir, 'ledger.sqlite')- if (existsSync(ledgerPath)) {- const db = openLedger(rootDir)- try {- db.exec('BEGIN')- const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceIdentity)- const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceIdentity)- const plans = db.prepare('DELETE FROM pending_plans WHERE workspace_key = ?').run(workspaceIdentity)- const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceIdentity)- const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceIdentity)- db.exec('COMMIT')- summary.ledger = {- operations: Number(operations.changes),- notices: Number(notices.changes),- plans: Number(plans.changes),- turns: Number(turns.changes),- workspaces: Number(workspaces.changes),+ const lock = acquireWorkspaceLockSync(rootDir, workspaceDir)+ try {+ const ledgerPath = join(rootDir, 'ledger.sqlite')+ if (existsSync(ledgerPath)) {+ const db = openLedger(rootDir)+ try {+ db.exec('BEGIN')+ const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceIdentity)+ const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceIdentity)+ const plans = db.prepare('DELETE FROM pending_plans WHERE workspace_key = ?').run(workspaceIdentity)+ const turns = db.prepare('DELETE FROM turns WHERE workspace_key = ?').run(workspaceIdentity)+ const workspaces = db.prepare('DELETE FROM workspaces WHERE workspace_key = ?').run(workspaceIdentity)+ db.exec('COMMIT')+ summary.ledger = {+ operations: Number(operations.changes),+ notices: Number(notices.changes),+ plans: Number(plans.changes),+ turns: Number(turns.changes),+ workspaces: Number(workspaces.changes),+ }+ }+ finally {+ db.close()}}- finally {- db.close()- }- }- summary.repoExisted = existsSync(repoDir)- rmSync(repoDir, { recursive: true, force: true })- return summary+ summary.repoExisted = existsSync(repoDir)+ rmSync(repoDir, { recursive: true, force: true })+ return summary+ }+ finally {+ lock.release()+ }}diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.tsindex fe4d33d1..6c5eed11 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts@@ -52,6 +52,7 @@ import {} from './ledger'import { classifyUndo, planDrift } from './planner'+import { acquireWorkspaceLock } from './workspace-lock'// ————————————————— redo(与 undo 同等的生产加固:applying operation / 失败明细 / needs-recovery) —————————————————@@ -90,46 +91,53 @@ async function applyRedo(runtime: WorkspaceRuntime, invocation: UndoInvocation,runtime.undoing = truetry {- 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) })+ // 与 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()}- 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 }}catch (error) {// completeRedoTransaction 已把本次 redo operation 落 needs-recovery,@@ -399,75 +407,83 @@ export async function executeUndoRestore(params: { sessionId: string, workspaceKey: string, target: TurnRow, paths: string[], entries: PlanEntry[], skipConflicts?: boolean },): Promise<string> {const { sessionId, workspaceKey, target, paths, entries, skipConflicts } = params- const operationId = randomUUID()- const beforeRef = `refs/turnrewind/operation-${operationId}`- await captureSnapshot(runtime.store, beforeRef, `turnrewind undo ${target.turn_id}`, runtime.parentRef)- createOperation(runtime.db, {- operationId,- kind: 'undo',- targetTurnId: target.turn_id,- requestedAt: new Date().toISOString(),- beforeRef,- })-+ // 跨进程互斥(P1-1):operation 快照、文件恢复与账本事务与另一个进程+ // 对同一 workspace 的 capture/settle/undo 互斥;忙等 10s 后显式报错。+ const lock = await acquireWorkspaceLock(runtime.store.rootDir, runtime.workspaceDir, { waitMs: 10000 })try {- const targets = skipConflicts ? entries.filter(entry => !entry.conflict) : entries- const restoredPaths: string[] = []- const failedPaths: { path: string, reason: string }[] = []- for (const entry of targets) {- try {- await restorePath(runtime.store, target.before_ref!, entry.path)- restoredPaths.push(entry.path)- }- catch (error) {- // One unrestorable file (oversized blob, unsupported target) must not- // abort the whole undo: the other files still restore, and the failure- // is reported per path instead of triggering a full rollback.- failedPaths.push({ path: entry.path, 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,+ 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,- createdAt: new Date().toISOString(),+ kind: 'undo',+ targetTurnId: target.turn_id,+ requestedAt: new Date().toISOString(),+ beforeRef,})- 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)+ const targets = skipConflicts ? entries.filter(entry => !entry.conflict) : entries+ const restoredPaths: string[] = []+ const failedPaths: { path: string, reason: string }[] = []+ for (const entry of targets) {+ try {+ await restorePath(runtime.store, target.before_ref!, entry.path)+ restoredPaths.push(entry.path)+ }+ catch (error) {+ // One unrestorable file (oversized blob, unsupported target) must not+ // abort the whole undo: the other files still restore, and the failure+ // is reported per path instead of triggering a full rollback.+ failedPaths.push({ path: entry.path, 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 (rollbackFailure) {- rollbackError = rollbackFailure+ 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)}`)}- 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()}}diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.tsnew file mode 100644index 00000000..09ff8293--- /dev/null+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts@@ -0,0 +1,179 @@+/**+ * 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 {+ 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)+ 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))+ }+ 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/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.tsindex 5e46617d..bb1d4be5 100644--- a/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/host/types/index.ts@@ -9,6 +9,8 @@ export type HostContext = any/** 快照仓库句柄:一个 Git worktree 对应一个私有 snapshot repo。 */export interface SnapshotStore {+ /** 数据根目录($DSH_HOME),workspace 锁文件的定位依赖它。 */+ rootDir: stringrepoDir: stringworkspaceDir: stringsourceGitDir: stringdiff --git a/packages/dsh-tauri-turnrewind-ts/src/index.ts b/packages/dsh-tauri-turnrewind-ts/src/index.tsindex 1888087d..dbe1f7cf 100644--- a/packages/dsh-tauri-turnrewind-ts/src/index.ts+++ b/packages/dsh-tauri-turnrewind-ts/src/index.ts@@ -42,4 +42,5 @@ export { openLedger } from './host/service/ledger'export { purgeWorkspace, resolveRootDir } from './host/service/maintenance'export { classifyUndo } from './host/service/planner'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/packages/dsh-tauri-turnrewind-ts/test/workspace-lock.test.js b/packages/dsh-tauri-turnrewind-ts/test/workspace-lock.test.jsnew file mode 100644index 00000000..36a6185a--- /dev/null+++ b/packages/dsh-tauri-turnrewind-ts/test/workspace-lock.test.js@@ -0,0 +1,121 @@+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')+})