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.
@@ -0,0 +1,96 @@
1
+ /** 只读编辑说明的工具入口:模型可以留一句话,但它不参与差异判定。 @author ddj 2026年11月25号 */
2
+ import { loadHostModule } from '../hostImport.js'
3
+ import type { Ctx } from '../store.js'
4
+ import { declareNote, NOTE_MAX } from './notes.js'
5
+
6
+ /** 工具参数。 */
7
+ interface NoteArgs {
8
+ path?: unknown
9
+ note?: unknown
10
+ }
11
+
12
+ /** 工具执行上下文里本工具关心的字段。 */
13
+ interface NoteExec {
14
+ agent?: { session?: { id?: string } }
15
+ signal?: AbortSignal
16
+ }
17
+
18
+ /** 工具回执。 */
19
+ interface NoteResult {
20
+ ok: boolean
21
+ path?: string
22
+ note?: string
23
+ error?: string
24
+ }
25
+
26
+ /** 会话 → 工作区。 */
27
+ export type CwdOf = (session: unknown) => string | null
28
+
29
+ /**
30
+ * @author ddj 2026年11月25号
31
+ * @description: 构造工具定义;只写进程内说明表,不碰磁盘、不碰工具参数。
32
+ * @param ctx Host 上下文(取 fs 解析路径)
33
+ * @param cwdOf 会话工作区解析
34
+ * @returns 定义选项
35
+ */
36
+ export function noteToolOptions(ctx: Ctx, cwdOf: CwdOf) {
37
+ /**
38
+ * @author ddj 2026年11月25号
39
+ * @description: 记录一条说明;非法输入返回可读原因,不抛错。
40
+ * @param args 模型参数
41
+ * @param exec 执行上下文
42
+ * @returns 回执
43
+ */
44
+ async function execute(args: NoteArgs, exec: NoteExec): Promise<NoteResult> {
45
+ const path = typeof args.path === 'string' ? args.path.trim() : ''
46
+ const note = typeof args.note === 'string' ? args.note.trim() : ''
47
+ if (!path || !note) return { ok: false, error: 'path 与 note 都必须是非空字符串' }
48
+ if (note.length > NOTE_MAX) return { ok: false, error: 'note 超过 ' + NOTE_MAX + ' 个字符' }
49
+ if (exec.signal?.aborted) return { ok: false, error: '说明已取消' }
50
+ const cwd = cwdOf(exec.agent?.session)
51
+ if (!cwd) return { ok: false, error: '编辑说明需要所属会话的工作区' }
52
+ const target = await ctx.get('fs').resolve(path, { cwd })
53
+ const identity = ctx.get('fs').processPath(target)
54
+ if (typeof identity !== 'string' || !identity) return { ok: false, error: '路径不可解析:' + path }
55
+ declareNote(cwd, identity, note)
56
+ return { ok: true, path, note }
57
+ }
58
+ /** @author ddj 2026年11月25号 @param _args 模型参数 @param result 回执 @returns 模型可见文本 */
59
+ function render(_args: NoteArgs, result: NoteResult) {
60
+ return [{ type: 'text', text: result.ok ? '已记录只读说明:' + result.path : '说明未记录:' + result.error }]
61
+ }
62
+ return {
63
+ name: 'edit_note',
64
+ description: 'Record a read-only note on a file for the review panel: why this file was changed. '
65
+ + 'It is display-only: it never decides whether a diff is real, never writes files, and never changes tool arguments.',
66
+ parameters: {
67
+ path: { type: 'string', required: true, description: 'File path, resolved by the filesystem backend in the session workspace.' },
68
+ note: { type: 'string', required: true, description: 'One sentence for the reviewer. At most ' + NOTE_MAX + ' characters.' },
69
+ },
70
+ output: { schema: { type: 'json' }, render },
71
+ isConcurrencySafe: true,
72
+ execute,
73
+ }
74
+ }
75
+
76
+ /**
77
+ * @author ddj 2026年11月25号
78
+ * @description: 注册工具;宿主缺少工具服务时静默跳过,不影响其余功能。
79
+ * @param ctx Host 插件上下文
80
+ * @param cwdOf 会话工作区解析
81
+ * @returns 无
82
+ */
83
+ export async function installNoteTool(ctx: Ctx, cwdOf: CwdOf): Promise<void> {
84
+ let module: { defineTool: (options: unknown) => unknown }
85
+ try {
86
+ module = await loadHostModule('@deepseek-ai/dsh-tools') as typeof module
87
+ } catch {
88
+ return
89
+ }
90
+ const definition = module.defineTool(noteToolOptions(ctx, cwdOf))
91
+ /** @author ddj 2026年11月25号 @returns 注册释放器 */
92
+ function install(): () => void {
93
+ return ctx.get('tools').register(definition)
94
+ }
95
+ ctx.effect(install, 'vscode-mode:edit-note')
96
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * 只读编辑说明:AI 给某个文件留一句「为什么改」,只供面板展示。
3
+ * 不参与真假判定、不改写工具参数、不落库;插件卸载或换工作区即清空。
4
+ * @author ddj 2026年11月25号
5
+ */
6
+ import { pathKeyOf } from './provenance.js'
7
+
8
+ /** 单条说明上限(字符)。 */
9
+ export const NOTE_MAX = 500
10
+ /** 每个工作区最多记住多少条,超出按写入序逐出最旧。 */
11
+ export const NOTE_SPACE_MAX = 200
12
+
13
+ /** 一个工作区的说明表。 */
14
+ interface NoteSpace {
15
+ /** 插入顺序,逐出时用。 */
16
+ order: string[]
17
+ /** 条目身份 → 说明。 */
18
+ byPath: Map<string, string>
19
+ }
20
+
21
+ /** 进程内说明表:随插件装配创建,卸载清空。 */
22
+ const spaces = new Map<string, NoteSpace>()
23
+
24
+ /**
25
+ * @private
26
+ * @author ddj 2026年11月25号
27
+ * @description: 取(或建)一个工作区的说明表。
28
+ * @param cwd 工作区
29
+ * @returns 说明表
30
+ */
31
+ function spaceOf(cwd: string): NoteSpace {
32
+ const key = pathKeyOf(cwd)
33
+ const existing = spaces.get(key)
34
+ if (existing) return existing
35
+ const created: NoteSpace = { order: [], byPath: new Map() }
36
+ spaces.set(key, created)
37
+ return created
38
+ }
39
+
40
+ /**
41
+ * @public
42
+ * @author ddj 2026年11月25号
43
+ * @description: 记录一条只读说明;同一文件后写的覆盖先写的,超出上限逐出最旧。
44
+ * @param cwd 工作区
45
+ * @param identity 条目身份(文件绝对路径)
46
+ * @param note 说明文本
47
+ * @returns 无
48
+ */
49
+ export function declareNote(cwd: string, identity: string, note: string): void {
50
+ if (!cwd || !identity || !note) return
51
+ const space = spaceOf(cwd)
52
+ const key = pathKeyOf(identity)
53
+ if (!space.byPath.has(key)) space.order.push(key)
54
+ space.byPath.set(key, note.slice(0, NOTE_MAX))
55
+ while (space.order.length > NOTE_SPACE_MAX) {
56
+ const oldest = space.order.shift()
57
+ if (oldest !== undefined) space.byPath.delete(oldest)
58
+ }
59
+ }
60
+
61
+ /**
62
+ * @public
63
+ * @author ddj 2026年11月25号
64
+ * @description: 读某个文件的只读说明;没有时返回 undefined。
65
+ * @param cwd 工作区
66
+ * @param identity 条目身份(文件绝对路径)
67
+ * @returns 说明或 undefined
68
+ */
69
+ export function noteOf(cwd: string, identity: string): string | undefined {
70
+ return spaces.get(pathKeyOf(cwd))?.byPath.get(pathKeyOf(identity))
71
+ }
72
+
73
+ /**
74
+ * @public
75
+ * @author ddj 2026年11月25号
76
+ * @description: 清空说明;不传工作区时清全部(插件卸载)。
77
+ * @param cwd 工作区
78
+ * @returns 无
79
+ */
80
+ export function clearNotes(cwd?: string): void {
81
+ if (cwd === undefined) spaces.clear()
82
+ else spaces.delete(pathKeyOf(cwd))
83
+ }
@@ -3,9 +3,10 @@
3
3
  * @author ddj 2026年10月29号
4
4
  */
5
5
  import type { DatabaseSync } from 'node:sqlite'
6
+ import { createHash } from 'node:crypto'
6
7
  import { activeReady, dbFor } from '../archiveDb.js'
7
8
  import { log } from '../log.js'
8
- import type { PendingBaseKind, PendingLineage, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
9
+ import type { PendingBaseKind, PendingEvidence, PendingLineage, PendingOrigin, PendingSource, PendingVerdict } from '../shared/pendingReview.js'
9
10
  import type { PendingEntry } from './kernel.js'
10
11
 
11
12
  /** 数据库行。 */
@@ -25,8 +26,8 @@ export interface StoredEntry {
25
26
  flags: PendingFlags
26
27
  }
27
28
 
28
- /** 待审库版本号,写进 metadata 便于日后迁移。v4 给条目加了采集来源与基线可信度。 */
29
- const SCHEMA_VERSION = '4'
29
+ /** 待审库版本号,写进 metadata 便于日后迁移。v6 把撤销栈改成「一条路径一行」。 */
30
+ const SCHEMA_VERSION = '6'
30
31
  /** 迁移前的备份后缀。 */
31
32
  const BACKUP_SUFFIX = '.before-pending.bak'
32
33
  /** 工作区待审版本号:条目一落库就自增,供客户端轮询判断是否需要重读列表。 */
@@ -80,7 +81,9 @@ export function pendingDb(cwd: string): DatabaseSync {
80
81
  try {
81
82
  db.exec(DDL)
82
83
  migrateHistory(db)
84
+ migrateHistoryMerge(db)
83
85
  migrateProvenance(db)
86
+ migrateEvidence(db)
84
87
  db.prepare("INSERT INTO metadata(name,value) VALUES('pending_schema',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value")
85
88
  .run(SCHEMA_VERSION)
86
89
  db.exec('COMMIT')
@@ -101,7 +104,8 @@ CREATE TABLE IF NOT EXISTS pending_entries (
101
104
  revision INTEGER NOT NULL DEFAULT 0, session_id TEXT NOT NULL,
102
105
  session_ids TEXT NOT NULL, lineage TEXT,
103
106
  source TEXT NOT NULL DEFAULT 'tool', origin TEXT NOT NULL DEFAULT 'agent',
104
- base_kind TEXT NOT NULL DEFAULT 'known');
107
+ base_kind TEXT NOT NULL DEFAULT 'known',
108
+ evidence TEXT NOT NULL DEFAULT 'snapshot', verdict TEXT NOT NULL DEFAULT 'changed');
105
109
  CREATE TABLE IF NOT EXISTS pending_blocks (
106
110
  entry_id TEXT NOT NULL, block_id TEXT NOT NULL, decision TEXT NOT NULL,
107
111
  PRIMARY KEY(entry_id,block_id));
@@ -109,9 +113,10 @@ CREATE TABLE IF NOT EXISTS pending_ops (
109
113
  operation_id TEXT PRIMARY KEY, request TEXT NOT NULL, state TEXT NOT NULL,
110
114
  result TEXT, undo TEXT);
111
115
  CREATE TABLE IF NOT EXISTS pending_history (
112
- id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, entry_id TEXT,
113
- snapshot TEXT NOT NULL, created_at INTEGER NOT NULL,
114
- state TEXT NOT NULL DEFAULT 'applied');
116
+ entry_id TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL,
117
+ earlier TEXT NOT NULL DEFAULT 'file', baseline TEXT NOT NULL, content TEXT NOT NULL,
118
+ digest TEXT NOT NULL, wrote INTEGER NOT NULL DEFAULT 0,
119
+ state TEXT NOT NULL DEFAULT 'applied', merged_at INTEGER NOT NULL);
115
120
  `
116
121
 
117
122
  /**
@@ -129,6 +134,20 @@ function migrateProvenance(db: DatabaseSync): void {
129
134
  if (!names.has('base_kind')) db.exec("ALTER TABLE pending_entries ADD COLUMN base_kind TEXT NOT NULL DEFAULT 'known'")
130
135
  }
131
136
 
137
+ /**
138
+ * @author ddj 2026年11月25号
139
+ * @description: v4 → v5:给条目补证据强度与结局两列。旧行按默认值读成「快照 / 真实改动」,
140
+ * 与 v4 的语义一致,不需要回填。
141
+ * @param db 已打开的工作区库
142
+ * @returns 无
143
+ */
144
+ function migrateEvidence(db: DatabaseSync): void {
145
+ const columns = db.prepare('PRAGMA table_info(pending_entries)').all() as Row[]
146
+ const names = new Set(columns.map((column) => String(column.name)))
147
+ if (!names.has('evidence')) db.exec("ALTER TABLE pending_entries ADD COLUMN evidence TEXT NOT NULL DEFAULT 'snapshot'")
148
+ if (!names.has('verdict')) db.exec("ALTER TABLE pending_entries ADD COLUMN verdict TEXT NOT NULL DEFAULT 'changed'")
149
+ }
150
+
132
151
  /**
133
152
  * @author ddj 2026年10月29号
134
153
  * @description: v1 历史表补 state 列(rebuild 成本高于一次 ALTER)。
@@ -141,6 +160,81 @@ function migrateHistory(db: DatabaseSync): void {
141
160
  db.exec("ALTER TABLE pending_history ADD COLUMN state TEXT NOT NULL DEFAULT 'applied'")
142
161
  }
143
162
 
163
+ /**
164
+ * @author ddj 2026年11月25号
165
+ * @description: v5 → v6:把「每次决定一行」的撤销栈折成「每条路径一行」。
166
+ * 同一路径只保留最近一次判定,用被替换掉的那一侧全文作撤销依据;其余旧行直接丢弃,
167
+ * 这是合并语义:一段代码改三次仍然只有一份差异,不再堆三次快照。
168
+ * @param db 已打开的工作区库
169
+ * @returns 无
170
+ */
171
+ function migrateHistoryMerge(db: DatabaseSync): void {
172
+ const columns = db.prepare('PRAGMA table_info(pending_history)').all() as Row[]
173
+ if (!columns.some((column) => column.name === 'snapshot')) return
174
+ const rows = db.prepare(`SELECT h.entry_id, h.snapshot, h.created_at, h.state, e.path AS entry_path
175
+ FROM pending_history h LEFT JOIN pending_entries e ON e.id = h.entry_id
176
+ WHERE h.id IN (SELECT MAX(id) FROM pending_history GROUP BY entry_id)`).all() as Row[]
177
+ db.exec(`CREATE TABLE IF NOT EXISTS pending_history_v6 (
178
+ entry_id TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL,
179
+ earlier TEXT NOT NULL DEFAULT 'file', baseline TEXT NOT NULL, content TEXT NOT NULL,
180
+ digest TEXT NOT NULL, wrote INTEGER NOT NULL DEFAULT 0,
181
+ state TEXT NOT NULL DEFAULT 'applied', merged_at INTEGER NOT NULL)`)
182
+ const insert = db.prepare(`INSERT OR REPLACE INTO pending_history_v6
183
+ (entry_id,path,kind,earlier,baseline,content,digest,wrote,state,merged_at) VALUES(?,?,?,?,?,?,?,?,?,?)`)
184
+ for (const row of rows) {
185
+ const folded = foldLegacySnapshot(row)
186
+ if (!folded) continue
187
+ insert.run(String(row.entry_id), String(row.entry_path ?? folded.path), folded.kind, folded.earlier,
188
+ folded.baseline, folded.content, digestOf(folded.content), folded.wrote ? 1 : 0,
189
+ row.state === 'undone' ? 'undone' : 'applied', Number(row.created_at) || Date.now())
190
+ }
191
+ db.exec('DROP TABLE pending_history')
192
+ db.exec('ALTER TABLE pending_history_v6 RENAME TO pending_history')
193
+ }
194
+
195
+ /**
196
+ * @private
197
+ * @author ddj 2026年11月25号
198
+ * @description: 把旧的「before/after 条目快照」还原成一条合并撤销行;解析不了就丢弃。
199
+ * @param row 旧历史行
200
+ * @returns 折叠结果,无法解析时为 null
201
+ */
202
+ function foldLegacySnapshot(row: Row): { kind: 'keep' | 'revert'; earlier: string; baseline: string; content: string; wrote: boolean; path: string } | null {
203
+ try {
204
+ const snapshot = JSON.parse(String(row.snapshot)) as {
205
+ before?: { entry?: { oldText?: unknown; newText?: unknown; earlierVersion?: unknown; path?: unknown } }
206
+ after?: { entry?: { oldText?: unknown; newText?: unknown } }
207
+ wrote?: unknown
208
+ }
209
+ const before = snapshot.before?.entry
210
+ const after = snapshot.after?.entry
211
+ if (!before || !after) return null
212
+ const baseline = String(before.oldText ?? '')
213
+ const content = String(before.newText ?? '')
214
+ return {
215
+ kind: String(after.oldText ?? '') !== baseline ? 'keep' : 'revert',
216
+ earlier: String(before.earlierVersion ?? 'file') === 'none' ? 'none' : 'file',
217
+ baseline,
218
+ content,
219
+ wrote: snapshot.wrote === true,
220
+ path: String(before.path ?? ''),
221
+ }
222
+ } catch {
223
+ return null
224
+ }
225
+ }
226
+
227
+ /**
228
+ * @private
229
+ * @author ddj 2026年11月25号
230
+ * @description: 撤销行内容指纹,用于重试幂等与诊断,不参与判定。
231
+ * @param text 被替换掉的那一侧全文
232
+ * @returns 十六进制摘要
233
+ */
234
+ function digestOf(text: string): string {
235
+ return createHash('sha256').update(text).digest('hex').slice(0, 32)
236
+ }
237
+
144
238
  /**
145
239
  * @author ddj 2026年10月29号
146
240
  * @description: 读出全部待审条目,按更新时间升序。
@@ -152,6 +246,21 @@ export function loadEntries(cwd: string): StoredEntry[] {
152
246
  return rows.map((row) => ({ entry: entryOfRow(row), flags: flagsOfRow(row) }))
153
247
  }
154
248
 
249
+ /**
250
+ * @author ddj 2026年11月25号
251
+ * @description: 按身份读单条条目:watch 批次快照可能早于工具落库,重读一条比整表便宜。
252
+ * @param cwd 工作区
253
+ * @param id 条目身份(后端进程路径)
254
+ * @returns 条目与标记,缺失时 undefined
255
+ */
256
+ export function loadEntry(cwd: string, id: string): StoredEntry | undefined {
257
+ const db = pendingDb(cwd)
258
+ // Windows 上盘符与路径大小写不敏感:精确命中失败再按 NOCASE 找一次。
259
+ const row = (db.prepare('SELECT * FROM pending_entries WHERE id=?').get(id)
260
+ ?? db.prepare('SELECT * FROM pending_entries WHERE id=? COLLATE NOCASE').get(id)) as Row | undefined
261
+ return row ? { entry: entryOfRow(row), flags: flagsOfRow(row) } : undefined
262
+ }
263
+
155
264
  /**
156
265
  * @author ddj 2026年10月29号
157
266
  * @description: 写入或更新一条条目(含标记),单条原子完成。
@@ -175,17 +284,19 @@ function upsertEntry(db: DatabaseSync, cwd: string, stored: StoredEntry): void {
175
284
  const { entry, flags } = stored
176
285
  db.prepare(`INSERT INTO pending_entries
177
286
  (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage,
178
- source,origin,base_kind)
179
- VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
287
+ source,origin,base_kind,evidence,verdict)
288
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
180
289
  ON CONFLICT(id) DO UPDATE SET path=excluded.path,earlier=excluded.earlier,old_text=excluded.old_text,
181
290
  new_text=excluded.new_text,updated_at=excluded.updated_at,unseen=excluded.unseen,missing=excluded.missing,
182
291
  diverged=excluded.diverged,oversized=excluded.oversized,revision=excluded.revision,
183
292
  session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage,
184
- source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind`)
293
+ source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind,
294
+ evidence=excluded.evidence,verdict=excluded.verdict`)
185
295
  .run(entry.id, entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt,
186
296
  entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0,
187
297
  flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null,
188
- entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known')
298
+ entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known',
299
+ entry.evidence ?? 'snapshot', entry.verdict ?? 'changed')
189
300
  bumpVersion(cwd)
190
301
  }
191
302
 
@@ -296,90 +407,106 @@ export function writeOp(
296
407
  }
297
408
 
298
409
  /**
299
- * @author ddj 2026年10月29号
300
- * @description: 追加一条撤销栈记录,并截断重做分支(新决定之后旧的"已撤销"记录不能再重做)。
410
+ * @author ddj 2026年10月29号 / 2026年11月25号
411
+ * @description: 写一条撤销行(同一路径覆盖写)。
301
412
  * @param cwd 工作区
302
- * @param kind 操作种类
303
- * @param entryId 涉及的条目
304
- * @param snapshot 可重放快照
413
+ * @param record 撤销行内容
305
414
  * @param now 时间
306
415
  * @returns 无
307
416
  */
308
- export function pushHistory(cwd: string, kind: string, entryId: string, snapshot: string, now: number): void {
309
- insertHistory(pendingDb(cwd), kind, entryId, snapshot, now)
417
+ export function pushHistory(cwd: string, record: HistoryRecord, now: number): void {
418
+ insertHistory(pendingDb(cwd), record, now)
310
419
  }
311
420
 
312
421
  /**
313
422
  * @private
314
- * @author ddj 2026年11月03号
315
- * @description: 在给定连接上追加撤销栈记录并截断重做分支,供单条与批量两个入口复用。
423
+ * @author ddj 2026年11月03号 / 2026年11月25号
424
+ * @description: 写一条合并撤销行:同一路径永远只有一行,新判定覆盖写,不再堆叠。
316
425
  * @param db 已迁移连接(可能已在事务中)
317
- * @param kind 操作种类
318
- * @param entryId 涉及的条目
319
- * @param snapshot 可重放快照
426
+ * @param record 撤销行内容
320
427
  * @param now 时间
321
428
  * @returns 无
322
429
  */
323
- function insertHistory(db: DatabaseSync, kind: string, entryId: string, snapshot: string, now: number): void {
324
- db.prepare("DELETE FROM pending_history WHERE state='undone'").run()
325
- db.prepare("INSERT INTO pending_history(kind,entry_id,snapshot,created_at,state) VALUES(?,?,?,?,'applied')")
326
- .run(kind, entryId, snapshot, now)
430
+ function insertHistory(db: DatabaseSync, record: HistoryRecord, now: number): void {
431
+ db.prepare(`INSERT INTO pending_history(entry_id,path,kind,earlier,baseline,content,digest,wrote,state,merged_at)
432
+ VALUES(?,?,?,?,?,?,?,?,'applied',?)
433
+ ON CONFLICT(entry_id) DO UPDATE SET path=excluded.path,kind=excluded.kind,earlier=excluded.earlier,
434
+ baseline=excluded.baseline,content=excluded.content,digest=excluded.digest,wrote=excluded.wrote,
435
+ state='applied',merged_at=excluded.merged_at`)
436
+ .run(record.entryId, record.path, record.kind, record.earlier, record.baseline, record.content,
437
+ digestOf(record.content), record.wrote ? 1 : 0, now)
327
438
  }
328
439
 
329
440
  /**
330
- * @author ddj 2026年10月30号
331
- * @description: 取最近一条仍生效的历史记录,撤销就作用在它上面。
441
+ * @author ddj 2026年10月30号 / 2026年11月25号
442
+ * @description: 取最近一条仍生效的撤销行,撤销就作用在它上面。
332
443
  * @param cwd 工作区
333
444
  * @returns 记录或 undefined
334
445
  */
335
446
  export function latestApplied(cwd: string): HistoryRow | undefined {
336
447
  const row = pendingDb(cwd).prepare(
337
- "SELECT id,kind,entry_id,snapshot FROM pending_history WHERE state='applied' ORDER BY id DESC LIMIT 1",
448
+ "SELECT * FROM pending_history WHERE state='applied' ORDER BY merged_at DESC LIMIT 1",
338
449
  ).get() as Row | undefined
339
450
  return row ? rowOfHistory(row) : undefined
340
451
  }
341
452
 
342
453
  /**
343
- * @author ddj 2026年10月30号
344
- * @description: 取最早一条被撤销的记录,重做按"撤销的逆序"重新生效。
454
+ * @author ddj 2026年10月30号 / 2026年11月25号
455
+ * @description: 取最早一条被撤销的记录,重做按「撤销的逆序」重新生效。
345
456
  * @param cwd 工作区
346
457
  * @returns 记录或 undefined
347
458
  */
348
459
  export function earliestUndone(cwd: string): HistoryRow | undefined {
349
460
  const row = pendingDb(cwd).prepare(
350
- "SELECT id,kind,entry_id,snapshot FROM pending_history WHERE state='undone' ORDER BY id ASC LIMIT 1",
461
+ "SELECT * FROM pending_history WHERE state='undone' ORDER BY merged_at ASC LIMIT 1",
351
462
  ).get() as Row | undefined
352
463
  return row ? rowOfHistory(row) : undefined
353
464
  }
354
465
 
355
466
  /**
356
- * @author ddj 2026年10月30号
357
- * @description: 翻转一条历史记录的生效状态。
467
+ * @author ddj 2026年10月30号 / 2026年11月25号
468
+ * @description: 翻转一条撤销行的生效状态。
358
469
  * @param cwd 工作区
359
- * @param id 记录主键
470
+ * @param entryId 条目身份(一条路径一行)
360
471
  * @param state applied / undone
361
472
  * @returns 无
362
473
  */
363
- export function setHistoryState(cwd: string, id: number, state: 'applied' | 'undone'): void {
364
- pendingDb(cwd).prepare('UPDATE pending_history SET state=? WHERE id=?').run(state, id)
474
+ export function setHistoryState(cwd: string, entryId: string, state: 'applied' | 'undone'): void {
475
+ pendingDb(cwd).prepare('UPDATE pending_history SET state=? WHERE entry_id=?').run(state, entryId)
365
476
  }
366
477
 
367
478
  /**
368
- * @author ddj 2026年10月30号
369
- * @description: 把数据库行还原成历史记录。
479
+ * @author ddj 2026年10月30号 / 2026年11月25号
480
+ * @description: 把数据库行还原成撤销记录。
370
481
  * @param row 数据库行
371
482
  * @returns 记录
372
483
  */
373
484
  function rowOfHistory(row: Row): HistoryRow {
374
- return { id: Number(row.id), kind: String(row.kind), entryId: String(row.entry_id), snapshot: String(row.snapshot) }
485
+ return {
486
+ entryId: String(row.entry_id), path: String(row.path),
487
+ kind: String(row.kind) === 'revert' ? 'revert' : 'keep',
488
+ earlier: String(row.earlier ?? 'file') === 'none' ? 'none' : 'file',
489
+ baseline: String(row.baseline), content: String(row.content),
490
+ wrote: Number(row.wrote) === 1, state: row.state === 'undone' ? 'undone' : 'applied',
491
+ mergedAt: Number(row.merged_at) || 0,
492
+ }
375
493
  }
376
494
 
377
- /** 历史记录行形态(快照为 JSON 文本)。 */
378
- export interface HistoryRow {
379
- id: number
380
- kind: string
495
+ /** 一条撤销行的内容:被这次判定替换掉的两侧全文,用于撤销与重做。 */
496
+ export interface HistoryRecord {
381
497
  entryId: string
382
- snapshot: string
498
+ path: string
499
+ kind: 'keep' | 'revert'
500
+ earlier: 'file' | 'none'
501
+ baseline: string
502
+ content: string
503
+ wrote: boolean
504
+ }
505
+
506
+ /** 撤销行形态(一条路径一行)。 */
507
+ export interface HistoryRow extends HistoryRecord {
508
+ state: 'applied' | 'undone'
509
+ mergedAt: number
383
510
  }
384
511
 
385
512
  /**
@@ -408,6 +535,8 @@ function entryOfRow(row: Row): PendingEntry {
408
535
  source: sourceOfRow(row),
409
536
  origin: originOfRow(row),
410
537
  baseKind: baseKindOfRow(row),
538
+ evidence: evidenceOfRow(row),
539
+ verdict: verdictOfRow(row),
411
540
  }
412
541
  if (Number(row.unseen) === 1) entry.unseen = true
413
542
  if (lineage !== undefined) entry.lineage = lineage
@@ -448,7 +577,31 @@ function originOfRow(row: Row): PendingOrigin {
448
577
  */
449
578
  function baseKindOfRow(row: Row): PendingBaseKind {
450
579
  const value = String(row.base_kind ?? 'known')
451
- return value === 'absent' || value === 'vcs' || value === 'unknown' ? value : 'known'
580
+ return value === 'absent' || value === 'vcs' || value === 'normalized' || value === 'unknown' ? value : 'known'
581
+ }
582
+
583
+ /**
584
+ * @private
585
+ * @author ddj 2026年11月25号
586
+ * @description: 读证据强度列;v4 旧库升级后该列有默认值,异常值按 `snapshot` 处理。
587
+ * @param row 数据库行
588
+ * @returns 证据强度
589
+ */
590
+ function evidenceOfRow(row: Row): PendingEvidence {
591
+ const value = String(row.evidence ?? 'snapshot')
592
+ return value === 'authoritative' || value === 'receipt' || value === 'none' ? value : 'snapshot'
593
+ }
594
+
595
+ /**
596
+ * @private
597
+ * @author ddj 2026年11月25号
598
+ * @description: 读调用结局列;异常值按 `changed` 处理(旧条目的语义就是真实改动)。
599
+ * @param row 数据库行
600
+ * @returns 调用结局
601
+ */
602
+ function verdictOfRow(row: Row): PendingVerdict {
603
+ const value = String(row.verdict ?? 'changed')
604
+ return value === 'noop' || value === 'failed' || value === 'unverified' ? value : 'changed'
452
605
  }
453
606
 
454
607
  /**
@@ -466,13 +619,12 @@ function flagsOfRow(row: Row): PendingFlags {
466
619
  }
467
620
  }
468
621
 
469
- /** 批量 Keep 的一条落库记录:stored 提供 CAS 依据与撤销快照 before,next 是推进后的条目。 */
622
+ /** 批量 Keep 的一条落库记录:stored 提供 CAS 依据与撤销依据,next 是推进后的条目。 */
470
623
  export interface KeepRecord {
471
624
  entryId: string
472
625
  stored: StoredEntry
473
626
  next: StoredEntry
474
627
  blocks: { id: string; decision: string }[]
475
- snapshot: string
476
628
  }
477
629
 
478
630
  /**
@@ -489,7 +641,8 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
489
641
  const db = pendingDb(cwd)
490
642
  const skipped: { id: string; reason: string }[] = []
491
643
  const advance = db.prepare(`UPDATE pending_entries SET path=?,earlier=?,old_text=?,new_text=?,updated_at=?,unseen=?,
492
- missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?
644
+ missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?,
645
+ evidence=?,verdict=?
493
646
  WHERE id=? AND revision=?`)
494
647
 
495
648
  db.exec('BEGIN IMMEDIATE')
@@ -502,6 +655,7 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
502
655
  flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds),
503
656
  entry.lineage ? JSON.stringify(entry.lineage) : null,
504
657
  entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known',
658
+ entry.evidence ?? 'snapshot', entry.verdict ?? 'changed',
505
659
  record.entryId, expected)
506
660
  // 读条目到落库之间被别的决定推进过:只放弃这一条
507
661
  if (changed.changes !== 1) {
@@ -509,7 +663,16 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
509
663
  continue
510
664
  }
511
665
  writeBlocks(db, record.entryId, record.blocks)
512
- insertHistory(db, 'decide', record.entryId, record.snapshot, Date.now())
666
+ // 撤销行每条路径只留一行:批量 Keep 也按同一口径覆盖写,不再追加
667
+ insertHistory(db, {
668
+ entryId: record.entryId,
669
+ path: record.stored.entry.path,
670
+ kind: 'keep',
671
+ earlier: record.stored.entry.earlierVersion,
672
+ baseline: record.stored.entry.oldText,
673
+ content: record.stored.entry.newText,
674
+ wrote: false,
675
+ }, Date.now())
513
676
  }
514
677
  db.exec('COMMIT')
515
678
  if (records.length) bumpVersion(cwd)