dsh-vscode-mode 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@
11
11
  * 作者 ddj 2026-11-24
12
12
  */
13
13
  import { createHash } from 'node:crypto'
14
- import type { PendingBaseKind, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
14
+ import type { PendingBaseKind, PendingEvidence, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
15
15
  import { pathKeyFor } from '../shared/pathKey.js'
16
16
 
17
17
  // --region 常量
@@ -49,6 +49,11 @@ const SOURCE_RANK: Record<PendingSource, number> = {
49
49
  edit: 6, write: 6, remote_ssh_write: 5, tool: 4, watch: 3, scan: 2, vcs: 1,
50
50
  }
51
51
 
52
+ /** 证据强度:回执说过的话比自己的快照可信,快照又胜过没有任何依据。 */
53
+ const EVIDENCE_RANK: Record<PendingEvidence, number> = {
54
+ authoritative: 4, receipt: 3, snapshot: 2, none: 1,
55
+ }
56
+
52
57
  // --endregion
53
58
 
54
59
  // --region 纯函数
@@ -87,6 +92,32 @@ export function strongerSource(earlier: PendingSource | undefined, later: Pendin
87
92
  return (SOURCE_RANK[left] >= SOURCE_RANK[right] ? left : right)
88
93
  }
89
94
 
95
+ /**
96
+ * @author ddj 2026年11月25号
97
+ * @description: 合并证据强度:回执胜过快照,同级保留首次值。
98
+ * @param earlier 已落库证据(可为空)
99
+ * @param later 本次证据
100
+ * @returns 应当落库的证据强度
101
+ */
102
+ export function strongerEvidence(earlier: PendingEvidence | undefined, later: PendingEvidence | undefined): PendingEvidence {
103
+ const left = earlier ?? 'snapshot'
104
+ const right = later ?? 'snapshot'
105
+ return (EVIDENCE_RANK[left] >= EVIDENCE_RANK[right] ? left : right)
106
+ }
107
+
108
+ /**
109
+ * @author ddj 2026年11月25号
110
+ * @description: 证据徽标文案;旧条目没有该字段时按快照处理。
111
+ * @param evidence 证据强度
112
+ * @returns 展示文案
113
+ */
114
+ export function evidenceLabelOf(evidence?: PendingEvidence): string {
115
+ if (evidence === 'authoritative') return '回执已核'
116
+ if (evidence === 'receipt') return '回执对账'
117
+ if (evidence === 'none') return '无回执'
118
+ return '快照推断'
119
+ }
120
+
90
121
  /**
91
122
  * @author ddj 2026-11-24
92
123
  * @description: 去重键:路径比较键 + 内容 sha256。只按内容判同一变化,不看时间。
@@ -99,8 +130,8 @@ export function dedupeKey(pathKey: string, content: string | null): string {
99
130
  }
100
131
 
101
132
  /**
102
- * @author ddj 2026-11-24
103
- * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销。
133
+ * @author ddj 2026-11-24 / 2026年11月25号
134
+ * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销;归一基线要确认。
104
135
  * @param origin 归属
105
136
  * @param baseKind 基线与可信度
106
137
  * @returns 可直接撤销 / 需确认 / 禁止
@@ -109,23 +140,26 @@ export function revertPolicyOf(
109
140
  origin: PendingOrigin | undefined,
110
141
  baseKind: PendingBaseKind | undefined,
111
142
  ): 'direct' | 'confirm' | 'blocked' {
112
- if ((baseKind ?? 'known') === 'unknown') return 'blocked'
143
+ const base = baseKind ?? 'known'
144
+ if (base === 'unknown') return 'blocked'
145
+ if (base === 'normalized') return 'confirm'
113
146
  return (origin ?? 'agent') === 'agent' ? 'direct' : 'confirm'
114
147
  }
115
148
 
116
149
  /**
117
- * @author ddj 2026-11-24
118
- * @description: 条目来源徽标文案;官方行没有徽标。
150
+ * @author ddj 2026-11-24 / 2026年11月25号
151
+ * @description: 条目来源徽标文案;官方行没有徽标,待审条目在来源后附证据强度。
119
152
  * @param entry 待审条目的来源字段
120
153
  * @returns 展示文案
121
154
  */
122
- export function sourceLabelOf(entry: { source?: PendingSource; origin?: PendingOrigin }): string {
155
+ export function sourceLabelOf(entry: { source?: PendingSource; origin?: PendingOrigin; evidence?: PendingEvidence }): string {
123
156
  const source = entry.source ?? 'tool'
124
157
  const origin = entry.origin ?? 'agent'
125
- if (origin === 'agent') return source + ' · agent'
126
- if (origin === 'editor') return '编辑器保存'
127
- if (origin === 'vcs') return '版本库同步'
128
- return source + ' · 外部'
158
+ const badge = ' · ' + evidenceLabelOf(entry.evidence)
159
+ if (origin === 'agent') return source + ' · agent' + badge
160
+ if (origin === 'editor') return '编辑器保存' + badge
161
+ if (origin === 'vcs') return '版本库同步' + badge
162
+ return source + ' · 外部' + badge
129
163
  }
130
164
 
131
165
  // --endregion
@@ -0,0 +1,177 @@
1
+ /**
2
+ * 工具回执适配:把一次写调用的结果读成「它自己声明改了哪个文件、改前改后是什么」。
3
+ * 只认已见形状;形状不认识一律返回空数组,交给快照判定,绝不猜内容。
4
+ * @author ddj 2026年11月25号
5
+ */
6
+ import { OPS_PREFIX } from '../toolTargets.js'
7
+
8
+ /** 回执强度:authoritative 带前后全文,receipt 只带哈希。 */
9
+ export type ReceiptStrength = 'authoritative' | 'receipt'
10
+
11
+ /** 一次调用对一个文件声明的效果。 */
12
+ export interface ToolReceipt {
13
+ /** 工具自己的路径写法(可能是相对路径)。 */
14
+ path: string
15
+ /** 写前文本;`null` = 工具声明该文件此前不存在。 */
16
+ before?: string | null
17
+ /** 写后文本;`null` = 工具声明该文件已被删除。 */
18
+ after?: string | null
19
+ /** 写前 SHA-256(小写十六进制)。 */
20
+ revisionBefore?: string
21
+ /** 写后 SHA-256(小写十六进制)。 */
22
+ revisionAfter?: string
23
+ /** 工具自己声明的完成状态,仅用于诊断。 */
24
+ status: 'completed' | 'failed' | 'unknown' | 'skipped'
25
+ /** 工具明确表示「写前内容给不出来」(超大/二进制/超过上下文上限),before 的 null 不代表文件不存在。 */
26
+ noBasis?: boolean
27
+ strength: ReceiptStrength
28
+ }
29
+
30
+ /** 无类型的结果对象。 */
31
+ type Row = Record<string, unknown>
32
+
33
+ /**
34
+ * @author ddj 2026年11月25号
35
+ * @description: 取工具结果里的规范值;失败结果没有值,直接返回 undefined。
36
+ * @param result 工具执行结果
37
+ * @returns 规范值对象或 undefined
38
+ */
39
+ function valueOf(result: unknown): Row | undefined {
40
+ if (!result || typeof result !== 'object') return undefined
41
+ const value = (result as Row & { value?: unknown }).value
42
+ return value && typeof value === 'object' ? value as Row : undefined
43
+ }
44
+
45
+ /**
46
+ * @author ddj 2026年11月25号
47
+ * @description: 读文本字段:字符串即内容,`null` 即声明不存在,其它一律无效。
48
+ * @param value 字段值
49
+ * @returns 文本、null 或 undefined(无效)
50
+ */
51
+ function textOf(value: unknown): string | null | undefined {
52
+ if (value === null) return null
53
+ return typeof value === 'string' ? value : undefined
54
+ }
55
+
56
+ /**
57
+ * @author ddj 2026年11月25号
58
+ * @description: 读哈希字段;只接受 64 位十六进制,其余(含 `absent`)视为没有。
59
+ * @param value 字段值
60
+ * @returns 小写哈希或 undefined
61
+ */
62
+ function hashOf(value: unknown): string | undefined {
63
+ return typeof value === 'string' && /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : undefined
64
+ }
65
+
66
+ /**
67
+ * @author ddj 2026年11月25号
68
+ * @description: 读路径字段;空串与非字符串都不算路径。
69
+ * @param value 字段值
70
+ * @returns 路径或 undefined
71
+ */
72
+ function pathOf(value: unknown): string | undefined {
73
+ return typeof value === 'string' && value.trim() ? value : undefined
74
+ }
75
+
76
+ /**
77
+ * @author ddj 2026年11月25号
78
+ * @description: 官方 edit/write 的回执:结果里直接带 path/before/after。
79
+ * @param name 工具名
80
+ * @param value 规范值
81
+ * @returns 回执列表;形状不符为空
82
+ */
83
+ function officialReceipts(name: string, value: Row): ToolReceipt[] {
84
+ const path = pathOf(value.path)
85
+ const before = textOf(value.before)
86
+ const after = textOf(value.after)
87
+ if (!path || before === undefined || after === undefined) return []
88
+ if (name === 'edit' && typeof before !== 'string') return []
89
+ // write 覆盖时 before 可能是 null(超大/二进制,后端不给上下文基线),不能当成新建。
90
+ const receipt: ToolReceipt = { path, before, after, status: 'completed', strength: 'authoritative' }
91
+ if (name === 'write' && before === null && value.operation === 'update') receipt.noBasis = true
92
+ return [receipt]
93
+ }
94
+
95
+ /**
96
+ * @author ddj 2026年11月25号
97
+ * @description: apply_patch 的回执:每个完成或失败操作下挂的 changes 才是实际效果。
98
+ * @param value 规范值
99
+ * @returns 逐文件回执
100
+ */
101
+ function patchReceipts(value: Row): ToolReceipt[] {
102
+ if (value.phase !== 'commit' || !Array.isArray(value.operations)) return []
103
+ const receipts: ToolReceipt[] = []
104
+ for (const raw of value.operations as unknown[]) {
105
+ if (!raw || typeof raw !== 'object') continue
106
+ const operation = raw as Row & { status?: unknown; changes?: unknown }
107
+ if (!Array.isArray(operation.changes)) continue
108
+ const status = operation.status === 'completed' ? 'completed' : operation.status === 'failed' ? 'failed' : 'skipped'
109
+ for (const change of operation.changes as unknown[]) {
110
+ if (!change || typeof change !== 'object') continue
111
+ const item = change as Row
112
+ const path = pathOf(item.path)
113
+ const before = textOf(item.before)
114
+ const after = textOf(item.after)
115
+ if (!path || before === undefined || after === undefined) continue
116
+ receipts.push({ path, before, after, status, strength: 'authoritative' })
117
+ }
118
+ }
119
+ return receipts
120
+ }
121
+
122
+ /**
123
+ * @author ddj 2026年11月25号
124
+ * @description: 批量替换回执:只认执行完成、且带写后计划的条目。
125
+ * @param items 回执条目
126
+ * @returns 逐文件回执
127
+ */
128
+ function replaceReceipts(items: unknown[]): ToolReceipt[] {
129
+ const receipts: ToolReceipt[] = []
130
+ for (const raw of items) {
131
+ if (!raw || typeof raw !== 'object') continue
132
+ const item = raw as Row
133
+ const path = pathOf(item.path)
134
+ const revisionAfter = hashOf(item.revisionAfter)
135
+ if (!path || item.status !== 'completed' || !revisionAfter) continue
136
+ receipts.push({
137
+ path, revisionBefore: hashOf(item.revision), revisionAfter, status: 'completed', strength: 'receipt',
138
+ })
139
+ }
140
+ return receipts
141
+ }
142
+
143
+ /**
144
+ * @author ddj 2026年11月25号
145
+ * @description: dsh-ops 回执:单目标带 path/to 与写前后哈希;删除没有写后哈希,交给快照。
146
+ * @param value 规范值
147
+ * @returns 回执列表
148
+ */
149
+ function opsReceipts(value: Row): ToolReceipt[] {
150
+ if (Array.isArray(value.items)) return replaceReceipts(value.items as unknown[])
151
+ // 删除没有写后内容:回执里的 revision 是写前值,不能当写后哈希用,交给快照。
152
+ if (value.removed === true) return []
153
+ const revisionAfter = hashOf(value.revision)
154
+ if (!revisionAfter) return []
155
+ const path = pathOf(value.to) ?? pathOf(value.path)
156
+ if (!path) return []
157
+ return [{ path, revisionBefore: hashOf(value.revisionBefore), revisionAfter, status: 'completed', strength: 'receipt' }]
158
+ }
159
+
160
+ /**
161
+ * @public
162
+ * @author ddj 2026年11月25号
163
+ * @description: 把一次写调用的结果转成回执;不认识的结果与工具返回空,调用方退回快照判定。
164
+ * @param name 工具名
165
+ * @param result 工具执行结果(可能带 value 包装)
166
+ * @param isError 工具是否报错
167
+ * @returns 回执列表
168
+ */
169
+ export function receiptsOf(name: string, result: unknown, isError: boolean): ToolReceipt[] {
170
+ if (isError && name !== 'apply_patch') return []
171
+ const value = valueOf(result)
172
+ if (!value) return []
173
+ if (name === 'edit' || name === 'write') return officialReceipts(name, value)
174
+ if (name === 'apply_patch') return patchReceipts(value)
175
+ if (String(name).startsWith(OPS_PREFIX)) return opsReceipts(value)
176
+ return []
177
+ }
@@ -9,6 +9,7 @@ import { addedFiles } from '../reviewDb.js'
9
9
  import { pathKeyOf, sourceOfTool, windows } from './provenance.js'
10
10
  import type { PendingWrite } from './capture.js'
11
11
  import { readText, pendingGaps } from './capture.js'
12
+ import { noteOf } from './notes.js'
12
13
  import type { ShellLike, VcsImportOptions } from './vcs.js'
13
14
  import { importVcsChanges } from './vcs.js'
14
15
  import type { DecideOutcome, WriteResult } from './decide.js'
@@ -18,42 +19,73 @@ import type { PendingEntry } from './kernel.js'
18
19
  import type { PendingFlags, StoredEntry } from './persist.js'
19
20
  import type { KeepRecord } from './persist.js'
20
21
  import {
21
- dropEntry, earliestUndone, latestApplied, loadBlocks, loadEntries, pendingDb, purgeEntries, pushHistory,
22
+ dropEntry, earliestUndone, latestApplied, loadBlocks, loadEntries, loadEntry, pendingDb, purgeEntries, pushHistory,
22
23
  readOp, saveBlocks, saveDecisions, saveEntry, setHistoryState, vacuumEntries, writeOp,
23
24
  } from './persist.js'
24
- import type { PurgeFilter, PurgeOutcome } from './persist.js'
25
+ import type { HistoryRow, PurgeFilter, PurgeOutcome } from './persist.js'
26
+
27
+ /** 派生结果缓存:列表每轮都重算全部条目的整文件差异,是卡顿主因之一;键取「revision + 两侧长度」。 */
28
+ const derivedCache = new Map<string, { signature: string; added: number; deleted: number; blocks: ReviewBlockState[] }>()
29
+ /** 派生缓存条数上限:超过就丢最早的一条,避免长会话无限增长。 */
30
+ const DERIVED_MAX = 256
25
31
 
26
32
  /**
27
- * @author ddj 2026年10月29号
28
- * @description: 统计一次差异的增删行数;非文本差异统一记 0/0。
33
+ * @private
34
+ * @author ddj 2026年11月25号
35
+ * @description: 一次 diff 同时给出增删行数与块状态,并按内容签名缓存;内容一变缓存自动失效。
29
36
  * @param entry 待审条目
30
37
  * @param baselineEmpty 基线置空(新建文件按全量新增计)
31
- * @returns 增删行数
38
+ * @param revision 条目版本号;未知时传 -1(按内容长度与时间退化判定)
39
+ * @returns 增删行数与块状态
32
40
  */
33
- function countsOf(entry: PendingEntry, baselineEmpty = false): { added: number; deleted: number } {
41
+ function derivedOf(entry: PendingEntry, baselineEmpty: boolean, revision: number): { added: number; deleted: number; blocks: ReviewBlockState[] } {
42
+ const signature = `${revision}:${baselineEmpty ? 1 : 0}:${entry.earlierVersion}:${entry.oldText.length}:${entry.newText.length}:${entry.updatedAt}`
43
+ const hit = derivedCache.get(entry.id)
44
+ if (hit && hit.signature === signature) return hit
34
45
  const diff = diffOf(entry, baselineEmpty)
35
- if (diff.kind !== 'text') return { added: 0, deleted: 0 }
36
46
  let added = 0
37
47
  let deleted = 0
38
- for (const hunk of diff.hunks) {
39
- for (const line of hunk.lines) {
40
- if (line.startsWith('+')) added++
41
- else if (line.startsWith('-')) deleted++
48
+ let blocks: ReviewBlockState[] = []
49
+ if (diff.kind === 'text') {
50
+ for (const hunk of diff.hunks) {
51
+ for (const line of hunk.lines) {
52
+ if (line.startsWith('+')) added++
53
+ else if (line.startsWith('-')) deleted++
54
+ }
42
55
  }
56
+ blocks = reviewBlocks(diff).map((block) => ({ id: block.id, decision: 'pending' as const }))
43
57
  }
44
- return { added, deleted }
58
+ const value = { signature, added, deleted, blocks }
59
+ if (derivedCache.size >= DERIVED_MAX) {
60
+ const oldest = derivedCache.keys().next().value
61
+ if (oldest !== undefined) derivedCache.delete(oldest)
62
+ }
63
+ derivedCache.set(entry.id, value)
64
+ return value
45
65
  }
46
66
 
47
67
  /**
48
- * @author ddj 2026年10月30号
68
+ * @author ddj 2026年10月29号 / 2026年11月25号
69
+ * @description: 统计一次差异的增删行数;非文本差异统一记 0/0。
70
+ * @param entry 待审条目
71
+ * @param baselineEmpty 基线置空(新建文件按全量新增计)
72
+ * @param revision 条目版本号
73
+ * @returns 增删行数
74
+ */
75
+ function countsOf(entry: PendingEntry, baselineEmpty = false, revision = -1): { added: number; deleted: number } {
76
+ const derived = derivedOf(entry, baselineEmpty, revision)
77
+ return { added: derived.added, deleted: derived.deleted }
78
+ }
79
+
80
+ /**
81
+ * @author ddj 2026年10月30号 / 2026年11月25号
49
82
  * @description: 由当前累计条目现场推导块身份;块是差异的纯函数,落库的只是决定状态。
50
83
  * @param entry 累计条目
84
+ * @param revision 条目版本号
51
85
  * @returns 块状态列表(决定一律 pending,判定推进后由下一次推导自然收窄)
52
86
  */
53
- function blockStatesOf(entry: PendingEntry): ReviewBlockState[] {
54
- const diff = diffOf(entry)
55
- if (diff.kind !== 'text') return []
56
- return reviewBlocks(diff).map((block) => ({ id: block.id, decision: 'pending' as const }))
87
+ function blockStatesOf(entry: PendingEntry, revision = -1): ReviewBlockState[] {
88
+ return derivedOf(entry, false, revision).blocks
57
89
  }
58
90
 
59
91
  /**
@@ -75,6 +107,8 @@ export function foldWrite(stored: StoredEntry | undefined, write: PendingWrite):
75
107
  source: sourceOfTool(write.tool),
76
108
  origin: originOf(write),
77
109
  baseKind: write.before === null ? 'absent' : (write.baseKind ?? 'known'),
110
+ evidence: write.evidence ?? 'snapshot',
111
+ verdict: write.verdict ?? 'changed',
78
112
  })
79
113
  if (!stored) {
80
114
  return {
@@ -119,7 +153,7 @@ function originOf(write: PendingWrite): PendingOrigin {
119
153
  */
120
154
  export function itemOf(stored: StoredEntry, baselineEmpty = false): PendingItem {
121
155
  const { entry, flags } = stored
122
- const counts = countsOf(entry, baselineEmpty)
156
+ const counts = countsOf(entry, baselineEmpty, flags.revision)
123
157
  const item: PendingItem = {
124
158
  id: entry.id,
125
159
  path: entry.path,
@@ -138,6 +172,8 @@ export function itemOf(stored: StoredEntry, baselineEmpty = false): PendingItem
138
172
  source: entry.source ?? 'tool',
139
173
  origin: entry.origin ?? 'agent',
140
174
  baseKind: entry.baseKind ?? 'known',
175
+ evidence: entry.evidence ?? 'snapshot',
176
+ verdict: entry.verdict ?? 'changed',
141
177
  }
142
178
  if (entry.lineage !== undefined) item.lineage = entry.lineage
143
179
  return item
@@ -178,7 +214,7 @@ export function loadPage(cwd: string, _sessionId?: string): PendingPage {
178
214
  const all = loadEntries(cwd)
179
215
  const visible = all
180
216
  const sourceAdds = new Map<string, Set<string>>()
181
- const items = visible.map((stored) => itemOf(stored, emptyBaseOf(cwd, stored, sourceAdds)))
217
+ const items = visible.map((stored) => withNote(cwd, itemOf(stored, emptyBaseOf(cwd, stored, sourceAdds))))
182
218
  const gaps: string[] = pendingGaps(cwd)
183
219
  for (const stored of visible) {
184
220
  if (stored.flags.oversized) gaps.push(`${stored.entry.path}: 文本超出上限,仅保留标记`)
@@ -186,6 +222,19 @@ export function loadPage(cwd: string, _sessionId?: string): PendingPage {
186
222
  return { items, pending: items.filter((item) => !item.settled).length, nextCursor: null, gaps }
187
223
  }
188
224
 
225
+ /**
226
+ * @private
227
+ * @author ddj 2026年11月25号
228
+ * @description: 挂上模型的只读说明;说明只在内存里,不落库也不参与判定。
229
+ * @param cwd 工作区
230
+ * @param item 列表项
231
+ * @returns 可能带说明的列表项
232
+ */
233
+ function withNote(cwd: string, item: PendingItem): PendingItem {
234
+ const note = noteOf(cwd, item.id)
235
+ return note === undefined ? item : { ...item, note }
236
+ }
237
+
189
238
  /**
190
239
  * @author ddj 2026年10月29号
191
240
  * @description: 读单条详情,包含可交给现有面板渲染的差异与块决定。
@@ -200,9 +249,9 @@ export function loadDetail(cwd: string, id: string, baselineEmpty = false): Pend
200
249
  const emptyBase = baselineEmpty || emptyBaseOf(cwd, stored)
201
250
  const diff = diffOf(stored.entry, emptyBase)
202
251
  return {
203
- item: itemOf(stored, emptyBase),
252
+ item: withNote(cwd, itemOf(stored, emptyBase)),
204
253
  diff,
205
- blocks: blockStatesOf(stored.entry),
254
+ blocks: blockStatesOf(stored.entry, stored.flags.revision),
206
255
  capability: capabilityOf(stored.entry, stored.flags),
207
256
  }
208
257
  }
@@ -315,7 +364,7 @@ export async function applyDecide(
315
364
  ): Promise<DecideOutcome | { ok: false; reason: string }> {
316
365
  const stored = loadEntries(cwd).find((item) => item.entry.id === request.id)
317
366
  if (!stored) return { ok: false, reason: 'unknown-item' }
318
- const beforeBlocks = blockStatesOf(stored.entry)
367
+ const beforeBlocks = blockStatesOf(stored.entry, stored.flags.revision)
319
368
  const outcome = await decide({
320
369
  request,
321
370
  entry: stored.entry,
@@ -332,12 +381,16 @@ export async function applyDecide(
332
381
  if (!outcome.ok) return { ok: false, reason: outcome.reason }
333
382
  saveEntry(cwd, { entry: outcome.entry, flags: outcome.flags })
334
383
  saveBlocks(cwd, request.id, outcome.blocks)
335
- // 记录撤销快照(含是否真的写过盘),撤销/重做都从这条记录反推
336
- pushHistory(cwd, 'decide', request.id, JSON.stringify({
337
- before: { entry: stored.entry, flags: stored.flags, blocks: beforeBlocks },
338
- after: { entry: outcome.entry, flags: outcome.flags, blocks: outcome.blocks as ReviewBlockState[] },
384
+ // 撤销行按路径覆盖写:同一路径永远只有一行,撤销回到判定前的基线或内容
385
+ pushHistory(cwd, {
386
+ entryId: request.id,
387
+ path: stored.entry.path,
388
+ kind: request.decision === 'accepted' ? 'keep' : 'revert',
389
+ earlier: stored.entry.earlierVersion,
390
+ baseline: stored.entry.oldText,
391
+ content: stored.entry.newText,
339
392
  wrote: outcome.wrote,
340
- }), Date.now())
393
+ }, Date.now())
341
394
  return outcome
342
395
  }
343
396
 
@@ -385,7 +438,7 @@ export async function keepAll(cwd: string, items: PendingKeepTarget[]): Promise<
385
438
  continue
386
439
  }
387
440
 
388
- const beforeBlocks = blockStatesOf(before.entry)
441
+ const beforeBlocks = blockStatesOf(before.entry, before.flags.revision)
389
442
  const outcomeOf = await decide({
390
443
  request: { sessionId: before.entry.sessionId, id: item.id, revision: before.flags.revision,
391
444
  operationId: item.operationId, decision: 'accepted', scope: 'file' },
@@ -399,11 +452,7 @@ export async function keepAll(cwd: string, items: PendingKeepTarget[]): Promise<
399
452
  }
400
453
  outcome.kept.push({ id: item.id, path: before.entry.path })
401
454
  records.push({ entryId: item.id, stored: before, next: { entry: outcomeOf.entry, flags: outcomeOf.flags },
402
- blocks: outcomeOf.blocks, snapshot: JSON.stringify({
403
- before: { entry: before.entry, flags: before.flags, blocks: beforeBlocks },
404
- after: { entry: outcomeOf.entry, flags: outcomeOf.flags, blocks: outcomeOf.blocks },
405
- wrote: outcomeOf.wrote,
406
- }) })
455
+ blocks: outcomeOf.blocks })
407
456
  }
408
457
 
409
458
  // 落库阶段被别的决定抢先推进的条目从 kept 挪到 skipped,如实反映磁盘状态
@@ -445,8 +494,8 @@ export async function importFromVcs(
445
494
 
446
495
  /**
447
496
  * @author ddj 2026年10月30号
448
- * @description: 撤销或重做最近一次判定。先按 operationId 判幂等,再据栈顶记录判定方向是否合法,
449
- * 只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
497
+ * @description: 撤销或重做最近一次判定。一条路径只有一行撤销记录:撤销回到判定前的两侧内容,
498
+ * 重做再按同一判定推进一次;只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
450
499
  * @param fs 文件系统
451
500
  * @param cwd 工作区
452
501
  * @param move 撤销/重做请求
@@ -461,28 +510,59 @@ export async function undoDecide(
461
510
 
462
511
  const record = move.direction === 'undo' ? latestApplied(cwd) : earliestUndone(cwd)
463
512
  if (!record) return { ok: false, reason: move.direction === 'undo' ? 'no-undo' : 'no-redo' }
464
- const snapshot = parseSnapshot(record.snapshot)
465
- if (!snapshot) return { ok: false, reason: 'bad-history' }
466
- const stored = loadEntries(cwd).find((item) => item.entry.id === record.entryId)
513
+ const stored = loadEntry(cwd, record.entryId)
467
514
  if (!stored) return { ok: false, reason: 'unknown-item' }
468
- const target = move.direction === 'undo' ? snapshot.before : snapshot.after
515
+ const target = replayTargetOf(stored, record, move.direction === 'undo')
469
516
 
470
517
  writeOp(cwd, move.operationId, JSON.stringify(move), 'prepared')
471
518
  let wrote = false
472
- if (snapshot.wrote) {
473
- const result = await writeBack(fs, cwd, stored, target, signal, policy)
519
+ if (target.write) {
520
+ const result = await writeBack(fs, cwd, stored, target.state, signal, policy)
474
521
  if (!result.ok) return { ok: false, reason: result.reason }
475
522
  wrote = true
476
523
  }
477
524
 
478
- saveEntry(cwd, { entry: target.entry, flags: target.flags })
479
- saveBlocks(cwd, record.entryId, target.blocks)
480
- setHistoryState(cwd, record.id, move.direction === 'undo' ? 'undone' : 'applied')
481
- const outcome = { ok: true as const, item: itemOf({ entry: target.entry, flags: target.flags }), wrote }
525
+ saveEntry(cwd, { entry: target.state.entry, flags: target.state.flags })
526
+ saveBlocks(cwd, record.entryId, target.state.blocks)
527
+ setHistoryState(cwd, record.entryId, move.direction === 'undo' ? 'undone' : 'applied')
528
+ const outcome = { ok: true as const, item: itemOf({ entry: target.state.entry, flags: target.state.flags }), wrote }
482
529
  writeOp(cwd, move.operationId, JSON.stringify(move), 'committed', { result: JSON.stringify(outcome) })
483
530
  return outcome
484
531
  }
485
532
 
533
+ /**
534
+ * @private
535
+ * @author ddj 2026年11月25号
536
+ * @description: 由当前条目与撤销行推导撤销/重做后的状态:Keep 只动基线,Revert 还要把内容写回盘。
537
+ * @param stored 当前条目
538
+ * @param record 撤销行
539
+ * @param undone 是否撤销(false 为重做)
540
+ * @returns 目标状态与是否需要写盘
541
+ */
542
+ function replayTargetOf(stored: StoredEntry, record: HistoryRow, undone: boolean): { state: HistoryState; write: boolean } {
543
+ const revision = stored.flags.revision + 1
544
+ if (record.kind === 'keep') {
545
+ const baseline = undone ? record.baseline : stored.entry.newText
546
+ const entry: PendingEntry = {
547
+ ...stored.entry,
548
+ oldText: baseline,
549
+ earlierVersion: undone ? record.earlier : 'file',
550
+ updatedAt: Date.now(),
551
+ }
552
+ delete entry.unseen
553
+ return { state: { entry, flags: { ...stored.flags, missing: false, revision }, blocks: [] }, write: false }
554
+ }
555
+ // Revert 写过盘:撤销写回判定前的内容,重做写回基线;新建文件的 Revert 重做等价于删除
556
+ const missing = !undone && record.earlier === 'none'
557
+ const entry: PendingEntry = {
558
+ ...stored.entry,
559
+ newText: missing ? '' : (undone ? record.content : record.baseline),
560
+ updatedAt: Date.now(),
561
+ }
562
+ delete entry.unseen
563
+ return { state: { entry, flags: { ...stored.flags, missing, revision }, blocks: [] }, write: true }
564
+ }
565
+
486
566
  /**
487
567
  * @author ddj 2026年10月30号
488
568
  * @description: 把文件内容恢复到目标快照:目标为缺失则删除,否则按版本守卫写回并读回校验。
@@ -501,36 +581,13 @@ async function writeBack(
501
581
  return write(target.entry.newText)
502
582
  }
503
583
 
504
- /** 历史快照中单侧状态。 */
584
+ /** 撤销/重做时的单侧目标状态。 */
505
585
  interface HistoryState {
506
586
  entry: PendingEntry
507
587
  flags: PendingFlags
508
588
  blocks: ReviewBlockState[]
509
589
  }
510
590
 
511
- /** 一次判定的双向快照。 */
512
- interface HistorySnapshot {
513
- before: HistoryState
514
- after: HistoryState
515
- wrote: boolean
516
- }
517
-
518
- /**
519
- * @author ddj 2026年10月30号
520
- * @description: 解析历史快照;损坏时返回 null,不猜测内容。
521
- * @param text 快照文本
522
- * @returns 快照或 null
523
- */
524
- function parseSnapshot(text: string): HistorySnapshot | null {
525
- try {
526
- const parsed = JSON.parse(text) as HistorySnapshot
527
- if (!parsed?.before?.entry || !parsed?.after?.entry) return null
528
- return parsed
529
- } catch {
530
- return null
531
- }
532
- }
533
-
534
591
  /** 稳定快照;缺失与读取失败严格区分,不允许省略现存文件的版本。 */
535
592
  type StableFile = { ok: true; content: string | null; version?: string } | { ok: false; reason: string }
536
593