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,170 @@
1
+ /**
2
+ * 采集判定闸门:工具回执、磁盘快照、调用成败三者对账,决定这次调用算不算真实改动。
3
+ * 对不上就不建条目(strict),只记缺口;warn 降级为快照条目,off 完全退回旧行为。
4
+ * @author ddj 2026年11月25号
5
+ */
6
+ import type { PendingEvidence, PendingVerdict } from '../shared/pendingReview.js'
7
+ import type { ToolReceipt } from './receipt.js'
8
+
9
+ /** 闸门开关的环境变量名:strict(默认)/ warn / off。 */
10
+ export const GATE_ENV = 'DSH_EDIT_REVIEW_RECEIPT_GATE'
11
+
12
+ /** 闸门模式。 */
13
+ export type GateMode = 'strict' | 'warn' | 'off'
14
+
15
+ /** 一次判定的输入:回执 + 自己的快照 + 成败。 */
16
+ export interface EvidenceInput {
17
+ receipt?: ToolReceipt
18
+ isError: boolean
19
+ /** 写前是否取到了原始快照;取不到(并发占用)时用回执文本补基线。 */
20
+ hasBaseline: boolean
21
+ beforeRead: string | null
22
+ afterRead: string | null
23
+ hashBefore: string | null
24
+ hashAfter: string | null
25
+ }
26
+
27
+ /** 判定结果。 */
28
+ export interface VerdictOutcome {
29
+ verdict: PendingVerdict
30
+ evidence: PendingEvidence
31
+ /** 拒绝或降级的原因,写进缺口。 */
32
+ reason: string
33
+ }
34
+
35
+ /**
36
+ * @public
37
+ * @author ddj 2026年11月25号
38
+ * @description: 读闸门模式;未知值按 strict 处理,避免配置写错就静默放行。
39
+ * @param env 环境变量表
40
+ * @returns 闸门模式
41
+ */
42
+ export function gateModeOf(env: Record<string, string | undefined> = process.env): GateMode {
43
+ const raw = String(env[GATE_ENV] ?? '').trim().toLowerCase()
44
+ if (raw === 'off') return 'off'
45
+ if (raw === 'warn') return 'warn'
46
+ return 'strict'
47
+ }
48
+
49
+ /**
50
+ * @author ddj 2026年11月25号
51
+ * @description: 只用于比对的归一:去掉 BOM、统一行尾;绝不用于写回。
52
+ * @param text 一侧文本
53
+ * @returns 归一后的文本
54
+ */
55
+ export function norm(text: string | null): string | null {
56
+ return text === null ? null : text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
57
+ }
58
+
59
+ /**
60
+ * @private
61
+ * @author ddj 2026年11月25号
62
+ * @description: 结论构造。
63
+ * @param verdict 结局
64
+ * @param evidence 证据强度
65
+ * @param reason 原因
66
+ * @returns 判定结果
67
+ */
68
+ function outcomeOf(verdict: PendingVerdict, evidence: PendingEvidence, reason: string): VerdictOutcome {
69
+ return { verdict, evidence, reason }
70
+ }
71
+
72
+ /**
73
+ * @private
74
+ * @author ddj 2026年11月25号
75
+ * @description: 没有回执时的兜底:沿用今天的快照比较。
76
+ * @param input 判定输入
77
+ * @returns 判定结果
78
+ */
79
+ function snapshotOf(input: EvidenceInput): VerdictOutcome {
80
+ return input.beforeRead === input.afterRead
81
+ ? outcomeOf('noop', 'snapshot', '前后内容相同')
82
+ : outcomeOf('changed', 'snapshot', '')
83
+ }
84
+
85
+ /**
86
+ * @private
87
+ * @author ddj 2026年11月25号
88
+ * @description: 权威回执:用回执的前后全文核对磁盘,写前写后都对得上才算数。
89
+ * @param receipt 工具回执
90
+ * @param input 判定输入
91
+ * @returns 判定结果
92
+ */
93
+ function textOutcome(receipt: ToolReceipt, input: EvidenceInput): VerdictOutcome {
94
+ if (receipt.after === undefined) return outcomeOf('unverified', 'authoritative', '回执没有写后内容')
95
+ if (norm(receipt.after) !== norm(input.afterRead)) {
96
+ return outcomeOf('unverified', 'authoritative', '写后内容与磁盘不一致')
97
+ }
98
+ // 后端明确说不给写前内容(超大/二进制):写前用我们自己的快照,写后已由回执核对。
99
+ if (receipt.noBasis === true) {
100
+ if (!input.hasBaseline) return outcomeOf('unverified', 'authoritative', '回执没有写前内容,无法补基线')
101
+ return norm(input.beforeRead) === norm(input.afterRead)
102
+ ? outcomeOf('noop', 'authoritative', '前后内容相同')
103
+ : outcomeOf('changed', 'authoritative', '')
104
+ }
105
+ if (input.hasBaseline) {
106
+ if (norm(receipt.before ?? null) !== norm(input.beforeRead)) {
107
+ return outcomeOf('unverified', 'authoritative', '写前内容与磁盘不一致')
108
+ }
109
+ } else if (receipt.before === undefined) {
110
+ return outcomeOf('unverified', 'authoritative', '回执没有写前内容,无法补基线')
111
+ }
112
+ return norm(receipt.before ?? null) === norm(receipt.after)
113
+ ? outcomeOf('noop', 'authoritative', '回执前后相同')
114
+ : outcomeOf('changed', 'authoritative', '')
115
+ }
116
+
117
+ /**
118
+ * @private
119
+ * @author ddj 2026年11月25号
120
+ * @description: 哈希回执:写后哈希必须等于磁盘,写前哈希(若有)必须等于快照。
121
+ * @param receipt 工具回执
122
+ * @param input 判定输入
123
+ * @returns 判定结果
124
+ */
125
+ function hashOutcome(receipt: ToolReceipt, input: EvidenceInput): VerdictOutcome {
126
+ if (!receipt.revisionAfter) return outcomeOf('unverified', 'receipt', '回执没有写后哈希')
127
+ if (input.hashAfter !== receipt.revisionAfter) return outcomeOf('unverified', 'receipt', '写后哈希与磁盘不一致')
128
+ if (!input.hasBaseline) return outcomeOf('unverified', 'receipt', '没有写前快照,无法对账哈希')
129
+ if (!receipt.revisionBefore) {
130
+ return input.hashBefore === null
131
+ ? outcomeOf('changed', 'receipt', '')
132
+ : outcomeOf('unverified', 'receipt', '回执没有写前哈希')
133
+ }
134
+ if (input.hashBefore !== receipt.revisionBefore) return outcomeOf('unverified', 'receipt', '写前哈希与磁盘不一致')
135
+ return receipt.revisionBefore === receipt.revisionAfter
136
+ ? outcomeOf('noop', 'receipt', '回执前后哈希相同')
137
+ : outcomeOf('changed', 'receipt', '')
138
+ }
139
+
140
+ /**
141
+ * @private
142
+ * @author ddj 2026年11月25号
143
+ * @description: 按回执强度选核对口径。
144
+ * @param receipt 工具回执
145
+ * @param input 判定输入
146
+ * @returns 判定结果
147
+ */
148
+ function receiptOutcome(receipt: ToolReceipt, input: EvidenceInput): VerdictOutcome {
149
+ return receipt.strength === 'authoritative' ? textOutcome(receipt, input) : hashOutcome(receipt, input)
150
+ }
151
+
152
+ /**
153
+ * @public
154
+ * @author ddj 2026年11月25号
155
+ * @description: 一次写入的结局判定;只有 changed 值得建待审条目。
156
+ * @param input 回执、快照与成败
157
+ * @param mode 闸门模式(缺省读环境变量)
158
+ * @returns 结局、证据强度与原因
159
+ */
160
+ export function verdictOf(input: EvidenceInput, mode: GateMode = gateModeOf()): VerdictOutcome {
161
+ const snapshot = snapshotOf(input)
162
+ if (mode === 'off') return snapshot
163
+ if (input.isError && !input.receipt) {
164
+ return outcomeOf('failed', 'none', '工具报错,没有可采信的效果')
165
+ }
166
+ if (!input.receipt) return snapshot
167
+ const judged = receiptOutcome(input.receipt, input)
168
+ if (judged.verdict !== 'unverified') return judged
169
+ return mode === 'warn' ? { ...snapshot, reason: judged.reason } : judged
170
+ }
@@ -119,10 +119,23 @@ export function pendingItemOf(item: PendingItem, cwd?: string): ReviewItem {
119
119
  current: true,
120
120
  }
121
121
  // 来源徽标只对待审条目有意义:官方行没有采集通道。
122
- if (item.settled !== true) row.sourceLabel = sourceLabelOf(item)
122
+ if (item.settled !== true) row.sourceLabel = withNote(sourceLabelOf(item), item.note)
123
123
  return row
124
124
  }
125
125
 
126
+ /**
127
+ * @private
128
+ * @author ddj 2026年11月25号
129
+ * @description: 把只读说明接在来源徽标后面;列表里只给前 40 字,避免长句刷屏。
130
+ * @param label 来源徽标
131
+ * @param note 只读说明
132
+ * @returns 展示文案
133
+ */
134
+ function withNote(label: string, note: string | undefined): string {
135
+ if (!note) return label
136
+ return label + ' · 备注:' + (note.length > 40 ? note.slice(0, 40) + '…' : note)
137
+ }
138
+
126
139
  /**
127
140
  * @author ddj 2026年10月29号
128
141
  * @description: 待审详情转面板详情;Revert 映射到面板的 Undo 能力位。
package/src/pendingRpc.ts CHANGED
@@ -7,7 +7,7 @@ import { bucketOf } from './registry.js'
7
7
  import { readText } from './pending/capture.js'
8
8
  import { pendingRawId, setPendingCovers, trackPendingCover } from './pendingCompat.js'
9
9
  import { loadEntries, pendingVersion, saveEntry } from './pending/persist.js'
10
- import { applyDecide, importFromVcs, itemOf, loadDetail, loadPage, recordWrite, refreshed, removeEntry, undoDecide } from './pending/store.js'
10
+ import { applyDecide, importFromVcs, itemOf, loadDetail, loadPage, purgePending, recordWrite, refreshed, removeEntry, undoDecide } from './pending/store.js'
11
11
  import { alignInWorkspace } from './pending/externalAlign.js'
12
12
  import type { ShellLike } from './pending/vcs.js'
13
13
  import type { Ctx } from './store.js'
@@ -205,6 +205,24 @@ function refreshHandlers(kit: ScopeKit): Partial<RpcHandlerMap> {
205
205
  setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path))
206
206
  return { ok: true, imported: outcome.imported, changed: outcome.changed, gaps: outcome.gaps }
207
207
  },
208
+ /**
209
+ * @author ddj 2026-11-24
210
+ * @description: 清掉指定通道的幽灵记录。dryRun 只报数;真删后按需 VACUUM,
211
+ * 并重建「待审接管」集合,避免旧路径继续顶掉官方行。
212
+ * @param args 清理请求
213
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
214
+ */
215
+ 'edrv.pending.purge': async (args) => {
216
+ const cwd = await kit.write(args.sessionId)
217
+ const outcome = purgePending(cwd, {
218
+ sources: args.sources,
219
+ baseKinds: args.baseKinds,
220
+ before: args.before,
221
+ }, { dryRun: args.dryRun === true, vacuum: true })
222
+ const page = loadPage(cwd, args.sessionId)
223
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path))
224
+ return { ok: true, matched: outcome.matched, removed: outcome.removed, kept: outcome.kept, vacuumMs: outcome.vacuumMs }
225
+ },
208
226
  }
209
227
  }
210
228
 
package/src/reviewDb.ts CHANGED
@@ -136,7 +136,7 @@ export async function repairPaths(cwd: string, resolvePath: (cwd: string, path:
136
136
  }
137
137
  }
138
138
 
139
- /** @private @author ddj 2026年10月26号 @param db Transaction. @param snapshot Source payload. @param hash Source digest. */
139
+ /** @private @author ddj 2026年10月26号 / 2026年11月25号 @param db Transaction. @param snapshot Source payload. @param hash Source digest. */
140
140
  function insertSnapshot(db: DatabaseSync, snapshot: ReviewSnapshot, hash: string): void {
141
141
  const { sessionId, turn, seq } = snapshot
142
142
  const previous = db.prepare('SELECT id,identity,diff,decision FROM review_files WHERE session_id=? AND turn=? AND current=1').all(sessionId, turn) as Row[]
@@ -146,10 +146,33 @@ function insertSnapshot(db: DatabaseSync, snapshot: ReviewSnapshot, hash: string
146
146
  const insert = db.prepare('INSERT INTO review_files VALUES(?,?,?,?,?,?,?,?,0,1)')
147
147
  for (const [index, file] of snapshot.files.entries()) {
148
148
  const encoded = JSON.stringify(file.diff)
149
+ const summary = JSON.stringify(snapshot.summary.files[index])
150
+ // 同一路径只留一条:合并时锚点(id/turn/seq)不动,只把差异换成最新;
151
+ // 完全相同的重发保留既有判定,已判定且内容真的变了才另起一条待审。
152
+ const prior = latestRowOf(db, file.identity)
153
+ if (prior) {
154
+ const identical = String(prior.diff) === encoded
155
+ if (identical) {
156
+ db.prepare('UPDATE review_files SET current=1 WHERE id=?').run(String(prior.id))
157
+ continue
158
+ }
159
+ if (prior.decision === 'pending') {
160
+ const kept = db.prepare('SELECT block_id,decision FROM review_blocks WHERE file_id=?').all(String(prior.id)) as Row[]
161
+ db.prepare('UPDATE review_files SET summary=?,diff=?,current=1,revision=revision+1 WHERE id=?')
162
+ .run(summary, encoded, String(prior.id))
163
+ db.prepare('DELETE FROM review_blocks WHERE file_id=?').run(String(prior.id))
164
+ seedBlocks(db, String(prior.id), file.diff, 'pending')
165
+ // 内容没变的块沿用已做出的判定:合并不等于把用户已审过的块重新变成待定
166
+ const restore = db.prepare('UPDATE review_blocks SET decision=? WHERE file_id=? AND block_id=?')
167
+ for (const block of kept) restore.run(String(block.decision), String(prior.id), String(block.block_id))
168
+ continue
169
+ }
170
+ dropFile(db, String(prior.id))
171
+ }
149
172
  const unchanged = previous.find((item) => item.identity === file.identity && item.diff === encoded)
150
173
  const id = digest(JSON.stringify([sessionId, turn, seq, file.identity]))
151
174
  const decision = String(unchanged?.decision ?? 'pending')
152
- insert.run(id, sessionId, turn, seq, file.identity, JSON.stringify(snapshot.summary.files[index]), encoded, decision)
175
+ insert.run(id, sessionId, turn, seq, file.identity, summary, encoded, decision)
153
176
  seedBlocks(db, id, file.diff, decision)
154
177
  if (unchanged) {
155
178
  // A same-turn republish must preserve mixed per-block decisions, not seed all blocks as mixed.
@@ -162,6 +185,44 @@ function insertSnapshot(db: DatabaseSync, snapshot: ReviewSnapshot, hash: string
162
185
  }
163
186
  }
164
187
 
188
+ /**
189
+ * @private
190
+ * @author ddj 2026年11月25号
191
+ * @description: 取某路径当前最新的一条记录,用于「同路径只留一条」的合并判断。
192
+ * @param db 已打开连接
193
+ * @param identity 路径身份
194
+ * @returns 记录行或 undefined
195
+ */
196
+ function latestRowOf(db: DatabaseSync, identity: string): Row | undefined {
197
+ return db.prepare('SELECT id,decision,diff FROM review_files WHERE identity=? ORDER BY rowid DESC LIMIT 1').get(identity) as Row | undefined
198
+ }
199
+
200
+ /**
201
+ * @private
202
+ * @author ddj 2026年11月25号
203
+ * @description: 清掉某条记录的块决定,合并重算前先归零。
204
+ * @param db 已打开连接
205
+ * @param fileId 记录 id
206
+ * @returns 无
207
+ */
208
+ function dropBlocksOf(db: DatabaseSync, fileId: string): void {
209
+ db.prepare('DELETE FROM review_blocks WHERE file_id=?').run(fileId)
210
+ db.prepare('DELETE FROM review_evidence WHERE file_id=?').run(fileId)
211
+ }
212
+
213
+ /**
214
+ * @private
215
+ * @author ddj 2026年11月25号
216
+ * @description: 删掉一条官方记录及其块决定:合并语义下旧轮次不再留档。
217
+ * @param db 已打开连接
218
+ * @param fileId 记录 id
219
+ * @returns 无
220
+ */
221
+ function dropFile(db: DatabaseSync, fileId: string): void {
222
+ dropBlocksOf(db, fileId)
223
+ db.prepare('DELETE FROM review_files WHERE id=?').run(fileId)
224
+ }
225
+
165
226
  /** @public @author ddj 2026年10月26号 @param cwd Workspace. @param gap Announced event identity. @param state Durable inbox or explicit failure. */
166
227
  export function captureState(cwd: string, gap: CaptureGap, state: 'queued' | 'gap'): void {
167
228
  reviewDb(cwd).prepare(`INSERT INTO review_capture VALUES(?,?,?,?,?) ON CONFLICT(session_id,turn,seq)
package/src/reviewRpc.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Session-scoped official review RPC. @author ddj 2026年10月26号 */
2
2
  import { createHash } from 'node:crypto'
3
3
  import type { RpcHandlerMap } from './shared/rpc.js'
4
- import type { KeepAllItem, KeepAllResult, ReviewDetail, ReviewItem, ReviewPage } from './shared/review.js'
4
+ import type { KeepAllItem, KeepAllResult, ReviewDetail, ReviewItem, ReviewPage, UndoAllItem, UndoAllResult } from './shared/review.js'
5
5
  import type { PendingPage } from './shared/pendingReview.js'
6
6
  import { decideReview, keepOfficialAll, reviewDetail, reviewPage } from './reviewDb.js'
7
7
  import { undoReview } from './reviewUndo.js'
@@ -358,5 +358,51 @@ export function reviewHandlers(ctx: Ctx, registry: Registry): Partial<RpcHandler
358
358
  return { ok: false, error: message }
359
359
  }
360
360
  },
361
+ 'edrv.review.undoAll': async (args) => {
362
+ // 批量 Undo 每条都要写回源文件:必须由会话活跃的一端执行,冷端给可读原因而不是 500。
363
+ try {
364
+ const scope = await scopeOf(args.sessionId)
365
+ if (!scope.live) return { ok: false, error: UNDO_NEEDS_LIVE }
366
+ const items = Array.isArray(args.items) ? args.items : []
367
+ if (!items.length) return { ok: false, error: '没有可撤销的记录' }
368
+ if (items.length > BATCH_LIMIT) {
369
+ return { ok: false, error: `记录过多(${items.length} 条,上限 ${BATCH_LIMIT}),请先分批处理后重试` }
370
+ }
371
+ if (items.some((item) => item.id.startsWith(PENDING_PREFIX))) {
372
+ return { ok: false, error: '待审条目请逐条判定;批量 Undo 只处理官方审查记录' }
373
+ }
374
+
375
+ // 非本会话工具写入的来源先统一确认一次,避免整批撤销误伤用户代码
376
+ if (args.confirmed !== true) {
377
+ const externals = items.filter((item) => reviewDetail(scope.cwd, item.id)?.capability.confirmUndo === true)
378
+ if (externals.length) {
379
+ return { ok: true, result: { completed: 0, total: items.length, paths: [], needsConfirm: externals.length, error: '' } }
380
+ }
381
+ }
382
+
383
+ const result: UndoAllResult = { completed: 0, total: items.length, paths: [], error: '' }
384
+ const session = sessionOf(ctx, args.sessionId)
385
+ for (const item of items) {
386
+ try {
387
+ await undoReview(ctx, session, scope.cwd, {
388
+ sessionId: args.sessionId, id: item.id, seq: item.seq, revision: item.revision,
389
+ operationId: item.operationId, decision: 'rejected', scope: 'file',
390
+ })
391
+ result.completed++
392
+ result.paths.push(item.display)
393
+ } catch (error) {
394
+ // 与既有口径一致:遇冲突即停止,不声称原子多文件回滚
395
+ result.error = (error instanceof Error ? error.message : String(error))
396
+ break
397
+ }
398
+ }
399
+ log.info(`[review] undoAll live=1 total=${result.total} done=${result.completed}`)
400
+ return { ok: true, result }
401
+ } catch (error) {
402
+ const message = error instanceof Error ? error.message : String(error)
403
+ log.warn(`[review] undoAll 失败: ${message}`)
404
+ return { ok: false, error: message }
405
+ }
406
+ },
361
407
  }
362
408
  }
package/src/rpc.ts CHANGED
@@ -25,8 +25,10 @@ import { cp, mkdir, readFile, rename, rm, stat, writeFile, readdir } from 'node:
25
25
  import { basename, dirname, join } from 'node:path'
26
26
  import { archiveEntryFor, markDecision, recordResolved, reconstructOriginal } from './model.js'
27
27
  import { clearRevertState, listArchives, pageArchives, readArchives, revertState, setRevertState, startReverts } from './archiveDb.js'
28
+ import { purgeArchiveDb, scheduleArchiveRewrite } from './archivePurge.js'
28
29
  import { hasOfficial } from './reviewDb.js'
29
30
  import { log } from './log.js'
31
+ import { beginOperation } from './slowLog.js'
30
32
  import type { Registry, SessionScope } from './registry.js'
31
33
  import { bucketOf, cwdOfSession, resolveScope, sessionOf } from './registry.js'
32
34
  import type { SearchOrchestrator } from './search/orchestrator.js'
@@ -1135,6 +1137,31 @@ export function buildHandlers(
1135
1137
  return { ok: false, error: '归档列表读取失败:' + String(error) }
1136
1138
  }
1137
1139
  },
1140
+ /**
1141
+ * @author ddj 2026-11-24
1142
+ * @description: 归档库清理:保留期 + 每文件上限 + 撤销栈截断。缺省 dryRun,显式传 false 才删。
1143
+ * @param args 清理参数
1144
+ * @returns 三个统计口径与删除行数
1145
+ */
1146
+ 'edrv.archive.purge': async (args) => {
1147
+ const sc = await resolveScope(ctx, args.sessionId)
1148
+ if ('err' in sc) return { ok: false, error: sc.err }
1149
+ try {
1150
+ // 删行在进程内做(快);备份与 VACUUM 是整库 IO,交给子进程,避免堵住事件循环
1151
+ const outcome = purgeArchiveDb(sc.cwd, {
1152
+ dryRun: args.dryRun !== false,
1153
+ retentionDays: args.retentionDays,
1154
+ keepBatches: args.keepBatches,
1155
+ keepOps: args.keepOps,
1156
+ vacuum: false,
1157
+ })
1158
+ const changed = outcome.removed.batches + outcome.removed.history
1159
+ if (args.dryRun === false && changed && args.vacuum !== false) scheduleArchiveRewrite(sc.cwd)
1160
+ return { ok: true, ...outcome }
1161
+ } catch (error) {
1162
+ return { ok: false, error: '归档清理失败:' + String(error) }
1163
+ }
1164
+ },
1138
1165
  'edrv.archivePage': async (args) => {
1139
1166
  const sc = await resolveScope(ctx, args.sessionId)
1140
1167
  if ('err' in sc) return { ok: false, error: sc.err }
@@ -1901,8 +1928,13 @@ export async function handleRpc<M extends RpcMethod>(
1901
1928
  svnHandlers?: Partial<RpcHandlerMap>,
1902
1929
  dapHandlers?: Partial<RpcHandlerMap>,
1903
1930
  ): Promise<RpcResult<M>> {
1904
- const handlers = buildHandlers(ctx, registry, searcher, contentSearcher, lspHandlers, aiHandlers, fileVersions, svnHandlers, dapHandlers)
1905
- const handler = Object.hasOwn(handlers, method) ? handlers[method] : undefined
1906
- if (typeof handler !== 'function') return { ok: false, error: '未知方法: ' + String(method) } as RpcResult<M>
1907
- return handler(args)
1931
+ const done = beginOperation('rpc:' + String(method))
1932
+ try {
1933
+ const handlers = buildHandlers(ctx, registry, searcher, contentSearcher, lspHandlers, aiHandlers, fileVersions, svnHandlers, dapHandlers)
1934
+ const handler = Object.hasOwn(handlers, method) ? handlers[method] : undefined
1935
+ if (typeof handler !== 'function') return { ok: false, error: '未知方法: ' + String(method) } as RpcResult<M>
1936
+ return await handler(args)
1937
+ } finally {
1938
+ done()
1939
+ }
1908
1940
  }
@@ -18,8 +18,20 @@ export type PendingSource = 'edit' | 'write' | 'remote_ssh_write' | 'tool' | 'wa
18
18
  /** 归属:谁动的文件。撤销白名单只看它。 */
19
19
  export type PendingOrigin = 'agent' | 'editor' | 'vcs' | 'external'
20
20
 
21
- /** 修改前内容的可信度:known 已知内容,absent 当时不存在,vcs 版本库基线,unknown 拿不到。 */
22
- export type PendingBaseKind = 'known' | 'absent' | 'vcs' | 'unknown'
21
+ /**
22
+ * 修改前内容的可信度:known 已知内容,absent 当时不存在,vcs 版本库基线,
23
+ * normalized 由工具回执文本补出的基线(行尾已归一,写回前必须确认),unknown 拿不到。
24
+ */
25
+ export type PendingBaseKind = 'known' | 'absent' | 'vcs' | 'normalized' | 'unknown'
26
+
27
+ /**
28
+ * 采集证据强度:authoritative 工具回执自带前后全文;receipt 回执只带哈希;
29
+ * snapshot 只有自己的前后快照;none 没有可用证据。
30
+ */
31
+ export type PendingEvidence = 'authoritative' | 'receipt' | 'snapshot' | 'none'
32
+
33
+ /** 一次写入调用的结局:只有 changed 会进待审列表。 */
34
+ export type PendingVerdict = 'changed' | 'noop' | 'failed' | 'unverified'
23
35
 
24
36
  /** 会话血缘,用于子代理/派生会话归属到同一待审视图。 */
25
37
  export interface PendingLineage {
@@ -59,6 +71,12 @@ export interface PendingItem {
59
71
  origin?: PendingOrigin
60
72
  /** 修改前内容的可信度;旧条目没有该字段,按 `known` 处理。 */
61
73
  baseKind?: PendingBaseKind
74
+ /** 这次差异靠什么证据立起来;旧条目没有该字段,按 `snapshot` 处理。 */
75
+ evidence?: PendingEvidence
76
+ /** 这次调用的结局;旧条目没有该字段,按 `changed` 处理。 */
77
+ verdict?: PendingVerdict
78
+ /** 只读编辑说明(模型声明,仅展示,不参与判定);没有时不出现。 */
79
+ note?: string
62
80
  }
63
81
 
64
82
  /** 一页待审条目。 */
@@ -122,3 +122,20 @@ export interface KeepAllResult {
122
122
  skipped: KeepAllSkip[]
123
123
  error: string
124
124
  }
125
+ /** 批量 Undo 的一条目标:与单条 decide 同口径,operationId 由客户端按批次派生。 */
126
+ export interface UndoAllItem {
127
+ id: string
128
+ display: string
129
+ seq: number
130
+ revision: number
131
+ operationId: string
132
+ }
133
+ /** 批量 Undo 的结果:遇冲突即停止并如实记录,不声称原子回滚。 */
134
+ export interface UndoAllResult {
135
+ completed: number
136
+ total: number
137
+ paths: string[]
138
+ /** 因需要显式确认而没有执行的条数(非 0 时客户端应确认后重试)。 */
139
+ needsConfirm?: number
140
+ error: string
141
+ }
@@ -24,10 +24,11 @@ export interface ReviewRegion extends ReviewBlock {
24
24
  end?: number
25
25
  }
26
26
 
27
- /** @public @author ddj 2026年10月27号 @param diff Immutable official patch. @returns Contiguous change runs with stable source-coordinate identities. */
27
+ /** @public @author ddj 2026年10月27号 / 2026年11月25号 @param diff Immutable official patch. @returns Contiguous change runs with content-fingerprint identities. */
28
28
  export function reviewBlocks(diff: OfficialDiff): ReviewBlock[] {
29
29
  if (diff.kind !== 'text') return []
30
30
  const blocks: ReviewBlock[] = []
31
+ const seen = new Map<string, number>()
31
32
  for (const [hunkIndex, hunk] of diff.hunks.entries()) {
32
33
  let oldLine = hunk.oldStart, newLine = hunk.newStart
33
34
  let before: string[] = []
@@ -42,7 +43,7 @@ export function reviewBlocks(diff: OfficialDiff): ReviewBlock[] {
42
43
  }
43
44
  if (marker !== '+' && marker !== '-') continue
44
45
  if (!current) {
45
- current = { id: `${hunkIndex}:${oldLine}:${newLine}`, hunkIndex, oldStart: oldLine, newStart: newLine,
46
+ current = { id: '', hunkIndex, oldStart: oldLine, newStart: newLine,
46
47
  oldLines: [], newLines: [], contextBefore: before.slice(-3), contextAfter: [] }
47
48
  blocks.push(current); before = []
48
49
  }
@@ -50,9 +51,34 @@ export function reviewBlocks(diff: OfficialDiff): ReviewBlock[] {
50
51
  else { current.newLines.push(text); newLine++ }
51
52
  }
52
53
  }
54
+ // 身份取「内容指纹 + 同批序号」:同一块内容即使行号飘了也还是同一个块,
55
+ // 行号只作为兜底匹配用,不再写进身份,避免上游一变就让块 id 失效。
56
+ for (const block of blocks) {
57
+ const fingerprint = fingerprintOf(block)
58
+ const ordinal = seen.get(fingerprint) ?? 0
59
+ seen.set(fingerprint, ordinal + 1)
60
+ block.id = `${block.hunkIndex}:${fingerprint}:${ordinal}`
61
+ }
53
62
  return blocks
54
63
  }
55
64
 
65
+ /**
66
+ * @public
67
+ * @author ddj 2026年11月25号
68
+ * @description: 块内容指纹(FNV-1a 32 位,纯函数,宿主与浏览器端结果一致)。
69
+ * @param block 差异块
70
+ * @returns 8 位十六进制指纹
71
+ */
72
+ export function fingerprintOf(block: Pick<ReviewBlock, 'oldLines' | 'newLines'>): string {
73
+ const text = block.oldLines.join('\n') + '\u0000' + block.newLines.join('\n')
74
+ let hash = 0x811c9dc5
75
+ for (let index = 0; index < text.length; index++) {
76
+ hash ^= text.charCodeAt(index)
77
+ hash = Math.imul(hash, 0x01000193) >>> 0
78
+ }
79
+ return hash.toString(16).padStart(8, '0')
80
+ }
81
+
56
82
  /** @private @author ddj 2026年10月28号 @param lines Current logical lines. @param pattern Full block context and new lines. @returns At most two matching offsets, enough to reject ambiguity. */
57
83
  function scan(lines: string[], pattern: string[]): number[] {
58
84
  const matches: number[] = []
@@ -84,7 +110,7 @@ export function reviewRegions(diff: OfficialDiff, recordId: string, states: Revi
84
110
  const lines = content === null ? null : logicalLines(content)
85
111
  /** @private @author ddj 2026年10月28号 @param block Immutable logical block. @param idx Block order. @returns Decision and current location without mutating stored evidence. */
86
112
  function placeRegion(block: ReviewBlock, idx: number): ReviewRegion {
87
- const status = states.find((state) => state.id === block.id)?.decision ?? 'pending'
113
+ const status = decisionOf(states, block)
88
114
  const region: ReviewRegion = { ...block, sourceKind: 'official', recordId, idx, status, stale: true }
89
115
  if (lines === null) return { ...region, staleReason: 'no-content' }
90
116
 
@@ -97,3 +123,22 @@ export function reviewRegions(diff: OfficialDiff, recordId: string, states: Revi
97
123
  }
98
124
  return reviewBlocks(diff).map(placeRegion)
99
125
  }
126
+
127
+ /**
128
+ * @private
129
+ * @author ddj 2026年11月25号
130
+ * @description: 取一个块的已存判定。先按 id 精确匹配,再按内容指纹兜底、
131
+ * 最后按旧坐标 id 兜底——升级前落库的块决定不必重做。
132
+ * @param states 已存块决定
133
+ * @param block 当前块
134
+ * @returns 判定;都匹配不上时为 pending
135
+ */
136
+ function decisionOf(states: ReviewBlockState[], block: ReviewBlock): 'pending' | 'accepted' | 'rejected' {
137
+ const exact = states.find((state) => state.id === block.id)
138
+ if (exact) return exact.decision
139
+ const fingerprint = block.id.split(':')[1]
140
+ const byFingerprint = states.filter((state) => state.id.split(':')[1] === fingerprint)
141
+ if (byFingerprint.length === 1) return byFingerprint[0].decision
142
+ const legacy = states.find((state) => state.id === `${block.hunkIndex}:${block.oldStart}:${block.newStart}`)
143
+ return legacy ? legacy.decision : 'pending'
144
+ }
package/src/shared/rpc.ts CHANGED
@@ -28,7 +28,7 @@ import { DAP_ACTIONS } from './dap.js'
28
28
  import { transportUrl } from './remoteChannel.js'
29
29
  import type { LoggerLevel } from './logger.js'
30
30
  import type { SvnViewRequest, SvnViewPayload } from './svnExplorer.js'
31
- import type { DecideReview, KeepAllItem, KeepAllResult, ReviewDetail, ReviewPage, ReviewRequest } from './review.js'
31
+ import type { DecideReview, KeepAllItem, KeepAllResult, ReviewDetail, ReviewPage, ReviewRequest, UndoAllItem, UndoAllResult } from './review.js'
32
32
  import type {
33
33
  PendingDecide, PendingDetail, PendingHistoryMove, PendingImport,
34
34
  PendingItem, PendingPage, PendingRemove, PendingRequest,
@@ -385,6 +385,7 @@ export interface RpcRequestMap {
385
385
  'edrv.review.detail': ReviewRequest & { id: string }
386
386
  'edrv.review.decide': DecideReview
387
387
  'edrv.review.keepAll': ReviewRequest & { batchId: string; items: KeepAllItem[] }
388
+ 'edrv.review.undoAll': ReviewRequest & { batchId: string; items: UndoAllItem[]; confirmed?: boolean }
388
389
  'edrv.pending.list': PendingRequest
389
390
  'edrv.pending.detail': PendingRequest & { id: string }
390
391
  'edrv.pending.decide': PendingDecide
@@ -393,6 +394,7 @@ export interface RpcRequestMap {
393
394
  'edrv.pending.history': PendingHistoryMove
394
395
  'edrv.pending.import': PendingImport
395
396
  'edrv.pending.align': PendingRequest & { includeUntracked?: boolean }
397
+ 'edrv.pending.purge': PendingRequest & { dryRun?: boolean; sources?: string[]; baseKinds?: string[]; before?: number }
396
398
  'edrv.pending.version': PendingRequest
397
399
  'edrv.list': { sessionId?: string; callIds?: string[]; skipStale?: boolean }
398
400
  'edrv.accept': { sessionId?: string; callId: string; scope?: RpcScope; hunkIndex?: number }
@@ -411,6 +413,7 @@ export interface RpcRequestMap {
411
413
  'edrv.archiveList': { sessionId?: string }
412
414
  'edrv.archivePage': { sessionId?: string; cursor?: string; limit?: number }
413
415
  'edrv.archiveRead': { sessionId?: string; path?: string; batch?: number | null }
416
+ 'edrv.archive.purge': { sessionId?: string; dryRun?: boolean; retentionDays?: number; keepBatches?: number; keepOps?: number; vacuum?: boolean }
414
417
  'edrv.rollback': { sessionId?: string; path: string; batch?: number }
415
418
  'edrv.debug': { sessionId?: string; text: string; level?: LoggerLevel }
416
419
  'edrv.dlog.list': { sessionId?: string }
@@ -595,6 +598,7 @@ export interface RpcOkMap {
595
598
  'edrv.review.detail': { detail: ReviewDetail }
596
599
  'edrv.review.decide': { revision: number }
597
600
  'edrv.review.keepAll': { result: KeepAllResult }
601
+ 'edrv.review.undoAll': { result: UndoAllResult }
598
602
  'edrv.pending.list': { page: PendingPage }
599
603
  'edrv.pending.detail': { detail: PendingDetail }
600
604
  'edrv.pending.decide': { item: PendingItem; wrote: boolean }
@@ -603,6 +607,7 @@ export interface RpcOkMap {
603
607
  'edrv.pending.history': { item: PendingItem; wrote: boolean }
604
608
  'edrv.pending.import': { imported: number; changes: number }
605
609
  'edrv.pending.align': { imported: number; changed: number; gaps: string[] }
610
+ 'edrv.pending.purge': { matched: number; removed: number; kept: number; vacuumMs?: number }
606
611
  'edrv.pending.version': { version: number }
607
612
  'edrv.list': { records: RecordView[] }
608
613
  'edrv.accept': { record: RecordView }
@@ -621,6 +626,7 @@ export interface RpcOkMap {
621
626
  'edrv.archiveList': { entries: ArchiveEntry[] }
622
627
  'edrv.archivePage': { entries: ArchiveEntry[]; nextCursor: string | null }
623
628
  'edrv.archiveRead': { batches: ArchiveBatch[] }
629
+ 'edrv.archive.purge': { expired: number; overCap: number; keptPending: number; removed: { records: number; batches: number; history: number }; vacuumMs?: number }
624
630
  'edrv.rollback': { path: string; batch: number | null }
625
631
  'edrv.debug': object
626
632
  'edrv.dlog.list': { root: string; files: DebugLogFileInfo[]; current: string | null }