dsh-vscode-mode 0.36.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.
Files changed (42) hide show
  1. package/README.md +32 -4
  2. package/lib/client.js +68 -65
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +1961 -222
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +1 -1
  8. package/src/archivePurge.ts +411 -0
  9. package/src/client/addToConversation.ts +77 -18
  10. package/src/client/htmlPlan/HtmlPlanPanel.ts +9 -13
  11. package/src/client/htmlPlan/planActions.ts +97 -23
  12. package/src/client/htmlPlan/planPage.ts +2 -2
  13. package/src/client/reviewBatch.ts +48 -1
  14. package/src/client/state/diffSummary.ts +2 -1
  15. package/src/client/styles/editor.css +3 -1
  16. package/src/client/ui/EditorView.ts +8 -9
  17. package/src/client/ui/SvnCommitDialog.ts +256 -31
  18. package/src/client/ui/svnCommitModel.ts +63 -0
  19. package/src/index.ts +13 -0
  20. package/src/pending/capture.ts +201 -34
  21. package/src/pending/decide.ts +33 -1
  22. package/src/pending/externalCapture.ts +171 -8
  23. package/src/pending/kernel.ts +13 -2
  24. package/src/pending/noteTool.ts +96 -0
  25. package/src/pending/notes.ts +83 -0
  26. package/src/pending/persist.ts +301 -51
  27. package/src/pending/provenance.ts +45 -11
  28. package/src/pending/receipt.ts +177 -0
  29. package/src/pending/store.ts +161 -69
  30. package/src/pending/vcs.ts +25 -7
  31. package/src/pending/verdict.ts +170 -0
  32. package/src/pendingCompat.ts +14 -1
  33. package/src/pendingRpc.ts +19 -1
  34. package/src/reviewDb.ts +63 -2
  35. package/src/reviewRpc.ts +47 -1
  36. package/src/rpc.ts +36 -4
  37. package/src/shared/pendingReview.ts +20 -2
  38. package/src/shared/review.ts +17 -0
  39. package/src/shared/reviewRegions.ts +48 -3
  40. package/src/shared/rpc.ts +7 -1
  41. package/src/slowLog.ts +74 -0
  42. package/src/textEncoding.probe.ts +1 -0
@@ -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,41 +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, pushHistory,
22
- readOp, saveBlocks, saveDecisions, saveEntry, setHistoryState, writeOp,
22
+ dropEntry, earliestUndone, latestApplied, loadBlocks, loadEntries, loadEntry, pendingDb, purgeEntries, pushHistory,
23
+ readOp, saveBlocks, saveDecisions, saveEntry, setHistoryState, vacuumEntries, writeOp,
23
24
  } 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
24
31
 
25
32
  /**
26
- * @author ddj 2026年10月29号
27
- * @description: 统计一次差异的增删行数;非文本差异统一记 0/0。
33
+ * @private
34
+ * @author ddj 2026年11月25号
35
+ * @description: 一次 diff 同时给出增删行数与块状态,并按内容签名缓存;内容一变缓存自动失效。
28
36
  * @param entry 待审条目
29
37
  * @param baselineEmpty 基线置空(新建文件按全量新增计)
30
- * @returns 增删行数
38
+ * @param revision 条目版本号;未知时传 -1(按内容长度与时间退化判定)
39
+ * @returns 增删行数与块状态
31
40
  */
32
- 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
33
45
  const diff = diffOf(entry, baselineEmpty)
34
- if (diff.kind !== 'text') return { added: 0, deleted: 0 }
35
46
  let added = 0
36
47
  let deleted = 0
37
- for (const hunk of diff.hunks) {
38
- for (const line of hunk.lines) {
39
- if (line.startsWith('+')) added++
40
- 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
+ }
41
55
  }
56
+ blocks = reviewBlocks(diff).map((block) => ({ id: block.id, decision: 'pending' as const }))
57
+ }
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)
42
62
  }
43
- return { added, deleted }
63
+ derivedCache.set(entry.id, value)
64
+ return value
44
65
  }
45
66
 
46
67
  /**
47
- * @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号
48
82
  * @description: 由当前累计条目现场推导块身份;块是差异的纯函数,落库的只是决定状态。
49
83
  * @param entry 累计条目
84
+ * @param revision 条目版本号
50
85
  * @returns 块状态列表(决定一律 pending,判定推进后由下一次推导自然收窄)
51
86
  */
52
- function blockStatesOf(entry: PendingEntry): ReviewBlockState[] {
53
- const diff = diffOf(entry)
54
- if (diff.kind !== 'text') return []
55
- 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
56
89
  }
57
90
 
58
91
  /**
@@ -74,6 +107,8 @@ export function foldWrite(stored: StoredEntry | undefined, write: PendingWrite):
74
107
  source: sourceOfTool(write.tool),
75
108
  origin: originOf(write),
76
109
  baseKind: write.before === null ? 'absent' : (write.baseKind ?? 'known'),
110
+ evidence: write.evidence ?? 'snapshot',
111
+ verdict: write.verdict ?? 'changed',
77
112
  })
78
113
  if (!stored) {
79
114
  return {
@@ -118,7 +153,7 @@ function originOf(write: PendingWrite): PendingOrigin {
118
153
  */
119
154
  export function itemOf(stored: StoredEntry, baselineEmpty = false): PendingItem {
120
155
  const { entry, flags } = stored
121
- const counts = countsOf(entry, baselineEmpty)
156
+ const counts = countsOf(entry, baselineEmpty, flags.revision)
122
157
  const item: PendingItem = {
123
158
  id: entry.id,
124
159
  path: entry.path,
@@ -137,6 +172,8 @@ export function itemOf(stored: StoredEntry, baselineEmpty = false): PendingItem
137
172
  source: entry.source ?? 'tool',
138
173
  origin: entry.origin ?? 'agent',
139
174
  baseKind: entry.baseKind ?? 'known',
175
+ evidence: entry.evidence ?? 'snapshot',
176
+ verdict: entry.verdict ?? 'changed',
140
177
  }
141
178
  if (entry.lineage !== undefined) item.lineage = entry.lineage
142
179
  return item
@@ -177,7 +214,7 @@ export function loadPage(cwd: string, _sessionId?: string): PendingPage {
177
214
  const all = loadEntries(cwd)
178
215
  const visible = all
179
216
  const sourceAdds = new Map<string, Set<string>>()
180
- 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))))
181
218
  const gaps: string[] = pendingGaps(cwd)
182
219
  for (const stored of visible) {
183
220
  if (stored.flags.oversized) gaps.push(`${stored.entry.path}: 文本超出上限,仅保留标记`)
@@ -185,6 +222,19 @@ export function loadPage(cwd: string, _sessionId?: string): PendingPage {
185
222
  return { items, pending: items.filter((item) => !item.settled).length, nextCursor: null, gaps }
186
223
  }
187
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
+
188
238
  /**
189
239
  * @author ddj 2026年10月29号
190
240
  * @description: 读单条详情,包含可交给现有面板渲染的差异与块决定。
@@ -199,9 +249,9 @@ export function loadDetail(cwd: string, id: string, baselineEmpty = false): Pend
199
249
  const emptyBase = baselineEmpty || emptyBaseOf(cwd, stored)
200
250
  const diff = diffOf(stored.entry, emptyBase)
201
251
  return {
202
- item: itemOf(stored, emptyBase),
252
+ item: withNote(cwd, itemOf(stored, emptyBase)),
203
253
  diff,
204
- blocks: blockStatesOf(stored.entry),
254
+ blocks: blockStatesOf(stored.entry, stored.flags.revision),
205
255
  capability: capabilityOf(stored.entry, stored.flags),
206
256
  }
207
257
  }
@@ -314,7 +364,7 @@ export async function applyDecide(
314
364
  ): Promise<DecideOutcome | { ok: false; reason: string }> {
315
365
  const stored = loadEntries(cwd).find((item) => item.entry.id === request.id)
316
366
  if (!stored) return { ok: false, reason: 'unknown-item' }
317
- const beforeBlocks = blockStatesOf(stored.entry)
367
+ const beforeBlocks = blockStatesOf(stored.entry, stored.flags.revision)
318
368
  const outcome = await decide({
319
369
  request,
320
370
  entry: stored.entry,
@@ -331,12 +381,16 @@ export async function applyDecide(
331
381
  if (!outcome.ok) return { ok: false, reason: outcome.reason }
332
382
  saveEntry(cwd, { entry: outcome.entry, flags: outcome.flags })
333
383
  saveBlocks(cwd, request.id, outcome.blocks)
334
- // 记录撤销快照(含是否真的写过盘),撤销/重做都从这条记录反推
335
- pushHistory(cwd, 'decide', request.id, JSON.stringify({
336
- before: { entry: stored.entry, flags: stored.flags, blocks: beforeBlocks },
337
- 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,
338
392
  wrote: outcome.wrote,
339
- }), Date.now())
393
+ }, Date.now())
340
394
  return outcome
341
395
  }
342
396
 
@@ -384,7 +438,7 @@ export async function keepAll(cwd: string, items: PendingKeepTarget[]): Promise<
384
438
  continue
385
439
  }
386
440
 
387
- const beforeBlocks = blockStatesOf(before.entry)
441
+ const beforeBlocks = blockStatesOf(before.entry, before.flags.revision)
388
442
  const outcomeOf = await decide({
389
443
  request: { sessionId: before.entry.sessionId, id: item.id, revision: before.flags.revision,
390
444
  operationId: item.operationId, decision: 'accepted', scope: 'file' },
@@ -398,11 +452,7 @@ export async function keepAll(cwd: string, items: PendingKeepTarget[]): Promise<
398
452
  }
399
453
  outcome.kept.push({ id: item.id, path: before.entry.path })
400
454
  records.push({ entryId: item.id, stored: before, next: { entry: outcomeOf.entry, flags: outcomeOf.flags },
401
- blocks: outcomeOf.blocks, snapshot: JSON.stringify({
402
- before: { entry: before.entry, flags: before.flags, blocks: beforeBlocks },
403
- after: { entry: outcomeOf.entry, flags: outcomeOf.flags, blocks: outcomeOf.blocks },
404
- wrote: outcomeOf.wrote,
405
- }) })
455
+ blocks: outcomeOf.blocks })
406
456
  }
407
457
 
408
458
  // 落库阶段被别的决定抢先推进的条目从 kept 挪到 skipped,如实反映磁盘状态
@@ -444,8 +494,8 @@ export async function importFromVcs(
444
494
 
445
495
  /**
446
496
  * @author ddj 2026年10月30号
447
- * @description: 撤销或重做最近一次判定。先按 operationId 判幂等,再据栈顶记录判定方向是否合法,
448
- * 只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
497
+ * @description: 撤销或重做最近一次判定。一条路径只有一行撤销记录:撤销回到判定前的两侧内容,
498
+ * 重做再按同一判定推进一次;只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
449
499
  * @param fs 文件系统
450
500
  * @param cwd 工作区
451
501
  * @param move 撤销/重做请求
@@ -460,28 +510,59 @@ export async function undoDecide(
460
510
 
461
511
  const record = move.direction === 'undo' ? latestApplied(cwd) : earliestUndone(cwd)
462
512
  if (!record) return { ok: false, reason: move.direction === 'undo' ? 'no-undo' : 'no-redo' }
463
- const snapshot = parseSnapshot(record.snapshot)
464
- if (!snapshot) return { ok: false, reason: 'bad-history' }
465
- const stored = loadEntries(cwd).find((item) => item.entry.id === record.entryId)
513
+ const stored = loadEntry(cwd, record.entryId)
466
514
  if (!stored) return { ok: false, reason: 'unknown-item' }
467
- const target = move.direction === 'undo' ? snapshot.before : snapshot.after
515
+ const target = replayTargetOf(stored, record, move.direction === 'undo')
468
516
 
469
517
  writeOp(cwd, move.operationId, JSON.stringify(move), 'prepared')
470
518
  let wrote = false
471
- if (snapshot.wrote) {
472
- 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)
473
521
  if (!result.ok) return { ok: false, reason: result.reason }
474
522
  wrote = true
475
523
  }
476
524
 
477
- saveEntry(cwd, { entry: target.entry, flags: target.flags })
478
- saveBlocks(cwd, record.entryId, target.blocks)
479
- setHistoryState(cwd, record.id, move.direction === 'undo' ? 'undone' : 'applied')
480
- 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 }
481
529
  writeOp(cwd, move.operationId, JSON.stringify(move), 'committed', { result: JSON.stringify(outcome) })
482
530
  return outcome
483
531
  }
484
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
+
485
566
  /**
486
567
  * @author ddj 2026年10月30号
487
568
  * @description: 把文件内容恢复到目标快照:目标为缺失则删除,否则按版本守卫写回并读回校验。
@@ -500,36 +581,13 @@ async function writeBack(
500
581
  return write(target.entry.newText)
501
582
  }
502
583
 
503
- /** 历史快照中单侧状态。 */
584
+ /** 撤销/重做时的单侧目标状态。 */
504
585
  interface HistoryState {
505
586
  entry: PendingEntry
506
587
  flags: PendingFlags
507
588
  blocks: ReviewBlockState[]
508
589
  }
509
590
 
510
- /** 一次判定的双向快照。 */
511
- interface HistorySnapshot {
512
- before: HistoryState
513
- after: HistoryState
514
- wrote: boolean
515
- }
516
-
517
- /**
518
- * @author ddj 2026年10月30号
519
- * @description: 解析历史快照;损坏时返回 null,不猜测内容。
520
- * @param text 快照文本
521
- * @returns 快照或 null
522
- */
523
- function parseSnapshot(text: string): HistorySnapshot | null {
524
- try {
525
- const parsed = JSON.parse(text) as HistorySnapshot
526
- if (!parsed?.before?.entry || !parsed?.after?.entry) return null
527
- return parsed
528
- } catch {
529
- return null
530
- }
531
- }
532
-
533
591
  /** 稳定快照;缺失与读取失败严格区分,不允许省略现存文件的版本。 */
534
592
  type StableFile = { ok: true; content: string | null; version?: string } | { ok: false; reason: string }
535
593
 
@@ -603,6 +661,40 @@ export function removeEntry(cwd: string, id: string, revision: number): boolean
603
661
  return true
604
662
  }
605
663
 
664
+ /** 清库回执:命中、删除、保留条数,以及可选的 VACUUM 耗时。 */
665
+ export interface PendingPurgeOutcome extends PurgeOutcome {
666
+ /** VACUUM 耗时毫秒;dryRun 或未清理时为 undefined。 */
667
+ vacuumMs?: number
668
+ }
669
+
670
+ /** 清库默认口径:只清 watch 通道、空基线的条目——幽灵记录就长这样。 */
671
+ export const PURGE_DEFAULT_SOURCES = ['watch']
672
+ /** 清库默认基线口径:空基线(改前内容缺失)。 */
673
+ export const PURGE_DEFAULT_BASE_KINDS = ['absent']
674
+
675
+ /**
676
+ * @public
677
+ * @author ddj 2026-11-24
678
+ * @description: 清掉指定通道的待审条目(幽灵记录治理入口)。dryRun 只报数;
679
+ * 真删之后按需 VACUUM,把已删行占的页还给磁盘。
680
+ * @param cwd 工作区
681
+ * @param filter 筛选条件(缺省 watch + absent)
682
+ * @param options dryRun 只数不删;vacuum 删除后是否回收
683
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
684
+ */
685
+ export function purgePending(
686
+ cwd: string, filter: PurgeFilter = {}, options: { dryRun?: boolean; vacuum?: boolean } = {},
687
+ ): PendingPurgeOutcome {
688
+ const scoped: PurgeFilter = {
689
+ sources: filter.sources && filter.sources.length ? filter.sources : PURGE_DEFAULT_SOURCES,
690
+ baseKinds: filter.baseKinds && filter.baseKinds.length ? filter.baseKinds : PURGE_DEFAULT_BASE_KINDS,
691
+ before: filter.before,
692
+ }
693
+ const outcome = purgeEntries(cwd, scoped, options.dryRun === true)
694
+ if (options.dryRun || !outcome.removed || !options.vacuum) return outcome
695
+ return { ...outcome, vacuumMs: vacuumEntries(cwd) }
696
+ }
697
+
606
698
  /**
607
699
  * @author ddj 2026年10月29号
608
700
  * @description: 取错误码用于拒绝原因,没有则回落到消息文本。
@@ -390,12 +390,22 @@ async function runCommand(
390
390
  * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
391
391
  * @param shell shell 能力
392
392
  * @param cwd 工作区
393
+ * @param onFailure 失败原因回调(可选):调用方用它把「为什么没有状态」写进采集缺口
393
394
  * @returns 状态集合或 null
394
395
  */
395
- export async function vcsStatus(shell: ShellLike, cwd: string): Promise<VcsStatus | null> {
396
+ export async function vcsStatus(
397
+ shell: ShellLike, cwd: string, onFailure?: (reason: string) => void,
398
+ ): Promise<VcsStatus | null> {
396
399
  const detected = await detectVcsRoot(cwd)
397
- if (!detected || detected.kind === 'p4') return null
398
- return detected.kind === 'git' ? gitStatus(shell, detected.root) : svnStatus(shell, detected.root)
400
+ if (!detected) {
401
+ onFailure?.('不是 git/svn 工作副本')
402
+ return null
403
+ }
404
+ if (detected.kind === 'p4') {
405
+ onFailure?.('Perforce 工作副本不支持状态探测')
406
+ return null
407
+ }
408
+ return detected.kind === 'git' ? gitStatus(shell, detected.root, onFailure) : svnStatus(shell, detected.root, onFailure)
399
409
  }
400
410
 
401
411
  /**
@@ -404,11 +414,15 @@ export async function vcsStatus(shell: ShellLike, cwd: string): Promise<VcsStatu
404
414
  * @description: git 状态:一条 status 命令解析出改动集合。
405
415
  * @param shell shell 能力
406
416
  * @param root 仓库根
417
+ * @param onFailure 失败原因回调(可选)
407
418
  * @returns 状态集合或 null(命令失败)
408
419
  */
409
- async function gitStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
420
+ async function gitStatus(shell: ShellLike, root: string, onFailure?: (reason: string) => void): Promise<VcsStatus | null> {
410
421
  const status = await runCommand(shell, 'git -c status.renames=false status --porcelain=v1 -z --untracked-files=all', root)
411
- if (!status.ok) return null
422
+ if (!status.ok) {
423
+ onFailure?.('git status 失败:' + status.stderr.slice(0, 200))
424
+ return null
425
+ }
412
426
  const entries = new Map<string, VcsEntry>()
413
427
  for (const entry of parseGitStatus(status.stdout)) {
414
428
  const absolute = join(root, ...entry.path.split(GIT_SEPARATOR))
@@ -424,11 +438,15 @@ async function gitStatus(shell: ShellLike, root: string): Promise<VcsStatus | nu
424
438
  * @description: svn 状态:一条 status --xml 解析出改动集合。
425
439
  * @param shell shell 能力
426
440
  * @param root 工作副本根
441
+ * @param onFailure 失败原因回调(可选)
427
442
  * @returns 状态集合或 null(命令失败)
428
443
  */
429
- async function svnStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
444
+ async function svnStatus(shell: ShellLike, root: string, onFailure?: (reason: string) => void): Promise<VcsStatus | null> {
430
445
  const status = await runCommand(shell, 'svn status --xml', root)
431
- if (!status.ok) return null
446
+ if (!status.ok) {
447
+ onFailure?.('svn status 失败:' + status.stderr.slice(0, 200))
448
+ return null
449
+ }
432
450
  const entries = new Map<string, VcsEntry>()
433
451
  for (const entry of parseSvnStatus(status.stdout)) {
434
452
  const absolute = resolve(root, entry.path)