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
package/lib/index.js CHANGED
@@ -6,8 +6,9 @@ import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { DatabaseSync } from "node:sqlite";
9
- import { Buffer as Buffer$1 } from "node:buffer";
10
9
  import { execFile, spawn, spawnSync } from "node:child_process";
10
+ import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
11
+ import { Buffer as Buffer$1 } from "node:buffer";
11
12
  import z from "@deepseek-ai/schemastery";
12
13
  import { inflateRawSync } from "node:zlib";
13
14
  import { StringDecoder } from "node:string_decoder";
@@ -1113,7 +1114,7 @@ const ROUTE_PREFIX = "/edrv";
1113
1114
  /** Monaco 静态资源前缀。 */
1114
1115
  const VENDOR_PREFIX = "/edrv/vendor";
1115
1116
  /** 稳定短哈希(cwd → 缓存文件名段;sha1 截断,跨运行稳定)。 */
1116
- function hashOf(text) {
1117
+ function hashOf$1(text) {
1117
1118
  return createHash("sha1").update(String(text)).digest("hex").slice(0, 16);
1118
1119
  }
1119
1120
  /**
@@ -1208,7 +1209,7 @@ function pluginLogRoot(home = dshHome()) {
1208
1209
  }
1209
1210
  /** 每工作区树缓存文件(工作区级:workspace/<id>/tree.v<schema>.json,文件名含版本便于 sweep)。 */
1210
1211
  function treeCacheFile(cwd, home = dshHome(), schema = 1) {
1211
- return join(workspaceCacheDir(hashOf(cwd), home), "tree.v" + schema + ".json");
1212
+ return join(workspaceCacheDir(hashOf$1(cwd), home), "tree.v" + schema + ".json");
1212
1213
  }
1213
1214
  /**
1214
1215
  * 每工作区 UI 状态镜像文件(工作区级:workspace/<id>/ui.v<schema>.json)。
@@ -1220,7 +1221,7 @@ function treeCacheFile(cwd, home = dshHome(), schema = 1) {
1220
1221
  * @returns UI 状态镜像文件绝对路径
1221
1222
  */
1222
1223
  function uiStateFile(cwd, home = dshHome(), schema = 1) {
1223
- return join(workspaceCacheDir(hashOf(cwd), home), "ui.v" + schema + ".json");
1224
+ return join(workspaceCacheDir(hashOf$1(cwd), home), "ui.v" + schema + ".json");
1224
1225
  }
1225
1226
  /**
1226
1227
  * 用户级 UI 状态镜像文件(跨工作区共享:user/ui-globals.v<schema>.json)。
@@ -1235,7 +1236,7 @@ function uiGlobalsFile(home = dshHome(), schema = 1) {
1235
1236
  }
1236
1237
  /** 每工作区 debug 日志文件(用户级日志根下,按 cwd hash 隔离)。 */
1237
1238
  function debugLogFile(cwd, home = dshHome()) {
1238
- return join(pluginLogRoot(home), "debug." + hashOf(cwd) + ".log");
1239
+ return join(pluginLogRoot(home), "debug." + hashOf$1(cwd) + ".log");
1239
1240
  }
1240
1241
  /**
1241
1242
  * 每工作区归档数据库(用户数据,不受缓存清理预算约束)。
@@ -1245,7 +1246,7 @@ function debugLogFile(cwd, home = dshHome()) {
1245
1246
  * @returns 归档数据库绝对路径
1246
1247
  */
1247
1248
  function archiveDbFile(cwd, home = dshHome()) {
1248
- return join(home, PLUGIN_ID, "data", "archive", hashOf(cwd) + ".sqlite");
1249
+ return join(home, PLUGIN_ID, "data", "archive", hashOf$1(cwd) + ".sqlite");
1249
1250
  }
1250
1251
  /**
1251
1252
  * 快捷菜单配置文本(用户数据,不受缓存清理预算约束,跨工作区共享一份)。
@@ -3073,6 +3074,13 @@ const SOURCE_RANK = {
3073
3074
  scan: 2,
3074
3075
  vcs: 1
3075
3076
  };
3077
+ /** 证据强度:回执说过的话比自己的快照可信,快照又胜过没有任何依据。 */
3078
+ const EVIDENCE_RANK = {
3079
+ authoritative: 4,
3080
+ receipt: 3,
3081
+ snapshot: 2,
3082
+ none: 1
3083
+ };
3076
3084
  /**
3077
3085
  * @author ddj 2026-11-24
3078
3086
  * @description: Host 侧的路径比较键:盘符恒折叠大小写,其余按运行平台折叠。
@@ -3104,29 +3112,56 @@ function strongerSource(earlier, later) {
3104
3112
  return SOURCE_RANK[left] >= SOURCE_RANK[right] ? left : right;
3105
3113
  }
3106
3114
  /**
3107
- * @author ddj 2026-11-24
3108
- * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销。
3115
+ * @author ddj 2026年11月25号
3116
+ * @description: 合并证据强度:回执胜过快照,同级保留首次值。
3117
+ * @param earlier 已落库证据(可为空)
3118
+ * @param later 本次证据
3119
+ * @returns 应当落库的证据强度
3120
+ */
3121
+ function strongerEvidence(earlier, later) {
3122
+ const left = earlier ?? "snapshot";
3123
+ const right = later ?? "snapshot";
3124
+ return EVIDENCE_RANK[left] >= EVIDENCE_RANK[right] ? left : right;
3125
+ }
3126
+ /**
3127
+ * @author ddj 2026年11月25号
3128
+ * @description: 证据徽标文案;旧条目没有该字段时按快照处理。
3129
+ * @param evidence 证据强度
3130
+ * @returns 展示文案
3131
+ */
3132
+ function evidenceLabelOf(evidence) {
3133
+ if (evidence === "authoritative") return "回执已核";
3134
+ if (evidence === "receipt") return "回执对账";
3135
+ if (evidence === "none") return "无回执";
3136
+ return "快照推断";
3137
+ }
3138
+ /**
3139
+ * @author ddj 2026-11-24 / 2026年11月25号
3140
+ * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销;归一基线要确认。
3109
3141
  * @param origin 归属
3110
3142
  * @param baseKind 基线与可信度
3111
3143
  * @returns 可直接撤销 / 需确认 / 禁止
3112
3144
  */
3113
3145
  function revertPolicyOf(origin, baseKind) {
3114
- if ((baseKind ?? "known") === "unknown") return "blocked";
3146
+ const base = baseKind ?? "known";
3147
+ if (base === "unknown") return "blocked";
3148
+ if (base === "normalized") return "confirm";
3115
3149
  return (origin ?? "agent") === "agent" ? "direct" : "confirm";
3116
3150
  }
3117
3151
  /**
3118
- * @author ddj 2026-11-24
3119
- * @description: 条目来源徽标文案;官方行没有徽标。
3152
+ * @author ddj 2026-11-24 / 2026年11月25号
3153
+ * @description: 条目来源徽标文案;官方行没有徽标,待审条目在来源后附证据强度。
3120
3154
  * @param entry 待审条目的来源字段
3121
3155
  * @returns 展示文案
3122
3156
  */
3123
3157
  function sourceLabelOf(entry) {
3124
3158
  const source = entry.source ?? "tool";
3125
3159
  const origin = entry.origin ?? "agent";
3126
- if (origin === "agent") return source + " · agent";
3127
- if (origin === "editor") return "编辑器保存";
3128
- if (origin === "vcs") return "版本库同步";
3129
- return source + " · 外部";
3160
+ const badge = " · " + evidenceLabelOf(entry.evidence);
3161
+ if (origin === "agent") return source + " · agent" + badge;
3162
+ if (origin === "editor") return "编辑器保存" + badge;
3163
+ if (origin === "vcs") return "版本库同步" + badge;
3164
+ return source + " · 外部" + badge;
3130
3165
  }
3131
3166
  /**
3132
3167
  * 创建窗口注册表(不依赖 Host,可单测)。
@@ -3309,10 +3344,22 @@ function pendingItemOf(item, cwd) {
3309
3344
  revision: item.revision,
3310
3345
  current: true
3311
3346
  };
3312
- if (item.settled !== true) row.sourceLabel = sourceLabelOf(item);
3347
+ if (item.settled !== true) row.sourceLabel = withNote$1(sourceLabelOf(item), item.note);
3313
3348
  return row;
3314
3349
  }
3315
3350
  /**
3351
+ * @private
3352
+ * @author ddj 2026年11月25号
3353
+ * @description: 把只读说明接在来源徽标后面;列表里只给前 40 字,避免长句刷屏。
3354
+ * @param label 来源徽标
3355
+ * @param note 只读说明
3356
+ * @returns 展示文案
3357
+ */
3358
+ function withNote$1(label, note) {
3359
+ if (!note) return label;
3360
+ return label + " · 备注:" + (note.length > 40 ? note.slice(0, 40) + "…" : note);
3361
+ }
3362
+ /**
3316
3363
  * @author ddj 2026年10月29号
3317
3364
  * @description: 待审详情转面板详情;Revert 映射到面板的 Undo 能力位。
3318
3365
  * @param detail 待审详情
@@ -3425,8 +3472,8 @@ function mergedPage(official, pending, cwd) {
3425
3472
  }
3426
3473
  //#endregion
3427
3474
  //#region src/pending/persist.ts
3428
- /** 待审库版本号,写进 metadata 便于日后迁移。v4 给条目加了采集来源与基线可信度。 */
3429
- const SCHEMA_VERSION = "4";
3475
+ /** 待审库版本号,写进 metadata 便于日后迁移。v6 把撤销栈改成「一条路径一行」。 */
3476
+ const SCHEMA_VERSION = "6";
3430
3477
  /** 工作区待审版本号:条目一落库就自增,供客户端轮询判断是否需要重读列表。 */
3431
3478
  const versions = /* @__PURE__ */ new Map();
3432
3479
  /**
@@ -3463,7 +3510,9 @@ function pendingDb(cwd) {
3463
3510
  try {
3464
3511
  db.exec(DDL);
3465
3512
  migrateHistory(db);
3513
+ migrateHistoryMerge(db);
3466
3514
  migrateProvenance(db);
3515
+ migrateEvidence(db);
3467
3516
  db.prepare("INSERT INTO metadata(name,value) VALUES('pending_schema',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value").run(SCHEMA_VERSION);
3468
3517
  db.exec("COMMIT");
3469
3518
  } catch (error) {
@@ -3482,7 +3531,8 @@ CREATE TABLE IF NOT EXISTS pending_entries (
3482
3531
  revision INTEGER NOT NULL DEFAULT 0, session_id TEXT NOT NULL,
3483
3532
  session_ids TEXT NOT NULL, lineage TEXT,
3484
3533
  source TEXT NOT NULL DEFAULT 'tool', origin TEXT NOT NULL DEFAULT 'agent',
3485
- base_kind TEXT NOT NULL DEFAULT 'known');
3534
+ base_kind TEXT NOT NULL DEFAULT 'known',
3535
+ evidence TEXT NOT NULL DEFAULT 'snapshot', verdict TEXT NOT NULL DEFAULT 'changed');
3486
3536
  CREATE TABLE IF NOT EXISTS pending_blocks (
3487
3537
  entry_id TEXT NOT NULL, block_id TEXT NOT NULL, decision TEXT NOT NULL,
3488
3538
  PRIMARY KEY(entry_id,block_id));
@@ -3490,9 +3540,10 @@ CREATE TABLE IF NOT EXISTS pending_ops (
3490
3540
  operation_id TEXT PRIMARY KEY, request TEXT NOT NULL, state TEXT NOT NULL,
3491
3541
  result TEXT, undo TEXT);
3492
3542
  CREATE TABLE IF NOT EXISTS pending_history (
3493
- id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, entry_id TEXT,
3494
- snapshot TEXT NOT NULL, created_at INTEGER NOT NULL,
3495
- state TEXT NOT NULL DEFAULT 'applied');
3543
+ entry_id TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL,
3544
+ earlier TEXT NOT NULL DEFAULT 'file', baseline TEXT NOT NULL, content TEXT NOT NULL,
3545
+ digest TEXT NOT NULL, wrote INTEGER NOT NULL DEFAULT 0,
3546
+ state TEXT NOT NULL DEFAULT 'applied', merged_at INTEGER NOT NULL);
3496
3547
  `;
3497
3548
  /**
3498
3549
  * @author ddj 2026-11-24
@@ -3509,6 +3560,19 @@ function migrateProvenance(db) {
3509
3560
  if (!names.has("base_kind")) db.exec("ALTER TABLE pending_entries ADD COLUMN base_kind TEXT NOT NULL DEFAULT 'known'");
3510
3561
  }
3511
3562
  /**
3563
+ * @author ddj 2026年11月25号
3564
+ * @description: v4 → v5:给条目补证据强度与结局两列。旧行按默认值读成「快照 / 真实改动」,
3565
+ * 与 v4 的语义一致,不需要回填。
3566
+ * @param db 已打开的工作区库
3567
+ * @returns 无
3568
+ */
3569
+ function migrateEvidence(db) {
3570
+ const columns = db.prepare("PRAGMA table_info(pending_entries)").all();
3571
+ const names = new Set(columns.map((column) => String(column.name)));
3572
+ if (!names.has("evidence")) db.exec("ALTER TABLE pending_entries ADD COLUMN evidence TEXT NOT NULL DEFAULT 'snapshot'");
3573
+ if (!names.has("verdict")) db.exec("ALTER TABLE pending_entries ADD COLUMN verdict TEXT NOT NULL DEFAULT 'changed'");
3574
+ }
3575
+ /**
3512
3576
  * @author ddj 2026年10月29号
3513
3577
  * @description: v1 历史表补 state 列(rebuild 成本高于一次 ALTER)。
3514
3578
  * @param db 已打开的工作区库
@@ -3519,6 +3583,71 @@ function migrateHistory(db) {
3519
3583
  db.exec("ALTER TABLE pending_history ADD COLUMN state TEXT NOT NULL DEFAULT 'applied'");
3520
3584
  }
3521
3585
  /**
3586
+ * @author ddj 2026年11月25号
3587
+ * @description: v5 → v6:把「每次决定一行」的撤销栈折成「每条路径一行」。
3588
+ * 同一路径只保留最近一次判定,用被替换掉的那一侧全文作撤销依据;其余旧行直接丢弃,
3589
+ * 这是合并语义:一段代码改三次仍然只有一份差异,不再堆三次快照。
3590
+ * @param db 已打开的工作区库
3591
+ * @returns 无
3592
+ */
3593
+ function migrateHistoryMerge(db) {
3594
+ if (!db.prepare("PRAGMA table_info(pending_history)").all().some((column) => column.name === "snapshot")) return;
3595
+ const rows = db.prepare(`SELECT h.entry_id, h.snapshot, h.created_at, h.state, e.path AS entry_path
3596
+ FROM pending_history h LEFT JOIN pending_entries e ON e.id = h.entry_id
3597
+ WHERE h.id IN (SELECT MAX(id) FROM pending_history GROUP BY entry_id)`).all();
3598
+ db.exec(`CREATE TABLE IF NOT EXISTS pending_history_v6 (
3599
+ entry_id TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL,
3600
+ earlier TEXT NOT NULL DEFAULT 'file', baseline TEXT NOT NULL, content TEXT NOT NULL,
3601
+ digest TEXT NOT NULL, wrote INTEGER NOT NULL DEFAULT 0,
3602
+ state TEXT NOT NULL DEFAULT 'applied', merged_at INTEGER NOT NULL)`);
3603
+ const insert = db.prepare(`INSERT OR REPLACE INTO pending_history_v6
3604
+ (entry_id,path,kind,earlier,baseline,content,digest,wrote,state,merged_at) VALUES(?,?,?,?,?,?,?,?,?,?)`);
3605
+ for (const row of rows) {
3606
+ const folded = foldLegacySnapshot(row);
3607
+ if (!folded) continue;
3608
+ insert.run(String(row.entry_id), String(row.entry_path ?? folded.path), folded.kind, folded.earlier, folded.baseline, folded.content, digestOf(folded.content), folded.wrote ? 1 : 0, row.state === "undone" ? "undone" : "applied", Number(row.created_at) || Date.now());
3609
+ }
3610
+ db.exec("DROP TABLE pending_history");
3611
+ db.exec("ALTER TABLE pending_history_v6 RENAME TO pending_history");
3612
+ }
3613
+ /**
3614
+ * @private
3615
+ * @author ddj 2026年11月25号
3616
+ * @description: 把旧的「before/after 条目快照」还原成一条合并撤销行;解析不了就丢弃。
3617
+ * @param row 旧历史行
3618
+ * @returns 折叠结果,无法解析时为 null
3619
+ */
3620
+ function foldLegacySnapshot(row) {
3621
+ try {
3622
+ const snapshot = JSON.parse(String(row.snapshot));
3623
+ const before = snapshot.before?.entry;
3624
+ const after = snapshot.after?.entry;
3625
+ if (!before || !after) return null;
3626
+ const baseline = String(before.oldText ?? "");
3627
+ const content = String(before.newText ?? "");
3628
+ return {
3629
+ kind: String(after.oldText ?? "") !== baseline ? "keep" : "revert",
3630
+ earlier: String(before.earlierVersion ?? "file") === "none" ? "none" : "file",
3631
+ baseline,
3632
+ content,
3633
+ wrote: snapshot.wrote === true,
3634
+ path: String(before.path ?? "")
3635
+ };
3636
+ } catch {
3637
+ return null;
3638
+ }
3639
+ }
3640
+ /**
3641
+ * @private
3642
+ * @author ddj 2026年11月25号
3643
+ * @description: 撤销行内容指纹,用于重试幂等与诊断,不参与判定。
3644
+ * @param text 被替换掉的那一侧全文
3645
+ * @returns 十六进制摘要
3646
+ */
3647
+ function digestOf(text) {
3648
+ return createHash("sha256").update(text).digest("hex").slice(0, 32);
3649
+ }
3650
+ /**
3522
3651
  * @author ddj 2026年10月29号
3523
3652
  * @description: 读出全部待审条目,按更新时间升序。
3524
3653
  * @param cwd 工作区
@@ -3531,6 +3660,21 @@ function loadEntries(cwd) {
3531
3660
  }));
3532
3661
  }
3533
3662
  /**
3663
+ * @author ddj 2026年11月25号
3664
+ * @description: 按身份读单条条目:watch 批次快照可能早于工具落库,重读一条比整表便宜。
3665
+ * @param cwd 工作区
3666
+ * @param id 条目身份(后端进程路径)
3667
+ * @returns 条目与标记,缺失时 undefined
3668
+ */
3669
+ function loadEntry(cwd, id) {
3670
+ const db = pendingDb(cwd);
3671
+ const row = db.prepare("SELECT * FROM pending_entries WHERE id=?").get(id) ?? db.prepare("SELECT * FROM pending_entries WHERE id=? COLLATE NOCASE").get(id);
3672
+ return row ? {
3673
+ entry: entryOfRow(row),
3674
+ flags: flagsOfRow(row)
3675
+ } : void 0;
3676
+ }
3677
+ /**
3534
3678
  * @author ddj 2026年10月29号
3535
3679
  * @description: 写入或更新一条条目(含标记),单条原子完成。
3536
3680
  * @param cwd 工作区
@@ -3552,13 +3696,14 @@ function upsertEntry(db, cwd, stored) {
3552
3696
  const { entry, flags } = stored;
3553
3697
  db.prepare(`INSERT INTO pending_entries
3554
3698
  (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage,
3555
- source,origin,base_kind)
3556
- VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
3699
+ source,origin,base_kind,evidence,verdict)
3700
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
3557
3701
  ON CONFLICT(id) DO UPDATE SET path=excluded.path,earlier=excluded.earlier,old_text=excluded.old_text,
3558
3702
  new_text=excluded.new_text,updated_at=excluded.updated_at,unseen=excluded.unseen,missing=excluded.missing,
3559
3703
  diverged=excluded.diverged,oversized=excluded.oversized,revision=excluded.revision,
3560
3704
  session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage,
3561
- source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind`).run(entry.id, entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt, entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0, flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null, entry.source ?? "tool", entry.origin ?? "agent", entry.baseKind ?? "known");
3705
+ source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind,
3706
+ evidence=excluded.evidence,verdict=excluded.verdict`).run(entry.id, entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt, entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0, flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null, entry.source ?? "tool", entry.origin ?? "agent", entry.baseKind ?? "known", entry.evidence ?? "snapshot", entry.verdict ?? "changed");
3562
3707
  bumpVersion(cwd);
3563
3708
  }
3564
3709
  /**
@@ -3646,76 +3791,80 @@ function writeOp(cwd, operationId, request, state, payload = {}) {
3646
3791
  result=COALESCE(excluded.result,pending_ops.result), undo=COALESCE(excluded.undo,pending_ops.undo)`).run(operationId, request, state, payload.result ?? null, payload.undo ?? null);
3647
3792
  }
3648
3793
  /**
3649
- * @author ddj 2026年10月29号
3650
- * @description: 追加一条撤销栈记录,并截断重做分支(新决定之后旧的"已撤销"记录不能再重做)。
3794
+ * @author ddj 2026年10月29号 / 2026年11月25号
3795
+ * @description: 写一条撤销行(同一路径覆盖写)。
3651
3796
  * @param cwd 工作区
3652
- * @param kind 操作种类
3653
- * @param entryId 涉及的条目
3654
- * @param snapshot 可重放快照
3797
+ * @param record 撤销行内容
3655
3798
  * @param now 时间
3656
3799
  * @returns 无
3657
3800
  */
3658
- function pushHistory(cwd, kind, entryId, snapshot, now) {
3659
- insertHistory(pendingDb(cwd), kind, entryId, snapshot, now);
3801
+ function pushHistory(cwd, record, now) {
3802
+ insertHistory(pendingDb(cwd), record, now);
3660
3803
  }
3661
3804
  /**
3662
3805
  * @private
3663
- * @author ddj 2026年11月03号
3664
- * @description: 在给定连接上追加撤销栈记录并截断重做分支,供单条与批量两个入口复用。
3806
+ * @author ddj 2026年11月03号 / 2026年11月25号
3807
+ * @description: 写一条合并撤销行:同一路径永远只有一行,新判定覆盖写,不再堆叠。
3665
3808
  * @param db 已迁移连接(可能已在事务中)
3666
- * @param kind 操作种类
3667
- * @param entryId 涉及的条目
3668
- * @param snapshot 可重放快照
3809
+ * @param record 撤销行内容
3669
3810
  * @param now 时间
3670
3811
  * @returns 无
3671
3812
  */
3672
- function insertHistory(db, kind, entryId, snapshot, now) {
3673
- db.prepare("DELETE FROM pending_history WHERE state='undone'").run();
3674
- db.prepare("INSERT INTO pending_history(kind,entry_id,snapshot,created_at,state) VALUES(?,?,?,?,'applied')").run(kind, entryId, snapshot, now);
3813
+ function insertHistory(db, record, now) {
3814
+ db.prepare(`INSERT INTO pending_history(entry_id,path,kind,earlier,baseline,content,digest,wrote,state,merged_at)
3815
+ VALUES(?,?,?,?,?,?,?,?,'applied',?)
3816
+ ON CONFLICT(entry_id) DO UPDATE SET path=excluded.path,kind=excluded.kind,earlier=excluded.earlier,
3817
+ baseline=excluded.baseline,content=excluded.content,digest=excluded.digest,wrote=excluded.wrote,
3818
+ state='applied',merged_at=excluded.merged_at`).run(record.entryId, record.path, record.kind, record.earlier, record.baseline, record.content, digestOf(record.content), record.wrote ? 1 : 0, now);
3675
3819
  }
3676
3820
  /**
3677
- * @author ddj 2026年10月30号
3678
- * @description: 取最近一条仍生效的历史记录,撤销就作用在它上面。
3821
+ * @author ddj 2026年10月30号 / 2026年11月25号
3822
+ * @description: 取最近一条仍生效的撤销行,撤销就作用在它上面。
3679
3823
  * @param cwd 工作区
3680
3824
  * @returns 记录或 undefined
3681
3825
  */
3682
3826
  function latestApplied(cwd) {
3683
- const row = pendingDb(cwd).prepare("SELECT id,kind,entry_id,snapshot FROM pending_history WHERE state='applied' ORDER BY id DESC LIMIT 1").get();
3827
+ const row = pendingDb(cwd).prepare("SELECT * FROM pending_history WHERE state='applied' ORDER BY merged_at DESC LIMIT 1").get();
3684
3828
  return row ? rowOfHistory(row) : void 0;
3685
3829
  }
3686
3830
  /**
3687
- * @author ddj 2026年10月30号
3688
- * @description: 取最早一条被撤销的记录,重做按"撤销的逆序"重新生效。
3831
+ * @author ddj 2026年10月30号 / 2026年11月25号
3832
+ * @description: 取最早一条被撤销的记录,重做按「撤销的逆序」重新生效。
3689
3833
  * @param cwd 工作区
3690
3834
  * @returns 记录或 undefined
3691
3835
  */
3692
3836
  function earliestUndone(cwd) {
3693
- const row = pendingDb(cwd).prepare("SELECT id,kind,entry_id,snapshot FROM pending_history WHERE state='undone' ORDER BY id ASC LIMIT 1").get();
3837
+ const row = pendingDb(cwd).prepare("SELECT * FROM pending_history WHERE state='undone' ORDER BY merged_at ASC LIMIT 1").get();
3694
3838
  return row ? rowOfHistory(row) : void 0;
3695
3839
  }
3696
3840
  /**
3697
- * @author ddj 2026年10月30号
3698
- * @description: 翻转一条历史记录的生效状态。
3841
+ * @author ddj 2026年10月30号 / 2026年11月25号
3842
+ * @description: 翻转一条撤销行的生效状态。
3699
3843
  * @param cwd 工作区
3700
- * @param id 记录主键
3844
+ * @param entryId 条目身份(一条路径一行)
3701
3845
  * @param state applied / undone
3702
3846
  * @returns 无
3703
3847
  */
3704
- function setHistoryState(cwd, id, state) {
3705
- pendingDb(cwd).prepare("UPDATE pending_history SET state=? WHERE id=?").run(state, id);
3848
+ function setHistoryState(cwd, entryId, state) {
3849
+ pendingDb(cwd).prepare("UPDATE pending_history SET state=? WHERE entry_id=?").run(state, entryId);
3706
3850
  }
3707
3851
  /**
3708
- * @author ddj 2026年10月30号
3709
- * @description: 把数据库行还原成历史记录。
3852
+ * @author ddj 2026年10月30号 / 2026年11月25号
3853
+ * @description: 把数据库行还原成撤销记录。
3710
3854
  * @param row 数据库行
3711
3855
  * @returns 记录
3712
3856
  */
3713
3857
  function rowOfHistory(row) {
3714
3858
  return {
3715
- id: Number(row.id),
3716
- kind: String(row.kind),
3717
3859
  entryId: String(row.entry_id),
3718
- snapshot: String(row.snapshot)
3860
+ path: String(row.path),
3861
+ kind: String(row.kind) === "revert" ? "revert" : "keep",
3862
+ earlier: String(row.earlier ?? "file") === "none" ? "none" : "file",
3863
+ baseline: String(row.baseline),
3864
+ content: String(row.content),
3865
+ wrote: Number(row.wrote) === 1,
3866
+ state: row.state === "undone" ? "undone" : "applied",
3867
+ mergedAt: Number(row.merged_at) || 0
3719
3868
  };
3720
3869
  }
3721
3870
  /**
@@ -3737,7 +3886,9 @@ function entryOfRow(row) {
3737
3886
  sessionIds: JSON.parse(String(row.session_ids)),
3738
3887
  source: sourceOfRow(row),
3739
3888
  origin: originOfRow(row),
3740
- baseKind: baseKindOfRow(row)
3889
+ baseKind: baseKindOfRow(row),
3890
+ evidence: evidenceOfRow(row),
3891
+ verdict: verdictOfRow(row)
3741
3892
  };
3742
3893
  if (Number(row.unseen) === 1) entry.unseen = true;
3743
3894
  if (lineage !== void 0) entry.lineage = lineage;
@@ -3774,7 +3925,29 @@ function originOfRow(row) {
3774
3925
  */
3775
3926
  function baseKindOfRow(row) {
3776
3927
  const value = String(row.base_kind ?? "known");
3777
- return value === "absent" || value === "vcs" || value === "unknown" ? value : "known";
3928
+ return value === "absent" || value === "vcs" || value === "normalized" || value === "unknown" ? value : "known";
3929
+ }
3930
+ /**
3931
+ * @private
3932
+ * @author ddj 2026年11月25号
3933
+ * @description: 读证据强度列;v4 旧库升级后该列有默认值,异常值按 `snapshot` 处理。
3934
+ * @param row 数据库行
3935
+ * @returns 证据强度
3936
+ */
3937
+ function evidenceOfRow(row) {
3938
+ const value = String(row.evidence ?? "snapshot");
3939
+ return value === "authoritative" || value === "receipt" || value === "none" ? value : "snapshot";
3940
+ }
3941
+ /**
3942
+ * @private
3943
+ * @author ddj 2026年11月25号
3944
+ * @description: 读调用结局列;异常值按 `changed` 处理(旧条目的语义就是真实改动)。
3945
+ * @param row 数据库行
3946
+ * @returns 调用结局
3947
+ */
3948
+ function verdictOfRow(row) {
3949
+ const value = String(row.verdict ?? "changed");
3950
+ return value === "noop" || value === "failed" || value === "unverified" ? value : "changed";
3778
3951
  }
3779
3952
  /**
3780
3953
  * @author ddj 2026年10月29号
@@ -3804,14 +3977,15 @@ function saveDecisions(cwd, records) {
3804
3977
  const db = pendingDb(cwd);
3805
3978
  const skipped = [];
3806
3979
  const advance = db.prepare(`UPDATE pending_entries SET path=?,earlier=?,old_text=?,new_text=?,updated_at=?,unseen=?,
3807
- missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?
3980
+ missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?,
3981
+ evidence=?,verdict=?
3808
3982
  WHERE id=? AND revision=?`);
3809
3983
  db.exec("BEGIN IMMEDIATE");
3810
3984
  try {
3811
3985
  for (const record of records) {
3812
3986
  const { entry, flags } = record.next;
3813
3987
  const expected = record.stored.flags.revision;
3814
- if (advance.run(entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt, entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0, flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null, entry.source ?? "tool", entry.origin ?? "agent", entry.baseKind ?? "known", record.entryId, expected).changes !== 1) {
3988
+ if (advance.run(entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt, entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0, flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null, entry.source ?? "tool", entry.origin ?? "agent", entry.baseKind ?? "known", entry.evidence ?? "snapshot", entry.verdict ?? "changed", record.entryId, expected).changes !== 1) {
3815
3989
  skipped.push({
3816
3990
  id: record.entryId,
3817
3991
  reason: "待审条目已变化,请重试"
@@ -3819,7 +3993,15 @@ function saveDecisions(cwd, records) {
3819
3993
  continue;
3820
3994
  }
3821
3995
  writeBlocks(db, record.entryId, record.blocks);
3822
- insertHistory(db, "decide", record.entryId, record.snapshot, Date.now());
3996
+ insertHistory(db, {
3997
+ entryId: record.entryId,
3998
+ path: record.stored.entry.path,
3999
+ kind: "keep",
4000
+ earlier: record.stored.entry.earlierVersion,
4001
+ baseline: record.stored.entry.oldText,
4002
+ content: record.stored.entry.newText,
4003
+ wrote: false
4004
+ }, Date.now());
3823
4005
  }
3824
4006
  db.exec("COMMIT");
3825
4007
  if (records.length) bumpVersion(cwd);
@@ -3829,6 +4011,75 @@ function saveDecisions(cwd, records) {
3829
4011
  throw error;
3830
4012
  }
3831
4013
  }
4014
+ /**
4015
+ * @public
4016
+ * @author ddj 2026-11-24
4017
+ * @description: 按条件清理待审条目(清幽灵记录用)。命中判定与删除在同一份读结果上做:
4018
+ * 有 pending_history 的条目(已经 Keep/Revert 过)一律保留,绝不按内容猜。
4019
+ * @param cwd 工作区
4020
+ * @param filter 筛选条件
4021
+ * @param dryRun 只数不删
4022
+ * @returns 命中、删除与保留条数
4023
+ * @throws 事务级异常整体回滚后抛出
4024
+ */
4025
+ function purgeEntries(cwd, filter = {}, dryRun = false) {
4026
+ const db = pendingDb(cwd);
4027
+ const sources = filter.sources && filter.sources.length ? new Set(filter.sources) : null;
4028
+ const baseKinds = filter.baseKinds && filter.baseKinds.length ? new Set(filter.baseKinds) : null;
4029
+ const before = typeof filter.before === "number" ? filter.before : null;
4030
+ const rows = db.prepare(`SELECT id, source, base_kind, updated_at,
4031
+ EXISTS(SELECT 1 FROM pending_history h WHERE h.entry_id = pending_entries.id) AS decided
4032
+ FROM pending_entries`).all();
4033
+ const hits = [];
4034
+ let kept = 0;
4035
+ for (const row of rows) {
4036
+ if (sources && !sources.has(String(row.source))) continue;
4037
+ if (baseKinds && !baseKinds.has(String(row.base_kind))) continue;
4038
+ if (before !== null && Number(row.updated_at) >= before) continue;
4039
+ if (Number(row.decided) === 1) kept += 1;
4040
+ else hits.push(String(row.id));
4041
+ }
4042
+ if (dryRun || !hits.length) return {
4043
+ matched: hits.length,
4044
+ removed: 0,
4045
+ kept
4046
+ };
4047
+ db.exec("BEGIN IMMEDIATE");
4048
+ try {
4049
+ const dropEntryRow = db.prepare("DELETE FROM pending_entries WHERE id=?");
4050
+ const dropBlockRows = db.prepare("DELETE FROM pending_blocks WHERE entry_id=?");
4051
+ for (const id of hits) {
4052
+ dropEntryRow.run(id);
4053
+ dropBlockRows.run(id);
4054
+ }
4055
+ db.exec("COMMIT");
4056
+ } catch (error) {
4057
+ if (db.isTransaction) db.exec("ROLLBACK");
4058
+ throw error;
4059
+ }
4060
+ bumpVersion(cwd);
4061
+ return {
4062
+ matched: hits.length,
4063
+ removed: hits.length,
4064
+ kept
4065
+ };
4066
+ }
4067
+ /**
4068
+ * @public
4069
+ * @author ddj 2026-11-24
4070
+ * @description: 回收已删行占用的页;失败只记日志,不影响已完成的删除。
4071
+ * @param cwd 工作区
4072
+ * @returns 耗时毫秒
4073
+ */
4074
+ function vacuumEntries(cwd) {
4075
+ const started = Date.now();
4076
+ try {
4077
+ pendingDb(cwd).exec("VACUUM");
4078
+ } catch (error) {
4079
+ log.warn("待审库 VACUUM 失败:" + String(error));
4080
+ }
4081
+ return Date.now() - started;
4082
+ }
3832
4083
  //#endregion
3833
4084
  //#region src/store.ts
3834
4085
  const READ_CAP$1 = 8388608;
@@ -9371,10 +9622,11 @@ function logicalLines(text) {
9371
9622
  }
9372
9623
  //#endregion
9373
9624
  //#region src/shared/reviewRegions.ts
9374
- /** @public @author ddj 2026年10月27号 @param diff Immutable official patch. @returns Contiguous change runs with stable source-coordinate identities. */
9625
+ /** @public @author ddj 2026年10月27号 / 2026年11月25号 @param diff Immutable official patch. @returns Contiguous change runs with content-fingerprint identities. */
9375
9626
  function reviewBlocks(diff) {
9376
9627
  if (diff.kind !== "text") return [];
9377
9628
  const blocks = [];
9629
+ const seen = /* @__PURE__ */ new Map();
9378
9630
  for (const [hunkIndex, hunk] of diff.hunks.entries()) {
9379
9631
  let oldLine = hunk.oldStart, newLine = hunk.newStart;
9380
9632
  let before = [];
@@ -9394,7 +9646,7 @@ function reviewBlocks(diff) {
9394
9646
  if (marker !== "+" && marker !== "-") continue;
9395
9647
  if (!current) {
9396
9648
  current = {
9397
- id: `${hunkIndex}:${oldLine}:${newLine}`,
9649
+ id: "",
9398
9650
  hunkIndex,
9399
9651
  oldStart: oldLine,
9400
9652
  newStart: newLine,
@@ -9415,8 +9667,30 @@ function reviewBlocks(diff) {
9415
9667
  }
9416
9668
  }
9417
9669
  }
9670
+ for (const block of blocks) {
9671
+ const fingerprint = fingerprintOf$1(block);
9672
+ const ordinal = seen.get(fingerprint) ?? 0;
9673
+ seen.set(fingerprint, ordinal + 1);
9674
+ block.id = `${block.hunkIndex}:${fingerprint}:${ordinal}`;
9675
+ }
9418
9676
  return blocks;
9419
9677
  }
9678
+ /**
9679
+ * @public
9680
+ * @author ddj 2026年11月25号
9681
+ * @description: 块内容指纹(FNV-1a 32 位,纯函数,宿主与浏览器端结果一致)。
9682
+ * @param block 差异块
9683
+ * @returns 8 位十六进制指纹
9684
+ */
9685
+ function fingerprintOf$1(block) {
9686
+ const text = block.oldLines.join("\n") + "\0" + block.newLines.join("\n");
9687
+ let hash = 2166136261;
9688
+ for (let index = 0; index < text.length; index++) {
9689
+ hash ^= text.charCodeAt(index);
9690
+ hash = Math.imul(hash, 16777619) >>> 0;
9691
+ }
9692
+ return hash.toString(16).padStart(8, "0");
9693
+ }
9420
9694
  //#endregion
9421
9695
  //#region src/reviewDb.ts
9422
9696
  /** Official history shares the archive connection, but never the legacy callId namespace. @author ddj 2026年10月26号 */
@@ -9542,7 +9816,7 @@ async function repairPaths(cwd, resolvePath) {
9542
9816
  }
9543
9817
  }
9544
9818
  }
9545
- /** @private @author ddj 2026年10月26号 @param db Transaction. @param snapshot Source payload. @param hash Source digest. */
9819
+ /** @private @author ddj 2026年10月26号 / 2026年11月25号 @param db Transaction. @param snapshot Source payload. @param hash Source digest. */
9546
9820
  function insertSnapshot(db, snapshot, hash) {
9547
9821
  const { sessionId, turn, seq } = snapshot;
9548
9822
  const previous = db.prepare("SELECT id,identity,diff,decision FROM review_files WHERE session_id=? AND turn=? AND current=1").all(sessionId, turn);
@@ -9552,6 +9826,24 @@ function insertSnapshot(db, snapshot, hash) {
9552
9826
  const insert = db.prepare("INSERT INTO review_files VALUES(?,?,?,?,?,?,?,?,0,1)");
9553
9827
  for (const [index, file] of snapshot.files.entries()) {
9554
9828
  const encoded = JSON.stringify(file.diff);
9829
+ const summary = JSON.stringify(snapshot.summary.files[index]);
9830
+ const prior = latestRowOf(db, file.identity);
9831
+ if (prior) {
9832
+ if (String(prior.diff) === encoded) {
9833
+ db.prepare("UPDATE review_files SET current=1 WHERE id=?").run(String(prior.id));
9834
+ continue;
9835
+ }
9836
+ if (prior.decision === "pending") {
9837
+ const kept = db.prepare("SELECT block_id,decision FROM review_blocks WHERE file_id=?").all(String(prior.id));
9838
+ db.prepare("UPDATE review_files SET summary=?,diff=?,current=1,revision=revision+1 WHERE id=?").run(summary, encoded, String(prior.id));
9839
+ db.prepare("DELETE FROM review_blocks WHERE file_id=?").run(String(prior.id));
9840
+ seedBlocks(db, String(prior.id), file.diff, "pending");
9841
+ const restore = db.prepare("UPDATE review_blocks SET decision=? WHERE file_id=? AND block_id=?");
9842
+ for (const block of kept) restore.run(String(block.decision), String(prior.id), String(block.block_id));
9843
+ continue;
9844
+ }
9845
+ dropFile(db, String(prior.id));
9846
+ }
9555
9847
  const unchanged = previous.find((item) => item.identity === file.identity && item.diff === encoded);
9556
9848
  const id = digest$1(JSON.stringify([
9557
9849
  sessionId,
@@ -9560,7 +9852,7 @@ function insertSnapshot(db, snapshot, hash) {
9560
9852
  file.identity
9561
9853
  ]));
9562
9854
  const decision = String(unchanged?.decision ?? "pending");
9563
- insert.run(id, sessionId, turn, seq, file.identity, JSON.stringify(snapshot.summary.files[index]), encoded, decision);
9855
+ insert.run(id, sessionId, turn, seq, file.identity, summary, encoded, decision);
9564
9856
  seedBlocks(db, id, file.diff, decision);
9565
9857
  if (unchanged) {
9566
9858
  db.prepare(`UPDATE review_blocks SET decision=(SELECT p.decision FROM review_blocks p
@@ -9570,6 +9862,41 @@ function insertSnapshot(db, snapshot, hash) {
9570
9862
  }
9571
9863
  }
9572
9864
  }
9865
+ /**
9866
+ * @private
9867
+ * @author ddj 2026年11月25号
9868
+ * @description: 取某路径当前最新的一条记录,用于「同路径只留一条」的合并判断。
9869
+ * @param db 已打开连接
9870
+ * @param identity 路径身份
9871
+ * @returns 记录行或 undefined
9872
+ */
9873
+ function latestRowOf(db, identity) {
9874
+ return db.prepare("SELECT id,decision,diff FROM review_files WHERE identity=? ORDER BY rowid DESC LIMIT 1").get(identity);
9875
+ }
9876
+ /**
9877
+ * @private
9878
+ * @author ddj 2026年11月25号
9879
+ * @description: 清掉某条记录的块决定,合并重算前先归零。
9880
+ * @param db 已打开连接
9881
+ * @param fileId 记录 id
9882
+ * @returns 无
9883
+ */
9884
+ function dropBlocksOf(db, fileId) {
9885
+ db.prepare("DELETE FROM review_blocks WHERE file_id=?").run(fileId);
9886
+ db.prepare("DELETE FROM review_evidence WHERE file_id=?").run(fileId);
9887
+ }
9888
+ /**
9889
+ * @private
9890
+ * @author ddj 2026年11月25号
9891
+ * @description: 删掉一条官方记录及其块决定:合并语义下旧轮次不再留档。
9892
+ * @param db 已打开连接
9893
+ * @param fileId 记录 id
9894
+ * @returns 无
9895
+ */
9896
+ function dropFile(db, fileId) {
9897
+ dropBlocksOf(db, fileId);
9898
+ db.prepare("DELETE FROM review_files WHERE id=?").run(fileId);
9899
+ }
9573
9900
  /** @public @author ddj 2026年10月26号 @param cwd Workspace. @param gap Announced event identity. @param state Durable inbox or explicit failure. */
9574
9901
  function captureState(cwd, gap, state) {
9575
9902
  reviewDb(cwd).prepare(`INSERT INTO review_capture VALUES(?,?,?,?,?) ON CONFLICT(session_id,turn,seq)
@@ -11660,7 +11987,7 @@ const SEARCH_RESULTS = 200;
11660
11987
  * @param fallback 缺省值
11661
11988
  * @returns 非空字符串
11662
11989
  */
11663
- function textOf$1(value, fallback) {
11990
+ function textOf$2(value, fallback) {
11664
11991
  return typeof value === "string" && value.trim() ? value : fallback;
11665
11992
  }
11666
11993
  /**
@@ -11686,7 +12013,7 @@ function globsOf(value) {
11686
12013
  async function scopeRoot(scope) {
11687
12014
  const fs = scope.ctx.get("fs");
11688
12015
  if (!fs || typeof fs.resolve !== "function") throw new Error("文件系统不可用");
11689
- const requested = textOf$1(scope.args.path, ".");
12016
+ const requested = textOf$2(scope.args.path, ".");
11690
12017
  return String(await fs.resolve(requested, { cwd: scope.cwd }));
11691
12018
  }
11692
12019
  /**
@@ -11712,7 +12039,7 @@ function targetOf(root, path) {
11712
12039
  * @throws 参数缺 pattern、文件系统不可用或搜索失败(由调用方转采集 gap)
11713
12040
  */
11714
12041
  async function replaceCandidates(scope, search = searchRipgrepContent) {
11715
- const query = textOf$1(scope.args.pattern, "");
12042
+ const query = textOf$2(scope.args.pattern, "");
11716
12043
  if (!query) return {
11717
12044
  paths: [],
11718
12045
  total: 0
@@ -11738,6 +12065,285 @@ async function replaceCandidates(scope, search = searchRipgrepContent) {
11738
12065
  };
11739
12066
  }
11740
12067
  //#endregion
12068
+ //#region src/pending/receipt.ts
12069
+ /**
12070
+ * 工具回执适配:把一次写调用的结果读成「它自己声明改了哪个文件、改前改后是什么」。
12071
+ * 只认已见形状;形状不认识一律返回空数组,交给快照判定,绝不猜内容。
12072
+ * @author ddj 2026年11月25号
12073
+ */
12074
+ /**
12075
+ * @author ddj 2026年11月25号
12076
+ * @description: 取工具结果里的规范值;失败结果没有值,直接返回 undefined。
12077
+ * @param result 工具执行结果
12078
+ * @returns 规范值对象或 undefined
12079
+ */
12080
+ function valueOf(result) {
12081
+ if (!result || typeof result !== "object") return void 0;
12082
+ const value = result.value;
12083
+ return value && typeof value === "object" ? value : void 0;
12084
+ }
12085
+ /**
12086
+ * @author ddj 2026年11月25号
12087
+ * @description: 读文本字段:字符串即内容,`null` 即声明不存在,其它一律无效。
12088
+ * @param value 字段值
12089
+ * @returns 文本、null 或 undefined(无效)
12090
+ */
12091
+ function textOf$1(value) {
12092
+ if (value === null) return null;
12093
+ return typeof value === "string" ? value : void 0;
12094
+ }
12095
+ /**
12096
+ * @author ddj 2026年11月25号
12097
+ * @description: 读哈希字段;只接受 64 位十六进制,其余(含 `absent`)视为没有。
12098
+ * @param value 字段值
12099
+ * @returns 小写哈希或 undefined
12100
+ */
12101
+ function hashOf(value) {
12102
+ return typeof value === "string" && /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : void 0;
12103
+ }
12104
+ /**
12105
+ * @author ddj 2026年11月25号
12106
+ * @description: 读路径字段;空串与非字符串都不算路径。
12107
+ * @param value 字段值
12108
+ * @returns 路径或 undefined
12109
+ */
12110
+ function pathOf(value) {
12111
+ return typeof value === "string" && value.trim() ? value : void 0;
12112
+ }
12113
+ /**
12114
+ * @author ddj 2026年11月25号
12115
+ * @description: 官方 edit/write 的回执:结果里直接带 path/before/after。
12116
+ * @param name 工具名
12117
+ * @param value 规范值
12118
+ * @returns 回执列表;形状不符为空
12119
+ */
12120
+ function officialReceipts(name, value) {
12121
+ const path = pathOf(value.path);
12122
+ const before = textOf$1(value.before);
12123
+ const after = textOf$1(value.after);
12124
+ if (!path || before === void 0 || after === void 0) return [];
12125
+ if (name === "edit" && typeof before !== "string") return [];
12126
+ const receipt = {
12127
+ path,
12128
+ before,
12129
+ after,
12130
+ status: "completed",
12131
+ strength: "authoritative"
12132
+ };
12133
+ if (name === "write" && before === null && value.operation === "update") receipt.noBasis = true;
12134
+ return [receipt];
12135
+ }
12136
+ /**
12137
+ * @author ddj 2026年11月25号
12138
+ * @description: apply_patch 的回执:每个完成或失败操作下挂的 changes 才是实际效果。
12139
+ * @param value 规范值
12140
+ * @returns 逐文件回执
12141
+ */
12142
+ function patchReceipts(value) {
12143
+ if (value.phase !== "commit" || !Array.isArray(value.operations)) return [];
12144
+ const receipts = [];
12145
+ for (const raw of value.operations) {
12146
+ if (!raw || typeof raw !== "object") continue;
12147
+ const operation = raw;
12148
+ if (!Array.isArray(operation.changes)) continue;
12149
+ const status = operation.status === "completed" ? "completed" : operation.status === "failed" ? "failed" : "skipped";
12150
+ for (const change of operation.changes) {
12151
+ if (!change || typeof change !== "object") continue;
12152
+ const item = change;
12153
+ const path = pathOf(item.path);
12154
+ const before = textOf$1(item.before);
12155
+ const after = textOf$1(item.after);
12156
+ if (!path || before === void 0 || after === void 0) continue;
12157
+ receipts.push({
12158
+ path,
12159
+ before,
12160
+ after,
12161
+ status,
12162
+ strength: "authoritative"
12163
+ });
12164
+ }
12165
+ }
12166
+ return receipts;
12167
+ }
12168
+ /**
12169
+ * @author ddj 2026年11月25号
12170
+ * @description: 批量替换回执:只认执行完成、且带写后计划的条目。
12171
+ * @param items 回执条目
12172
+ * @returns 逐文件回执
12173
+ */
12174
+ function replaceReceipts(items) {
12175
+ const receipts = [];
12176
+ for (const raw of items) {
12177
+ if (!raw || typeof raw !== "object") continue;
12178
+ const item = raw;
12179
+ const path = pathOf(item.path);
12180
+ const revisionAfter = hashOf(item.revisionAfter);
12181
+ if (!path || item.status !== "completed" || !revisionAfter) continue;
12182
+ receipts.push({
12183
+ path,
12184
+ revisionBefore: hashOf(item.revision),
12185
+ revisionAfter,
12186
+ status: "completed",
12187
+ strength: "receipt"
12188
+ });
12189
+ }
12190
+ return receipts;
12191
+ }
12192
+ /**
12193
+ * @author ddj 2026年11月25号
12194
+ * @description: dsh-ops 回执:单目标带 path/to 与写前后哈希;删除没有写后哈希,交给快照。
12195
+ * @param value 规范值
12196
+ * @returns 回执列表
12197
+ */
12198
+ function opsReceipts(value) {
12199
+ if (Array.isArray(value.items)) return replaceReceipts(value.items);
12200
+ if (value.removed === true) return [];
12201
+ const revisionAfter = hashOf(value.revision);
12202
+ if (!revisionAfter) return [];
12203
+ const path = pathOf(value.to) ?? pathOf(value.path);
12204
+ if (!path) return [];
12205
+ return [{
12206
+ path,
12207
+ revisionBefore: hashOf(value.revisionBefore),
12208
+ revisionAfter,
12209
+ status: "completed",
12210
+ strength: "receipt"
12211
+ }];
12212
+ }
12213
+ /**
12214
+ * @public
12215
+ * @author ddj 2026年11月25号
12216
+ * @description: 把一次写调用的结果转成回执;不认识的结果与工具返回空,调用方退回快照判定。
12217
+ * @param name 工具名
12218
+ * @param result 工具执行结果(可能带 value 包装)
12219
+ * @param isError 工具是否报错
12220
+ * @returns 回执列表
12221
+ */
12222
+ function receiptsOf(name, result, isError) {
12223
+ if (isError && name !== "apply_patch") return [];
12224
+ const value = valueOf(result);
12225
+ if (!value) return [];
12226
+ if (name === "edit" || name === "write") return officialReceipts(name, value);
12227
+ if (name === "apply_patch") return patchReceipts(value);
12228
+ if (String(name).startsWith("ops_")) return opsReceipts(value);
12229
+ return [];
12230
+ }
12231
+ /**
12232
+ * @public
12233
+ * @author ddj 2026年11月25号
12234
+ * @description: 读闸门模式;未知值按 strict 处理,避免配置写错就静默放行。
12235
+ * @param env 环境变量表
12236
+ * @returns 闸门模式
12237
+ */
12238
+ function gateModeOf(env = process.env) {
12239
+ const raw = String(env["DSH_EDIT_REVIEW_RECEIPT_GATE"] ?? "").trim().toLowerCase();
12240
+ if (raw === "off") return "off";
12241
+ if (raw === "warn") return "warn";
12242
+ return "strict";
12243
+ }
12244
+ /**
12245
+ * @author ddj 2026年11月25号
12246
+ * @description: 只用于比对的归一:去掉 BOM、统一行尾;绝不用于写回。
12247
+ * @param text 一侧文本
12248
+ * @returns 归一后的文本
12249
+ */
12250
+ function norm(text) {
12251
+ return text === null ? null : text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
12252
+ }
12253
+ /**
12254
+ * @private
12255
+ * @author ddj 2026年11月25号
12256
+ * @description: 结论构造。
12257
+ * @param verdict 结局
12258
+ * @param evidence 证据强度
12259
+ * @param reason 原因
12260
+ * @returns 判定结果
12261
+ */
12262
+ function outcomeOf(verdict, evidence, reason) {
12263
+ return {
12264
+ verdict,
12265
+ evidence,
12266
+ reason
12267
+ };
12268
+ }
12269
+ /**
12270
+ * @private
12271
+ * @author ddj 2026年11月25号
12272
+ * @description: 没有回执时的兜底:沿用今天的快照比较。
12273
+ * @param input 判定输入
12274
+ * @returns 判定结果
12275
+ */
12276
+ function snapshotOf(input) {
12277
+ return input.beforeRead === input.afterRead ? outcomeOf("noop", "snapshot", "前后内容相同") : outcomeOf("changed", "snapshot", "");
12278
+ }
12279
+ /**
12280
+ * @private
12281
+ * @author ddj 2026年11月25号
12282
+ * @description: 权威回执:用回执的前后全文核对磁盘,写前写后都对得上才算数。
12283
+ * @param receipt 工具回执
12284
+ * @param input 判定输入
12285
+ * @returns 判定结果
12286
+ */
12287
+ function textOutcome(receipt, input) {
12288
+ if (receipt.after === void 0) return outcomeOf("unverified", "authoritative", "回执没有写后内容");
12289
+ if (norm(receipt.after) !== norm(input.afterRead)) return outcomeOf("unverified", "authoritative", "写后内容与磁盘不一致");
12290
+ if (receipt.noBasis === true) {
12291
+ if (!input.hasBaseline) return outcomeOf("unverified", "authoritative", "回执没有写前内容,无法补基线");
12292
+ return norm(input.beforeRead) === norm(input.afterRead) ? outcomeOf("noop", "authoritative", "前后内容相同") : outcomeOf("changed", "authoritative", "");
12293
+ }
12294
+ if (input.hasBaseline) {
12295
+ if (norm(receipt.before ?? null) !== norm(input.beforeRead)) return outcomeOf("unverified", "authoritative", "写前内容与磁盘不一致");
12296
+ } else if (receipt.before === void 0) return outcomeOf("unverified", "authoritative", "回执没有写前内容,无法补基线");
12297
+ return norm(receipt.before ?? null) === norm(receipt.after) ? outcomeOf("noop", "authoritative", "回执前后相同") : outcomeOf("changed", "authoritative", "");
12298
+ }
12299
+ /**
12300
+ * @private
12301
+ * @author ddj 2026年11月25号
12302
+ * @description: 哈希回执:写后哈希必须等于磁盘,写前哈希(若有)必须等于快照。
12303
+ * @param receipt 工具回执
12304
+ * @param input 判定输入
12305
+ * @returns 判定结果
12306
+ */
12307
+ function hashOutcome(receipt, input) {
12308
+ if (!receipt.revisionAfter) return outcomeOf("unverified", "receipt", "回执没有写后哈希");
12309
+ if (input.hashAfter !== receipt.revisionAfter) return outcomeOf("unverified", "receipt", "写后哈希与磁盘不一致");
12310
+ if (!input.hasBaseline) return outcomeOf("unverified", "receipt", "没有写前快照,无法对账哈希");
12311
+ if (!receipt.revisionBefore) return input.hashBefore === null ? outcomeOf("changed", "receipt", "") : outcomeOf("unverified", "receipt", "回执没有写前哈希");
12312
+ if (input.hashBefore !== receipt.revisionBefore) return outcomeOf("unverified", "receipt", "写前哈希与磁盘不一致");
12313
+ return receipt.revisionBefore === receipt.revisionAfter ? outcomeOf("noop", "receipt", "回执前后哈希相同") : outcomeOf("changed", "receipt", "");
12314
+ }
12315
+ /**
12316
+ * @private
12317
+ * @author ddj 2026年11月25号
12318
+ * @description: 按回执强度选核对口径。
12319
+ * @param receipt 工具回执
12320
+ * @param input 判定输入
12321
+ * @returns 判定结果
12322
+ */
12323
+ function receiptOutcome(receipt, input) {
12324
+ return receipt.strength === "authoritative" ? textOutcome(receipt, input) : hashOutcome(receipt, input);
12325
+ }
12326
+ /**
12327
+ * @public
12328
+ * @author ddj 2026年11月25号
12329
+ * @description: 一次写入的结局判定;只有 changed 值得建待审条目。
12330
+ * @param input 回执、快照与成败
12331
+ * @param mode 闸门模式(缺省读环境变量)
12332
+ * @returns 结局、证据强度与原因
12333
+ */
12334
+ function verdictOf$1(input, mode = gateModeOf()) {
12335
+ const snapshot = snapshotOf(input);
12336
+ if (mode === "off") return snapshot;
12337
+ if (input.isError && !input.receipt) return outcomeOf("failed", "none", "工具报错,没有可采信的效果");
12338
+ if (!input.receipt) return snapshot;
12339
+ const judged = receiptOutcome(input.receipt, input);
12340
+ if (judged.verdict !== "unverified") return judged;
12341
+ return mode === "warn" ? {
12342
+ ...snapshot,
12343
+ reason: judged.reason
12344
+ } : judged;
12345
+ }
12346
+ //#endregion
11741
12347
  //#region src/pending/capture.ts
11742
12348
  /**
11743
12349
  * 待审差异采集:环绕一次文件写入读取真实前后内容,只有内容确实变化才落库。
@@ -11826,10 +12432,12 @@ function installPending(ctx, sink, options) {
11826
12432
  }
11827
12433
  /**
11828
12434
  * @author ddj 2026年10月30号
11829
- * @description: 判定本次调用是否值得采集;不值得时返回 null,调用方直接透传原始分发。
11830
- * @param ctx Host 生命周期
12435
+ * @description: 判定本次调用是否值得采集并冻结写前基线;同目标并发调用改记「无基线」,
12436
+ * 交给工具回执补前像,不再整次丢弃。
12437
+ * @param scope 工作区作用域
11831
12438
  * @param state 采集状态
11832
- * @param exec 工具分发上下文
12439
+ * @param requested 目标路径
12440
+ * @param tool 工具名
11833
12441
  * @returns 采集计划或 null
11834
12442
  */
11835
12443
  async function planOf(scope, state, requested, tool) {
@@ -11837,23 +12445,34 @@ async function planOf(scope, state, requested, tool) {
11837
12445
  if (state.stopped || state.disposed.has(sessionId)) return null;
11838
12446
  const target = await fs.resolve(requested, { cwd });
11839
12447
  const identity = fs.processPath(target);
11840
- if (state.stopped || state.disposed.has(sessionId) || typeof identity !== "string" || !identity || state.busy.has(identity)) return null;
12448
+ if (state.stopped || state.disposed.has(sessionId) || typeof identity !== "string" || !identity) return null;
12449
+ const base = {
12450
+ cwd: String(cwd),
12451
+ sessionId,
12452
+ path: requested,
12453
+ identity,
12454
+ target,
12455
+ fs,
12456
+ tool
12457
+ };
12458
+ if (state.busy.has(identity)) return {
12459
+ ...base,
12460
+ before: void 0,
12461
+ hashBefore: null,
12462
+ held: false
12463
+ };
11841
12464
  state.busy.add(identity);
11842
12465
  try {
11843
- const before = await readText$1(fs, target);
11844
- if (state.stopped || state.disposed.has(sessionId) || before !== null && before.length > MAX_TEXT) {
12466
+ const snapshot = await readSnapshot(fs, target);
12467
+ if (state.stopped || state.disposed.has(sessionId) || snapshot.text !== null && snapshot.text.length > MAX_TEXT) {
11845
12468
  state.busy.delete(identity);
11846
12469
  return null;
11847
12470
  }
11848
12471
  return {
11849
- cwd: String(cwd),
11850
- sessionId,
11851
- path: requested,
11852
- identity,
11853
- before,
11854
- target,
11855
- fs,
11856
- tool
12472
+ ...base,
12473
+ before: snapshot.text,
12474
+ hashBefore: snapshot.hash,
12475
+ held: true
11857
12476
  };
11858
12477
  } catch (error) {
11859
12478
  state.busy.delete(identity);
@@ -11961,8 +12580,9 @@ async function buildPlans(scope, state, exec, paths) {
11961
12580
  return plans;
11962
12581
  }
11963
12582
  /**
11964
- * @author ddj 2026年10月30号
11965
- * @description: 写工具执行前后各读一次,内容变化才上报;任何采集异常都不改变工具结果。
12583
+ * @author ddj 2026年10月30号 / 2026年11月25号
12584
+ * @description: 写工具执行前后各读一次,并用工具自己的回执对账;只有确认变化的调用才上报。
12585
+ * 任何采集异常都不改变工具结果。
11966
12586
  * @param ctx Host 生命周期
11967
12587
  * @param state 采集状态
11968
12588
  * @param sink 已确认写入的接收方
@@ -11992,68 +12612,188 @@ async function aroundTool(ctx, state, sink, exec, next) {
11992
12612
  }
11993
12613
  if (bulk && targets.total > targets.paths.length) recordGap(scope, exec, BULK_TOOL, "批量替换候选 " + targets.total + " 个文件,仅采集前 " + targets.paths.length + " 个");
11994
12614
  const plans = await buildPlans(scope, state, exec, targets.paths);
12615
+ let result;
12616
+ let failed;
11995
12617
  try {
11996
- const result = await next();
12618
+ result = await next();
11997
12619
  if (bulk && !state.stopped && !state.disposed.has(scope.sessionId)) await reconcileBulk(scope, exec, result, plans);
11998
12620
  if (name === "apply_patch" && !state.stopped && !state.disposed.has(scope.sessionId)) for (const diagnostic of patchDiagnostics(result)) recordGap(scope, exec, "apply_patch", diagnostic);
11999
12621
  return result;
12622
+ } catch (error) {
12623
+ failed = error;
12624
+ throw error;
12000
12625
  } finally {
12001
- for (const plan of plans) try {
12002
- await reportWrite(state, sink, plan);
12003
- } catch (error) {
12004
- if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, plan.path, error);
12005
- log.debug("待审上报失败:" + String(error));
12006
- } finally {
12007
- state.busy.delete(plan.identity);
12008
- }
12626
+ await settle(scope, state, sink, exec, plans, result, failed);
12009
12627
  }
12010
12628
  }
12011
12629
  /**
12012
- * @author ddj 2026年11月04号
12013
- * @description: 固定目标写后读回;内容一致不产生条目,卸载后不再上报。
12630
+ * @private
12631
+ * @author ddj 2026年11月25号
12632
+ * @description: 解析回执并逐条收尾;单条失败只记缺口,绝不改变工具结果与 busy 释放。
12633
+ * @param scope 工作区作用域
12634
+ * @param state 采集状态
12635
+ * @param sink 已确认写入的接收方
12636
+ * @param exec 工具分发上下文
12637
+ * @param plans 写前冻结的采集计划
12638
+ * @param result 工具结果
12639
+ * @param failure 工具抛出的错误(没有则 undefined)
12640
+ * @returns 无
12641
+ */
12642
+ async function settle(scope, state, sink, exec, plans, result, failure) {
12643
+ const flagError = Boolean(result?.isError);
12644
+ const context = {
12645
+ scope,
12646
+ exec,
12647
+ isError: failure !== void 0 || flagError,
12648
+ receipts: await receiptsFor(scope, exec, result)
12649
+ };
12650
+ for (const plan of plans) try {
12651
+ await reportWrite(state, sink, plan, context);
12652
+ } catch (error) {
12653
+ if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, plan.path, error);
12654
+ log.debug("待审上报失败:" + String(error));
12655
+ } finally {
12656
+ if (plan.held) state.busy.delete(plan.identity);
12657
+ }
12658
+ }
12659
+ /**
12660
+ * @private
12661
+ * @author ddj 2026年11月25号
12662
+ * @description: 把回执里的路径解析成条目身份;解析不了的回执丢弃,退回快照判定。
12663
+ * @param scope 工作区作用域
12664
+ * @param exec 工具分发上下文
12665
+ * @param result 工具结果
12666
+ * @returns 身份 → 回执
12667
+ */
12668
+ async function receiptsFor(scope, exec, result) {
12669
+ const map = /* @__PURE__ */ new Map();
12670
+ if (result === void 0) return map;
12671
+ let receipts;
12672
+ try {
12673
+ receipts = receiptsOf(String(exec.name), result, Boolean(result.isError));
12674
+ } catch {
12675
+ return map;
12676
+ }
12677
+ for (const receipt of receipts) try {
12678
+ const target = await scope.fs.resolve(receipt.path, { cwd: scope.cwd });
12679
+ const identity = scope.fs.processPath(target);
12680
+ if (typeof identity === "string" && identity) map.set(identity, receipt);
12681
+ } catch {
12682
+ log.debug("回执路径不可解析:" + receipt.path);
12683
+ }
12684
+ return map;
12685
+ }
12686
+ /**
12687
+ * @private
12688
+ * @author ddj 2026年11月25号
12689
+ * @description: 该路径的旧缺口在本次写入被正式采用后清掉,避免缺口里留着已解决的原因。
12690
+ * @param plan 采集计划
12691
+ * @returns 无
12692
+ */
12693
+ function clearGapsOf(plan) {
12694
+ for (const [key, gap] of captureGaps) {
12695
+ const identity = JSON.parse(key);
12696
+ if (gap.cwd === plan.cwd && gap.sessionId === plan.sessionId && identity[3] === plan.path) captureGaps.delete(key);
12697
+ }
12698
+ }
12699
+ /**
12700
+ * @author ddj 2026年11月04号 / 2026年11月25号
12701
+ * @description: 固定目标写后读回并按回执判定;不一致只记缺口,未确认变化一律不建条目。
12014
12702
  * @param state 采集生命周期状态
12015
12703
  * @param sink 已确认写入的接收方
12016
12704
  * @param plan 采集计划
12705
+ * @param context 本次调用的事实
12017
12706
  * @returns 无;读回失败只记日志
12018
12707
  */
12019
- async function reportWrite(state, sink, plan) {
12708
+ async function reportWrite(state, sink, plan, context) {
12020
12709
  if (state.stopped || state.disposed.has(plan.sessionId)) return;
12021
- const after = await readText$1(plan.fs, plan.target);
12710
+ const receipt = context.receipts.get(plan.identity);
12711
+ if (plan.before === void 0 && !receipt) {
12712
+ log.debug("同目标并发写入且没有回执,跳过该次采集:" + plan.path);
12713
+ return;
12714
+ }
12715
+ const after = await readSnapshot(plan.fs, plan.target);
12022
12716
  if (state.stopped || state.disposed.has(plan.sessionId)) return;
12023
- if (after !== null && after.length > MAX_TEXT) throw new Error("capture text budget exceeded");
12024
- for (const [key, gap] of captureGaps) {
12025
- const identity = JSON.parse(key);
12026
- if (gap.cwd === plan.cwd && gap.sessionId === plan.sessionId && identity[3] === plan.path) captureGaps.delete(key);
12717
+ if (after.text !== null && after.text.length > MAX_TEXT) throw new Error("capture text budget exceeded");
12718
+ clearGapsOf(plan);
12719
+ const judged = verdictOf$1({
12720
+ receipt,
12721
+ isError: context.isError,
12722
+ hasBaseline: plan.before !== void 0,
12723
+ beforeRead: plan.before ?? null,
12724
+ afterRead: after.text,
12725
+ hashBefore: plan.hashBefore,
12726
+ hashAfter: after.hash
12727
+ });
12728
+ if (judged.verdict === "unverified") {
12729
+ recordGap(context.scope, context.exec, plan.path, "回执与磁盘不一致,未记录该次调用:" + judged.reason);
12730
+ return;
12027
12731
  }
12028
- if (plan.before === after) return;
12029
- sink({
12732
+ if (judged.verdict !== "changed") {
12733
+ if (plan.before !== void 0 && plan.before !== after.text) {
12734
+ const reason = judged.verdict === "failed" ? "工具报错后文件内容发生变化,无法判断是否本次写入:" : "回执声明没有变化但磁盘内容变了,未记录该次调用:";
12735
+ recordGap(context.scope, context.exec, plan.path, reason + judged.reason);
12736
+ }
12737
+ return;
12738
+ }
12739
+ const before = plan.before === void 0 ? receipt?.before ?? null : plan.before;
12740
+ if (before === after.text) return;
12741
+ const write = {
12030
12742
  cwd: plan.cwd,
12031
12743
  sessionId: plan.sessionId,
12032
12744
  path: plan.path,
12033
12745
  identity: plan.identity,
12034
- before: plan.before,
12035
- after,
12746
+ before,
12747
+ after: after.text,
12036
12748
  now: Date.now(),
12037
- tool: plan.tool
12038
- });
12749
+ tool: plan.tool,
12750
+ evidence: judged.evidence,
12751
+ verdict: judged.verdict
12752
+ };
12753
+ if (plan.before === void 0 && judged.evidence === "authoritative") write.baseKind = "normalized";
12754
+ sink(write);
12039
12755
  }
12040
12756
  /**
12041
- * @author ddj 2026年10月29号
12042
- * @description: 读取全文;只有明确缺失返回 null,不可读或超限错误保留失败语义。
12757
+ * @author ddj 2026年10月29号 / 2026年11月25号
12758
+ * @description: 读原始字节并同时给出文本与 sha256;只有明确缺失返回空,不可读或超限保留失败语义。
12043
12759
  * @param fs 文件系统
12044
12760
  * @param target 目标
12045
- * @returns 文本或 null
12761
+ * @param signal 取消信号
12762
+ * @returns 文本与哈希
12046
12763
  */
12047
- async function readText$1(fs, target, signal) {
12764
+ async function readSnapshot(fs, target, signal) {
12048
12765
  try {
12049
- if (typeof fs.readBytes === "function") return rawText(rawReviewFile(await fs.readBytes(target, signal, MAX_TEXT)));
12050
- throw new Error("Raw byte capture unavailable");
12766
+ if (typeof fs.readBytes !== "function") throw new Error("Raw byte capture unavailable");
12767
+ const bytes = await fs.readBytes(target, signal, MAX_TEXT);
12768
+ if (bytes === null || bytes === void 0) return {
12769
+ text: null,
12770
+ hash: null
12771
+ };
12772
+ const payload = Buffer.from(bytes);
12773
+ return {
12774
+ text: rawText(rawReviewFile(payload)),
12775
+ hash: createHash("sha256").update(payload).digest("hex")
12776
+ };
12051
12777
  } catch (error) {
12052
12778
  const code = error.code;
12053
- if (code === "ENOENT" || code === "FS_NOT_FOUND") return null;
12779
+ if (code === "ENOENT" || code === "FS_NOT_FOUND") return {
12780
+ text: null,
12781
+ hash: null
12782
+ };
12054
12783
  throw error;
12055
12784
  }
12056
12785
  }
12786
+ /**
12787
+ * @author ddj 2026年10月29号
12788
+ * @description: 读取全文;只有明确缺失返回 null,不可读或超限错误保留失败语义。
12789
+ * @param fs 文件系统
12790
+ * @param target 目标
12791
+ * @param signal 取消信号
12792
+ * @returns 文本或 null
12793
+ */
12794
+ async function readText$1(fs, target, signal) {
12795
+ return (await readSnapshot(fs, target, signal)).text;
12796
+ }
12057
12797
  //#endregion
12058
12798
  //#region src/pending/vcs.ts
12059
12799
  /**
@@ -12411,12 +13151,20 @@ async function runCommand(shell, command, workdir, stdoutMaxBytes = STDOUT_BUDGE
12411
13151
  * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
12412
13152
  * @param shell shell 能力
12413
13153
  * @param cwd 工作区
13154
+ * @param onFailure 失败原因回调(可选):调用方用它把「为什么没有状态」写进采集缺口
12414
13155
  * @returns 状态集合或 null
12415
13156
  */
12416
- async function vcsStatus(shell, cwd) {
13157
+ async function vcsStatus(shell, cwd, onFailure) {
12417
13158
  const detected = await detectVcsRoot(cwd);
12418
- if (!detected || detected.kind === "p4") return null;
12419
- return detected.kind === "git" ? gitStatus(shell, detected.root) : svnStatus(shell, detected.root);
13159
+ if (!detected) {
13160
+ onFailure?.("不是 git/svn 工作副本");
13161
+ return null;
13162
+ }
13163
+ if (detected.kind === "p4") {
13164
+ onFailure?.("Perforce 工作副本不支持状态探测");
13165
+ return null;
13166
+ }
13167
+ return detected.kind === "git" ? gitStatus(shell, detected.root, onFailure) : svnStatus(shell, detected.root, onFailure);
12420
13168
  }
12421
13169
  /**
12422
13170
  * @private
@@ -12424,11 +13172,15 @@ async function vcsStatus(shell, cwd) {
12424
13172
  * @description: git 状态:一条 status 命令解析出改动集合。
12425
13173
  * @param shell shell 能力
12426
13174
  * @param root 仓库根
13175
+ * @param onFailure 失败原因回调(可选)
12427
13176
  * @returns 状态集合或 null(命令失败)
12428
13177
  */
12429
- async function gitStatus(shell, root) {
13178
+ async function gitStatus(shell, root, onFailure) {
12430
13179
  const status = await runCommand(shell, "git -c status.renames=false status --porcelain=v1 -z --untracked-files=all", root);
12431
- if (!status.ok) return null;
13180
+ if (!status.ok) {
13181
+ onFailure?.("git status 失败:" + status.stderr.slice(0, 200));
13182
+ return null;
13183
+ }
12432
13184
  const entries = /* @__PURE__ */ new Map();
12433
13185
  for (const entry of parseGitStatus(status.stdout)) {
12434
13186
  const absolute = join(root, ...entry.path.split(GIT_SEPARATOR));
@@ -12450,11 +13202,15 @@ async function gitStatus(shell, root) {
12450
13202
  * @description: svn 状态:一条 status --xml 解析出改动集合。
12451
13203
  * @param shell shell 能力
12452
13204
  * @param root 工作副本根
13205
+ * @param onFailure 失败原因回调(可选)
12453
13206
  * @returns 状态集合或 null(命令失败)
12454
13207
  */
12455
- async function svnStatus(shell, root) {
13208
+ async function svnStatus(shell, root, onFailure) {
12456
13209
  const status = await runCommand(shell, "svn status --xml", root);
12457
- if (!status.ok) return null;
13210
+ if (!status.ok) {
13211
+ onFailure?.("svn status 失败:" + status.stderr.slice(0, 200));
13212
+ return null;
13213
+ }
12458
13214
  const entries = /* @__PURE__ */ new Map();
12459
13215
  for (const entry of parseSvnStatus(status.stdout)) {
12460
13216
  const absolute = resolve(root, entry.path);
@@ -12842,6 +13598,8 @@ const SEEN_MAX = 5e3;
12842
13598
  const ALIGN_INTERVAL_MS = 6e5;
12843
13599
  /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
12844
13600
  const ALIGN_AFTER_VCS_MS = 1500;
13601
+ /** 熔断后的静默期:这段时间只更新已有条目,不新建。 */
13602
+ const BURST_COOLDOWN_MS = 6e5;
12845
13603
  /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
12846
13604
  const VCS_WRITE_METHODS = /* @__PURE__ */ new Set([
12847
13605
  "svn.revert",
@@ -12866,7 +13624,11 @@ const VCS_WRITE_TOOLS = /* @__PURE__ */ new Set([
12866
13624
  "svn_changelist",
12867
13625
  "remote_ssh_write"
12868
13626
  ]);
12869
- /** 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。 */
13627
+ /**
13628
+ * 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。
13629
+ * 只收版本库元数据、Unity 缓存与构建产物:第三方与代码生成目录不在忽略之列,
13630
+ * 它们的改动靠「mtime 证据 + 版本库状态」两道闸门拦,而不是按目录名一刀切。
13631
+ */
12870
13632
  const EXTRA_IGNORE_SEGMENTS = [
12871
13633
  ".svn",
12872
13634
  ".hg",
@@ -12941,7 +13703,13 @@ function installExternalCapture(deps) {
12941
13703
  status: void 0,
12942
13704
  alignedAt: 0,
12943
13705
  alignTimer: null,
12944
- requestTimer: null
13706
+ requestTimer: null,
13707
+ startedAt: 0,
13708
+ gapKeys: /* @__PURE__ */ new Set(),
13709
+ statusNoteAt: 0,
13710
+ burstAt: 0,
13711
+ burstCount: 0,
13712
+ burstMutedUntil: 0
12945
13713
  };
12946
13714
  spaces.set(key, created);
12947
13715
  return created;
@@ -12978,6 +13746,7 @@ function installExternalCapture(deps) {
12978
13746
  */
12979
13747
  function startWatch(space) {
12980
13748
  if (space.watchers.length || stopped) return;
13749
+ space.startedAt = now();
12981
13750
  try {
12982
13751
  const watcher = watch(space.cwd, {
12983
13752
  recursive: true,
@@ -13036,6 +13805,23 @@ function installExternalCapture(deps) {
13036
13805
  }
13037
13806
  /**
13038
13807
  * @private
13808
+ * @author ddj 2026年11月25号
13809
+ * @description: 取某路径的最新条目:批次快照可能早于工具落库,写记录前按身份重读一条。
13810
+ * @param space 工作区状态
13811
+ * @param absolute 绝对路径
13812
+ * @param fallback 批次内的旧条目
13813
+ * @returns 最新条目(读不到时回落到旧条目)
13814
+ */
13815
+ function latestOf(space, absolute, fallback) {
13816
+ try {
13817
+ if (deps.latest) return deps.latest(space.cwd, absolute) ?? fallback;
13818
+ return loadEntry(space.cwd, absolute) ?? fallback;
13819
+ } catch {
13820
+ return fallback;
13821
+ }
13822
+ }
13823
+ /**
13824
+ * @private
13039
13825
  * @description: 读磁盘内容;缺失返回 null,其它失败抛出(由调用点记缺口)。
13040
13826
  * @param cwd 工作区
13041
13827
  * @param absolute 绝对路径
@@ -13062,11 +13848,100 @@ function installExternalCapture(deps) {
13062
13848
  return space.status;
13063
13849
  }
13064
13850
  const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId);
13065
- space.status = scope ? await vcsStatus(scope.shell, space.cwd) : null;
13851
+ if (!scope) {
13852
+ noteStatusOnce(space, "没有 shell 能力,版本库状态不可用");
13853
+ space.status = null;
13854
+ return space.status;
13855
+ }
13856
+ space.status = await vcsStatus(scope.shell, space.cwd, (reason) => noteStatusOnce(space, reason));
13066
13857
  return space.status;
13067
13858
  }
13068
13859
  /**
13069
13860
  * @private
13861
+ * @author ddj 2026-11-24
13862
+ * @description: 读文件修改时间(测试可注入);读不到返回 undefined。
13863
+ * @param space 工作区状态
13864
+ * @param absolute 绝对路径
13865
+ * @returns 毫秒时间戳或 undefined
13866
+ */
13867
+ function mtimeOf(space, absolute) {
13868
+ if (deps.mtime) return deps.mtime(space.cwd, absolute);
13869
+ try {
13870
+ return statSync(absolute).mtimeMs;
13871
+ } catch {
13872
+ return;
13873
+ }
13874
+ }
13875
+ /**
13876
+ * @private
13877
+ * @author ddj 2026-11-24
13878
+ * @description: 判断文件是否在本次监听开始之后被写过:这是「拿不到版本库状态」时唯一的外部证据。
13879
+ * @param space 工作区状态
13880
+ * @param absolute 绝对路径
13881
+ * @returns 刚被写过返回 true
13882
+ */
13883
+ function recentlyWritten(space, absolute) {
13884
+ if (!space.startedAt) return false;
13885
+ const mtime = mtimeOf(space, absolute);
13886
+ return mtime !== void 0 && mtime >= space.startedAt - 2e3;
13887
+ }
13888
+ /**
13889
+ * @private
13890
+ * @author ddj 2026-11-24
13891
+ * @description: 同一条缺口只上报一次;去重表满了就丢最早的键,保证内存有界。
13892
+ * @param space 工作区状态
13893
+ * @param key 去重键
13894
+ * @param absolute 出问题的路径
13895
+ * @param message 原因
13896
+ * @returns 无
13897
+ */
13898
+ function noteGapOnce(space, key, absolute, message) {
13899
+ if (space.gapKeys.has(key)) return;
13900
+ if (space.gapKeys.size >= 500) {
13901
+ const oldest = space.gapKeys.values().next().value;
13902
+ if (oldest !== void 0) space.gapKeys.delete(oldest);
13903
+ }
13904
+ space.gapKeys.add(key);
13905
+ noteCaptureGap(space.cwd, space.sessionId, absolute, message);
13906
+ }
13907
+ /**
13908
+ * @private
13909
+ * @author ddj 2026-11-24
13910
+ * @description: 「版本库状态不可用」按工作区节流上报,让面板能说清为什么没拦住噪声。
13911
+ * @param space 工作区状态
13912
+ * @param reason 失败原因(命令回执头 200 字)
13913
+ * @returns 无
13914
+ */
13915
+ function noteStatusOnce(space, reason) {
13916
+ const at = now();
13917
+ if (at - space.statusNoteAt < 3e5) return;
13918
+ space.statusNoteAt = at;
13919
+ noteCaptureGap(space.cwd, space.sessionId, space.cwd, "版本库状态不可用:" + reason.slice(0, 200));
13920
+ }
13921
+ /**
13922
+ * @private
13923
+ * @author ddj 2026-11-24
13924
+ * @description: 整文件新增的熔断:短时间成批出现「没有基线的整文件新增」时判定为批量噪声,
13925
+ * 静默一段时间不新建档,只留一条缺口。已有条目的更新不受影响。
13926
+ * @param space 工作区状态
13927
+ * @param absolute 触发熔断的路径
13928
+ * @returns 允许新建返回 true
13929
+ */
13930
+ function allowNewWholeFile(space, absolute) {
13931
+ const at = now();
13932
+ if (space.burstMutedUntil > at) return false;
13933
+ if (at - space.burstAt > 3e5) {
13934
+ space.burstAt = at;
13935
+ space.burstCount = 0;
13936
+ }
13937
+ space.burstCount += 1;
13938
+ if (space.burstCount <= 200) return true;
13939
+ space.burstMutedUntil = at + BURST_COOLDOWN_MS;
13940
+ noteGapOnce(space, "burst:" + String(space.burstMutedUntil), absolute, `短时间内新建 ${space.burstCount} 条整文件新增记录:疑似批量噪声,暂停 ${Math.round(BURST_COOLDOWN_MS / 6e4)} 分钟`);
13941
+ return false;
13942
+ }
13943
+ /**
13944
+ * @private
13070
13945
  * @description: 处理一个路径:判定链见文件头注释。
13071
13946
  * @param space 工作区状态
13072
13947
  * @param absolute 绝对路径
@@ -13092,21 +13967,34 @@ function installExternalCapture(deps) {
13092
13967
  if (window === "editor") {
13093
13968
  space.seen.set(key, content);
13094
13969
  if (!stored) return false;
13095
- deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "watch", "editor", "known"));
13970
+ const current = latestOf(space, absolute, stored);
13971
+ if (!current || current.entry.newText === (content ?? "")) return false;
13972
+ deps.record(writeOf(space, absolute, current.entry.newText, content, at, "watch", "editor", "known"));
13096
13973
  return true;
13097
13974
  }
13098
13975
  const status = await statusOf(space);
13099
13976
  if (status && !status.entries.has(key)) {
13100
13977
  space.seen.set(key, content);
13101
13978
  if (!stored) return false;
13102
- deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "vcs", "vcs", "known"));
13979
+ const current = latestOf(space, absolute, stored);
13980
+ if (!current || current.entry.newText === (content ?? "")) return false;
13981
+ deps.record(writeOf(space, absolute, current.entry.newText, content, at, "vcs", "vcs", "known"));
13103
13982
  return true;
13104
13983
  }
13984
+ if (!status && !stored && !space.seen.has(key) && !recentlyWritten(space, absolute)) {
13985
+ noteGapOnce(space, "absent:" + key, absolute, "无版本库状态且文件未改动,未建档");
13986
+ space.seen.set(key, content);
13987
+ return false;
13988
+ }
13105
13989
  const before = await beforeOf(space, key, absolute, stored, status, content);
13106
13990
  if (before.text === null && content === null) {
13107
13991
  space.seen.set(key, null);
13108
13992
  return false;
13109
13993
  }
13994
+ if (!stored && before.text === null && !allowNewWholeFile(space, absolute)) {
13995
+ space.seen.set(key, content);
13996
+ return false;
13997
+ }
13110
13998
  deps.record(writeOf(space, absolute, before.text, content, at, "watch", windows.inAgentWindow(at) ? "agent" : "external", before.kind));
13111
13999
  space.seen.set(key, content);
13112
14000
  return true;
@@ -13338,6 +14226,68 @@ function installExternalCapture(deps) {
13338
14226
  }
13339
14227
  }
13340
14228
  }
14229
+ /** 进程内说明表:随插件装配创建,卸载清空。 */
14230
+ const spaces = /* @__PURE__ */ new Map();
14231
+ /**
14232
+ * @private
14233
+ * @author ddj 2026年11月25号
14234
+ * @description: 取(或建)一个工作区的说明表。
14235
+ * @param cwd 工作区
14236
+ * @returns 说明表
14237
+ */
14238
+ function spaceOf(cwd) {
14239
+ const key = pathKeyOf(cwd);
14240
+ const existing = spaces.get(key);
14241
+ if (existing) return existing;
14242
+ const created = {
14243
+ order: [],
14244
+ byPath: /* @__PURE__ */ new Map()
14245
+ };
14246
+ spaces.set(key, created);
14247
+ return created;
14248
+ }
14249
+ /**
14250
+ * @public
14251
+ * @author ddj 2026年11月25号
14252
+ * @description: 记录一条只读说明;同一文件后写的覆盖先写的,超出上限逐出最旧。
14253
+ * @param cwd 工作区
14254
+ * @param identity 条目身份(文件绝对路径)
14255
+ * @param note 说明文本
14256
+ * @returns 无
14257
+ */
14258
+ function declareNote(cwd, identity, note) {
14259
+ if (!cwd || !identity || !note) return;
14260
+ const space = spaceOf(cwd);
14261
+ const key = pathKeyOf(identity);
14262
+ if (!space.byPath.has(key)) space.order.push(key);
14263
+ space.byPath.set(key, note.slice(0, 500));
14264
+ while (space.order.length > 200) {
14265
+ const oldest = space.order.shift();
14266
+ if (oldest !== void 0) space.byPath.delete(oldest);
14267
+ }
14268
+ }
14269
+ /**
14270
+ * @public
14271
+ * @author ddj 2026年11月25号
14272
+ * @description: 读某个文件的只读说明;没有时返回 undefined。
14273
+ * @param cwd 工作区
14274
+ * @param identity 条目身份(文件绝对路径)
14275
+ * @returns 说明或 undefined
14276
+ */
14277
+ function noteOf(cwd, identity) {
14278
+ return spaces.get(pathKeyOf(cwd))?.byPath.get(pathKeyOf(identity));
14279
+ }
14280
+ /**
14281
+ * @public
14282
+ * @author ddj 2026年11月25号
14283
+ * @description: 清空说明;不传工作区时清全部(插件卸载)。
14284
+ * @param cwd 工作区
14285
+ * @returns 无
14286
+ */
14287
+ function clearNotes(cwd) {
14288
+ if (cwd === void 0) spaces.clear();
14289
+ else spaces.delete(pathKeyOf(cwd));
14290
+ }
13341
14291
  //#endregion
13342
14292
  //#region src/pending/lineDiff.ts
13343
14293
  /** 单窗口 LCS 单元格上限:超过先找锚点;4 MB 表实测约 7 ms。 */
@@ -13871,7 +14821,9 @@ function mergeEntries(earlier, later) {
13871
14821
  sessionIds: unionSessions(earlier, later),
13872
14822
  source: strongerSource(earlier.source, later.source),
13873
14823
  origin: later.origin ?? earlier.origin,
13874
- baseKind: later.baseKind ?? earlier.baseKind
14824
+ baseKind: later.baseKind ?? earlier.baseKind,
14825
+ evidence: strongerEvidence(earlier.evidence, later.evidence),
14826
+ verdict: later.verdict ?? earlier.verdict
13875
14827
  };
13876
14828
  if (later.lineage === void 0 && earlier.lineage !== void 0) merged.lineage = earlier.lineage;
13877
14829
  if (earlier.earlierVersion === "none" && later.earlierVersion === "none") {
@@ -13904,6 +14856,8 @@ function entryFromNew(input) {
13904
14856
  if (input.source !== void 0) entry.source = input.source;
13905
14857
  if (input.origin !== void 0) entry.origin = input.origin;
13906
14858
  if (input.baseKind !== void 0) entry.baseKind = input.baseKind;
14859
+ if (input.evidence !== void 0) entry.evidence = input.evidence;
14860
+ if (input.verdict !== void 0) entry.verdict = input.verdict;
13907
14861
  return entry;
13908
14862
  }
13909
14863
  /**
@@ -14086,7 +15040,7 @@ function pickBlocks(blocks, input) {
14086
15040
  const scope = input.request.scope;
14087
15041
  if (scope === "file" || scope === "all") return [];
14088
15042
  if (scope === "block") {
14089
- const block = blocks.find((item) => item.id === input.request.blockId);
15043
+ const block = findBlock(blocks, input.request.blockId);
14090
15044
  return block ? [block] : null;
14091
15045
  }
14092
15046
  const start = input.request.startLine ?? 0;
@@ -14094,6 +15048,30 @@ function pickBlocks(blocks, input) {
14094
15048
  return blocks.filter((block) => block.newStart <= end && block.newStart + Math.max(block.newLines.length, 1) >= start);
14095
15049
  }
14096
15050
  /**
15051
+ * @private
15052
+ * @author ddj 2026年11月25号
15053
+ * @description: 按 id 找块,找不到再按内容指纹、最后按旧坐标 id 兜底。
15054
+ * 块身份现在是内容指纹,上游行号飘动不会让同一个块换名;旧客户端发来的
15055
+ * `hunkIndex:oldLine:newLine` 仍按行号唯一匹配。
15056
+ * @param blocks 当前差异块
15057
+ * @param blockId 请求里的块 id
15058
+ * @returns 唯一命中的块,找不到或不唯一时 undefined
15059
+ */
15060
+ function findBlock(blocks, blockId) {
15061
+ if (!blockId) return void 0;
15062
+ const exact = blocks.find((block) => block.id === blockId);
15063
+ if (exact) return exact;
15064
+ const fingerprint = blockId.split(":")[1];
15065
+ if (fingerprint !== void 0 && fingerprint !== "") {
15066
+ const byFingerprint = blocks.filter((block) => block.id.split(":")[1] === fingerprint);
15067
+ if (byFingerprint.length === 1) return byFingerprint[0];
15068
+ }
15069
+ const legacy = /^(\d+):(\d+):(\d+)$/.exec(blockId);
15070
+ if (!legacy) return void 0;
15071
+ const byCoordinate = blocks.filter((block) => block.hunkIndex === Number(legacy[1]) && block.oldStart === Number(legacy[2]) && block.newStart === Number(legacy[3]));
15072
+ return byCoordinate.length === 1 ? byCoordinate[0] : void 0;
15073
+ }
15074
+ /**
14097
15075
  * @author ddj 2026年10月29号
14098
15076
  * @description: 把目标块标记为已决定;整文件时把全部块一起标记。
14099
15077
  * @param states 已存块决定
@@ -14140,6 +15118,12 @@ function capabilityOf$1(entry, flags) {
14140
15118
  revert: false,
14141
15119
  reason: "未捕获修改前内容(外部写入):留档可见,但不能撤销,否则会删掉现有代码"
14142
15120
  };
15121
+ if (entry.baseKind === "normalized") return {
15122
+ keep: true,
15123
+ revert: true,
15124
+ confirmRevert: true,
15125
+ reason: "基线与行尾已归一(来自工具回执):撤销会按归一文本写回,写前请确认"
15126
+ };
14143
15127
  if (entry.earlierVersion === "none" && entry.newText.length === 0) return {
14144
15128
  keep: true,
14145
15129
  revert: false,
@@ -14180,41 +15164,72 @@ function diffOf(entry, baselineEmpty = false) {
14180
15164
  }
14181
15165
  //#endregion
14182
15166
  //#region src/pending/store.ts
15167
+ /** 派生结果缓存:列表每轮都重算全部条目的整文件差异,是卡顿主因之一;键取「revision + 两侧长度」。 */
15168
+ const derivedCache = /* @__PURE__ */ new Map();
15169
+ /** 派生缓存条数上限:超过就丢最早的一条,避免长会话无限增长。 */
15170
+ const DERIVED_MAX = 256;
14183
15171
  /**
14184
- * @author ddj 2026年10月29号
14185
- * @description: 统计一次差异的增删行数;非文本差异统一记 0/0。
15172
+ * @private
15173
+ * @author ddj 2026年11月25号
15174
+ * @description: 一次 diff 同时给出增删行数与块状态,并按内容签名缓存;内容一变缓存自动失效。
14186
15175
  * @param entry 待审条目
14187
15176
  * @param baselineEmpty 基线置空(新建文件按全量新增计)
14188
- * @returns 增删行数
15177
+ * @param revision 条目版本号;未知时传 -1(按内容长度与时间退化判定)
15178
+ * @returns 增删行数与块状态
14189
15179
  */
14190
- function countsOf(entry, baselineEmpty = false) {
15180
+ function derivedOf(entry, baselineEmpty, revision) {
15181
+ const signature = `${revision}:${baselineEmpty ? 1 : 0}:${entry.earlierVersion}:${entry.oldText.length}:${entry.newText.length}:${entry.updatedAt}`;
15182
+ const hit = derivedCache.get(entry.id);
15183
+ if (hit && hit.signature === signature) return hit;
14191
15184
  const diff = diffOf(entry, baselineEmpty);
14192
- if (diff.kind !== "text") return {
14193
- added: 0,
14194
- deleted: 0
14195
- };
14196
15185
  let added = 0;
14197
15186
  let deleted = 0;
14198
- for (const hunk of diff.hunks) for (const line of hunk.lines) if (line.startsWith("+")) added++;
14199
- else if (line.startsWith("-")) deleted++;
14200
- return {
15187
+ let blocks = [];
15188
+ if (diff.kind === "text") {
15189
+ for (const hunk of diff.hunks) for (const line of hunk.lines) if (line.startsWith("+")) added++;
15190
+ else if (line.startsWith("-")) deleted++;
15191
+ blocks = reviewBlocks(diff).map((block) => ({
15192
+ id: block.id,
15193
+ decision: "pending"
15194
+ }));
15195
+ }
15196
+ const value = {
15197
+ signature,
14201
15198
  added,
14202
- deleted
15199
+ deleted,
15200
+ blocks
14203
15201
  };
15202
+ if (derivedCache.size >= DERIVED_MAX) {
15203
+ const oldest = derivedCache.keys().next().value;
15204
+ if (oldest !== void 0) derivedCache.delete(oldest);
15205
+ }
15206
+ derivedCache.set(entry.id, value);
15207
+ return value;
14204
15208
  }
14205
15209
  /**
14206
- * @author ddj 2026年10月30号
15210
+ * @author ddj 2026年10月29号 / 2026年11月25号
15211
+ * @description: 统计一次差异的增删行数;非文本差异统一记 0/0。
15212
+ * @param entry 待审条目
15213
+ * @param baselineEmpty 基线置空(新建文件按全量新增计)
15214
+ * @param revision 条目版本号
15215
+ * @returns 增删行数
15216
+ */
15217
+ function countsOf(entry, baselineEmpty = false, revision = -1) {
15218
+ const derived = derivedOf(entry, baselineEmpty, revision);
15219
+ return {
15220
+ added: derived.added,
15221
+ deleted: derived.deleted
15222
+ };
15223
+ }
15224
+ /**
15225
+ * @author ddj 2026年10月30号 / 2026年11月25号
14207
15226
  * @description: 由当前累计条目现场推导块身份;块是差异的纯函数,落库的只是决定状态。
14208
15227
  * @param entry 累计条目
15228
+ * @param revision 条目版本号
14209
15229
  * @returns 块状态列表(决定一律 pending,判定推进后由下一次推导自然收窄)
14210
15230
  */
14211
- function blockStatesOf(entry) {
14212
- const diff = diffOf(entry);
14213
- if (diff.kind !== "text") return [];
14214
- return reviewBlocks(diff).map((block) => ({
14215
- id: block.id,
14216
- decision: "pending"
14217
- }));
15231
+ function blockStatesOf(entry, revision = -1) {
15232
+ return derivedOf(entry, false, revision).blocks;
14218
15233
  }
14219
15234
  /**
14220
15235
  * @author ddj 2026年10月29号
@@ -14234,7 +15249,9 @@ function foldWrite(stored, write) {
14234
15249
  updatedAt: write.now,
14235
15250
  source: sourceOfTool(write.tool),
14236
15251
  origin: originOf(write),
14237
- baseKind: write.before === null ? "absent" : write.baseKind ?? "known"
15252
+ baseKind: write.before === null ? "absent" : write.baseKind ?? "known",
15253
+ evidence: write.evidence ?? "snapshot",
15254
+ verdict: write.verdict ?? "changed"
14238
15255
  });
14239
15256
  if (!stored) return {
14240
15257
  entry: fresh,
@@ -14280,7 +15297,7 @@ function originOf(write) {
14280
15297
  */
14281
15298
  function itemOf(stored, baselineEmpty = false) {
14282
15299
  const { entry, flags } = stored;
14283
- const counts = countsOf(entry, baselineEmpty);
15300
+ const counts = countsOf(entry, baselineEmpty, flags.revision);
14284
15301
  const item = {
14285
15302
  id: entry.id,
14286
15303
  path: entry.path,
@@ -14298,7 +15315,9 @@ function itemOf(stored, baselineEmpty = false) {
14298
15315
  sessionIds: entry.sessionIds,
14299
15316
  source: entry.source ?? "tool",
14300
15317
  origin: entry.origin ?? "agent",
14301
- baseKind: entry.baseKind ?? "known"
15318
+ baseKind: entry.baseKind ?? "known",
15319
+ evidence: entry.evidence ?? "snapshot",
15320
+ verdict: entry.verdict ?? "changed"
14302
15321
  };
14303
15322
  if (entry.lineage !== void 0) item.lineage = entry.lineage;
14304
15323
  return item;
@@ -14335,7 +15354,7 @@ function emptyBaseOf(cwd, stored, sourceAdds = /* @__PURE__ */ new Map()) {
14335
15354
  function loadPage(cwd, _sessionId) {
14336
15355
  const visible = loadEntries(cwd);
14337
15356
  const sourceAdds = /* @__PURE__ */ new Map();
14338
- const items = visible.map((stored) => itemOf(stored, emptyBaseOf(cwd, stored, sourceAdds)));
15357
+ const items = visible.map((stored) => withNote(cwd, itemOf(stored, emptyBaseOf(cwd, stored, sourceAdds))));
14339
15358
  const gaps = pendingGaps(cwd);
14340
15359
  for (const stored of visible) if (stored.flags.oversized) gaps.push(`${stored.entry.path}: 文本超出上限,仅保留标记`);
14341
15360
  return {
@@ -14346,6 +15365,21 @@ function loadPage(cwd, _sessionId) {
14346
15365
  };
14347
15366
  }
14348
15367
  /**
15368
+ * @private
15369
+ * @author ddj 2026年11月25号
15370
+ * @description: 挂上模型的只读说明;说明只在内存里,不落库也不参与判定。
15371
+ * @param cwd 工作区
15372
+ * @param item 列表项
15373
+ * @returns 可能带说明的列表项
15374
+ */
15375
+ function withNote(cwd, item) {
15376
+ const note = noteOf(cwd, item.id);
15377
+ return note === void 0 ? item : {
15378
+ ...item,
15379
+ note
15380
+ };
15381
+ }
15382
+ /**
14349
15383
  * @author ddj 2026年10月29号
14350
15384
  * @description: 读单条详情,包含可交给现有面板渲染的差异与块决定。
14351
15385
  * @param cwd 工作区
@@ -14359,9 +15393,9 @@ function loadDetail(cwd, id, baselineEmpty = false) {
14359
15393
  const emptyBase = baselineEmpty || emptyBaseOf(cwd, stored);
14360
15394
  const diff = diffOf(stored.entry, emptyBase);
14361
15395
  return {
14362
- item: itemOf(stored, emptyBase),
15396
+ item: withNote(cwd, itemOf(stored, emptyBase)),
14363
15397
  diff,
14364
- blocks: blockStatesOf(stored.entry),
15398
+ blocks: blockStatesOf(stored.entry, stored.flags.revision),
14365
15399
  capability: capabilityOf$1(stored.entry, stored.flags)
14366
15400
  };
14367
15401
  }
@@ -14514,7 +15548,7 @@ async function applyDecide(fs, cwd, request, signal, policy) {
14514
15548
  ok: false,
14515
15549
  reason: "unknown-item"
14516
15550
  };
14517
- const beforeBlocks = blockStatesOf(stored.entry);
15551
+ const beforeBlocks = blockStatesOf(stored.entry, stored.flags.revision);
14518
15552
  const outcome = await decide({
14519
15553
  request,
14520
15554
  entry: stored.entry,
@@ -14535,19 +15569,15 @@ async function applyDecide(fs, cwd, request, signal, policy) {
14535
15569
  flags: outcome.flags
14536
15570
  });
14537
15571
  saveBlocks(cwd, request.id, outcome.blocks);
14538
- pushHistory(cwd, "decide", request.id, JSON.stringify({
14539
- before: {
14540
- entry: stored.entry,
14541
- flags: stored.flags,
14542
- blocks: beforeBlocks
14543
- },
14544
- after: {
14545
- entry: outcome.entry,
14546
- flags: outcome.flags,
14547
- blocks: outcome.blocks
14548
- },
15572
+ pushHistory(cwd, {
15573
+ entryId: request.id,
15574
+ path: stored.entry.path,
15575
+ kind: request.decision === "accepted" ? "keep" : "revert",
15576
+ earlier: stored.entry.earlierVersion,
15577
+ baseline: stored.entry.oldText,
15578
+ content: stored.entry.newText,
14549
15579
  wrote: outcome.wrote
14550
- }), Date.now());
15580
+ }, Date.now());
14551
15581
  return outcome;
14552
15582
  }
14553
15583
  /**
@@ -14593,7 +15623,7 @@ async function keepAll(cwd, items) {
14593
15623
  });
14594
15624
  continue;
14595
15625
  }
14596
- const beforeBlocks = blockStatesOf(before.entry);
15626
+ const beforeBlocks = blockStatesOf(before.entry, before.flags.revision);
14597
15627
  const outcomeOf = await decide({
14598
15628
  request: {
14599
15629
  sessionId: before.entry.sessionId,
@@ -14630,20 +15660,7 @@ async function keepAll(cwd, items) {
14630
15660
  entry: outcomeOf.entry,
14631
15661
  flags: outcomeOf.flags
14632
15662
  },
14633
- blocks: outcomeOf.blocks,
14634
- snapshot: JSON.stringify({
14635
- before: {
14636
- entry: before.entry,
14637
- flags: before.flags,
14638
- blocks: beforeBlocks
14639
- },
14640
- after: {
14641
- entry: outcomeOf.entry,
14642
- flags: outcomeOf.flags,
14643
- blocks: outcomeOf.blocks
14644
- },
14645
- wrote: outcomeOf.wrote
14646
- })
15663
+ blocks: outcomeOf.blocks
14647
15664
  });
14648
15665
  }
14649
15666
  const displayOf = new Map(items.map((item) => [item.id, item.display]));
@@ -14685,8 +15702,8 @@ async function importFromVcs(shell, cwd, sessionId, options = {}) {
14685
15702
  }
14686
15703
  /**
14687
15704
  * @author ddj 2026年10月30号
14688
- * @description: 撤销或重做最近一次判定。先按 operationId 判幂等,再据栈顶记录判定方向是否合法,
14689
- * 只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
15705
+ * @description: 撤销或重做最近一次判定。一条路径只有一行撤销记录:撤销回到判定前的两侧内容,
15706
+ * 重做再按同一判定推进一次;只有写盘过的判定才反向写盘,写盘失败时条目状态保持原样。
14690
15707
  * @param fs 文件系统
14691
15708
  * @param cwd 工作区
14692
15709
  * @param move 撤销/重做请求
@@ -14701,21 +15718,16 @@ async function undoDecide(fs, cwd, move, signal, policy) {
14701
15718
  ok: false,
14702
15719
  reason: move.direction === "undo" ? "no-undo" : "no-redo"
14703
15720
  };
14704
- const snapshot = parseSnapshot(record.snapshot);
14705
- if (!snapshot) return {
14706
- ok: false,
14707
- reason: "bad-history"
14708
- };
14709
- const stored = loadEntries(cwd).find((item) => item.entry.id === record.entryId);
15721
+ const stored = loadEntry(cwd, record.entryId);
14710
15722
  if (!stored) return {
14711
15723
  ok: false,
14712
15724
  reason: "unknown-item"
14713
15725
  };
14714
- const target = move.direction === "undo" ? snapshot.before : snapshot.after;
15726
+ const target = replayTargetOf(stored, record, move.direction === "undo");
14715
15727
  writeOp(cwd, move.operationId, JSON.stringify(move), "prepared");
14716
15728
  let wrote = false;
14717
- if (snapshot.wrote) {
14718
- const result = await writeBack(fs, cwd, stored, target, signal, policy);
15729
+ if (target.write) {
15730
+ const result = await writeBack(fs, cwd, stored, target.state, signal, policy);
14719
15731
  if (!result.ok) return {
14720
15732
  ok: false,
14721
15733
  reason: result.reason
@@ -14723,16 +15735,16 @@ async function undoDecide(fs, cwd, move, signal, policy) {
14723
15735
  wrote = true;
14724
15736
  }
14725
15737
  saveEntry(cwd, {
14726
- entry: target.entry,
14727
- flags: target.flags
15738
+ entry: target.state.entry,
15739
+ flags: target.state.flags
14728
15740
  });
14729
- saveBlocks(cwd, record.entryId, target.blocks);
14730
- setHistoryState(cwd, record.id, move.direction === "undo" ? "undone" : "applied");
15741
+ saveBlocks(cwd, record.entryId, target.state.blocks);
15742
+ setHistoryState(cwd, record.entryId, move.direction === "undo" ? "undone" : "applied");
14731
15743
  const outcome = {
14732
15744
  ok: true,
14733
15745
  item: itemOf({
14734
- entry: target.entry,
14735
- flags: target.flags
15746
+ entry: target.state.entry,
15747
+ flags: target.state.flags
14736
15748
  }),
14737
15749
  wrote
14738
15750
  };
@@ -14740,6 +15752,59 @@ async function undoDecide(fs, cwd, move, signal, policy) {
14740
15752
  return outcome;
14741
15753
  }
14742
15754
  /**
15755
+ * @private
15756
+ * @author ddj 2026年11月25号
15757
+ * @description: 由当前条目与撤销行推导撤销/重做后的状态:Keep 只动基线,Revert 还要把内容写回盘。
15758
+ * @param stored 当前条目
15759
+ * @param record 撤销行
15760
+ * @param undone 是否撤销(false 为重做)
15761
+ * @returns 目标状态与是否需要写盘
15762
+ */
15763
+ function replayTargetOf(stored, record, undone) {
15764
+ const revision = stored.flags.revision + 1;
15765
+ if (record.kind === "keep") {
15766
+ const baseline = undone ? record.baseline : stored.entry.newText;
15767
+ const entry = {
15768
+ ...stored.entry,
15769
+ oldText: baseline,
15770
+ earlierVersion: undone ? record.earlier : "file",
15771
+ updatedAt: Date.now()
15772
+ };
15773
+ delete entry.unseen;
15774
+ return {
15775
+ state: {
15776
+ entry,
15777
+ flags: {
15778
+ ...stored.flags,
15779
+ missing: false,
15780
+ revision
15781
+ },
15782
+ blocks: []
15783
+ },
15784
+ write: false
15785
+ };
15786
+ }
15787
+ const missing = !undone && record.earlier === "none";
15788
+ const entry = {
15789
+ ...stored.entry,
15790
+ newText: missing ? "" : undone ? record.content : record.baseline,
15791
+ updatedAt: Date.now()
15792
+ };
15793
+ delete entry.unseen;
15794
+ return {
15795
+ state: {
15796
+ entry,
15797
+ flags: {
15798
+ ...stored.flags,
15799
+ missing,
15800
+ revision
15801
+ },
15802
+ blocks: []
15803
+ },
15804
+ write: true
15805
+ };
15806
+ }
15807
+ /**
14743
15808
  * @author ddj 2026年10月30号
14744
15809
  * @description: 把文件内容恢复到目标快照:目标为缺失则删除,否则按版本守卫写回并读回校验。
14745
15810
  * @param fs 文件系统
@@ -14754,21 +15819,6 @@ async function writeBack(fs, cwd, stored, target, signal, policy) {
14754
15819
  return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy, true)(target.entry.newText);
14755
15820
  }
14756
15821
  /**
14757
- * @author ddj 2026年10月30号
14758
- * @description: 解析历史快照;损坏时返回 null,不猜测内容。
14759
- * @param text 快照文本
14760
- * @returns 快照或 null
14761
- */
14762
- function parseSnapshot(text) {
14763
- try {
14764
- const parsed = JSON.parse(text);
14765
- if (!parsed?.before?.entry || !parsed?.after?.entry) return null;
14766
- return parsed;
14767
- } catch {
14768
- return null;
14769
- }
14770
- }
14771
- /**
14772
15822
  * @private
14773
15823
  * @author ddj 2026年11月04号
14774
15824
  * @description 版本—内容—版本读取,防止将新版本令牌与旧内容拼成写入依据。
@@ -14871,6 +15921,32 @@ function removeEntry(cwd, id, revision) {
14871
15921
  dropEntry(cwd, id);
14872
15922
  return true;
14873
15923
  }
15924
+ /** 清库默认口径:只清 watch 通道、空基线的条目——幽灵记录就长这样。 */
15925
+ const PURGE_DEFAULT_SOURCES = ["watch"];
15926
+ /** 清库默认基线口径:空基线(改前内容缺失)。 */
15927
+ const PURGE_DEFAULT_BASE_KINDS = ["absent"];
15928
+ /**
15929
+ * @public
15930
+ * @author ddj 2026-11-24
15931
+ * @description: 清掉指定通道的待审条目(幽灵记录治理入口)。dryRun 只报数;
15932
+ * 真删之后按需 VACUUM,把已删行占的页还给磁盘。
15933
+ * @param cwd 工作区
15934
+ * @param filter 筛选条件(缺省 watch + absent)
15935
+ * @param options dryRun 只数不删;vacuum 删除后是否回收
15936
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
15937
+ */
15938
+ function purgePending(cwd, filter = {}, options = {}) {
15939
+ const outcome = purgeEntries(cwd, {
15940
+ sources: filter.sources && filter.sources.length ? filter.sources : PURGE_DEFAULT_SOURCES,
15941
+ baseKinds: filter.baseKinds && filter.baseKinds.length ? filter.baseKinds : PURGE_DEFAULT_BASE_KINDS,
15942
+ before: filter.before
15943
+ }, options.dryRun === true);
15944
+ if (options.dryRun || !outcome.removed || !options.vacuum) return outcome;
15945
+ return {
15946
+ ...outcome,
15947
+ vacuumMs: vacuumEntries(cwd)
15948
+ };
15949
+ }
14874
15950
  /**
14875
15951
  * @author ddj 2026年10月29号
14876
15952
  * @description: 取错误码用于拒绝原因,没有则回落到消息文本。
@@ -14881,6 +15957,426 @@ function reasonOf(error) {
14881
15957
  const code = error.code;
14882
15958
  return typeof code === "string" ? code : String(error);
14883
15959
  }
15960
+ /** 真删前备份文件名后缀。 */
15961
+ const BACKUP_SUFFIX = ".before-purge.bak";
15962
+ /**
15963
+ * @author ddj 2026-11-24
15964
+ * @description: 挑出要删的批次:先按保留期,再按每路径上限,未判完的整批跳过。
15965
+ * @param db 工作区归档库连接
15966
+ * @param options 清理选项
15967
+ * @returns 候选批次 id 与两个统计口径
15968
+ */
15969
+ function pickCandidates(db, options) {
15970
+ const retentionDays = options.retentionDays ?? 30;
15971
+ const keepBatches = options.keepBatches ?? 20;
15972
+ const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1e3;
15973
+ const rows = db.prepare(`SELECT b.id, b.path, b.at, b.pending,
15974
+ (SELECT COUNT(*) FROM records r WHERE r.batch_id = b.id AND r.pending > 0) AS open_records
15975
+ FROM batches b ORDER BY b.path, b.at DESC, b.id DESC`).all();
15976
+ const seen = /* @__PURE__ */ new Map();
15977
+ const picked = /* @__PURE__ */ new Set();
15978
+ let expired = 0;
15979
+ let overCap = 0;
15980
+ let keptPending = 0;
15981
+ for (const row of rows) {
15982
+ const id = Number(row.id);
15983
+ const path = String(row.path);
15984
+ const order = (seen.get(path) ?? 0) + 1;
15985
+ seen.set(path, order);
15986
+ const at = Date.parse(String(row.at));
15987
+ const isExpired = Number.isFinite(at) && at < cutoff;
15988
+ const isOverCap = order > keepBatches;
15989
+ if (!isExpired && !isOverCap) continue;
15990
+ if (isExpired) expired += 1;
15991
+ if (isOverCap) overCap += 1;
15992
+ if (Number(row.pending) > 0 || Number(row.open_records) > 0) {
15993
+ keptPending += 1;
15994
+ continue;
15995
+ }
15996
+ picked.add(id);
15997
+ }
15998
+ return {
15999
+ ids: [...picked],
16000
+ expired,
16001
+ overCap,
16002
+ keptPending
16003
+ };
16004
+ }
16005
+ /**
16006
+ * @author ddj 2026年11月25号
16007
+ * @description: 截断幂等表:撤销栈已改成「一条路径一行」,不再按步裁剪。
16008
+ * @param db 工作区归档库连接
16009
+ * @param keepOps 幂等表保留条数
16010
+ * @returns 删除的历史行数(恒为 0,保留字段只为回执口径不变)
16011
+ */
16012
+ function trimPendingTables(db, keepOps) {
16013
+ db.prepare(`DELETE FROM pending_ops WHERE rowid NOT IN (
16014
+ SELECT rowid FROM pending_ops ORDER BY rowid DESC LIMIT ?)`).run(keepOps);
16015
+ return 0;
16016
+ }
16017
+ /**
16018
+ * @author ddj 2026-11-24
16019
+ * @description: 真删:单事务内按「撤销意图 → 记录 → 批次」顺序清,备份在事务之前做。
16020
+ * @param db 工作区归档库连接
16021
+ * @param ids 候选批次 id
16022
+ * @returns 删除的记录数与批次数
16023
+ */
16024
+ function removeBatches(db, ids) {
16025
+ const callIds = db.prepare("SELECT call_id FROM records WHERE batch_id = ?");
16026
+ const dropIntent = db.prepare("DELETE FROM revert_intents WHERE call_id = ?");
16027
+ const dropRecords = db.prepare("DELETE FROM records WHERE batch_id = ?");
16028
+ const dropBatch = db.prepare("DELETE FROM batches WHERE id = ?");
16029
+ let records = 0;
16030
+ let batches = 0;
16031
+ db.exec("BEGIN IMMEDIATE");
16032
+ try {
16033
+ for (const id of ids) {
16034
+ for (const row of callIds.all(id)) dropIntent.run(String(row.call_id));
16035
+ records += Number(dropRecords.run(id).changes);
16036
+ batches += Number(dropBatch.run(id).changes);
16037
+ }
16038
+ db.exec("COMMIT");
16039
+ } catch (error) {
16040
+ if (db.isTransaction) db.exec("ROLLBACK");
16041
+ throw error;
16042
+ }
16043
+ return {
16044
+ records,
16045
+ batches
16046
+ };
16047
+ }
16048
+ /**
16049
+ * @public
16050
+ * @author ddj 2026-11-24
16051
+ * @description: 归档库清理入口:保留期 + 每文件上限 + 撤销栈截断,可选 VACUUM。
16052
+ * @param cwd 工作区
16053
+ * @param options 清理选项
16054
+ * @returns 三个统计口径与实际删除行数
16055
+ * @throws 归档库不可用或事务失败
16056
+ */
16057
+ function purgeArchiveDb(cwd, options = {}) {
16058
+ const db = dbFor(cwd);
16059
+ const { ids, expired, overCap, keptPending } = pickCandidates(db, options);
16060
+ const dryRun = options.dryRun !== false;
16061
+ const keepOps = options.keepOps ?? 500;
16062
+ if (dryRun) return {
16063
+ expired,
16064
+ overCap,
16065
+ keptPending,
16066
+ removed: {
16067
+ records: 0,
16068
+ batches: 0,
16069
+ history: 0
16070
+ }
16071
+ };
16072
+ if (ids.length) backupBeforePurge(db, cwd);
16073
+ const removedBatches = removeBatches(db, ids);
16074
+ const history = activeReady(cwd) ? trimPendingTables(db, keepOps) : 0;
16075
+ const outcome = {
16076
+ expired,
16077
+ overCap,
16078
+ keptPending,
16079
+ removed: {
16080
+ ...removedBatches,
16081
+ history
16082
+ }
16083
+ };
16084
+ if (options.vacuum !== false && (removedBatches.batches || history)) outcome.vacuumMs = vacuumOf(db);
16085
+ return outcome;
16086
+ }
16087
+ /**
16088
+ * @private
16089
+ * @author ddj 2026-11-24
16090
+ * @description: 回收已删行占用的页;失败只记日志,不影响已完成的删除。
16091
+ * @param db 工作区归档库连接
16092
+ * @returns 耗时毫秒
16093
+ */
16094
+ function vacuumOf(db) {
16095
+ const started = Date.now();
16096
+ try {
16097
+ db.exec("VACUUM");
16098
+ } catch (error) {
16099
+ log.warn("归档库 VACUUM 失败:" + String(error));
16100
+ }
16101
+ return Date.now() - started;
16102
+ }
16103
+ /**
16104
+ * @private
16105
+ * @author ddj 2026-11-24
16106
+ * @description: 真删前留一份备份;同名覆盖,每个工作区只占一份。
16107
+ * @param db 工作区归档库连接
16108
+ * @param cwd 工作区
16109
+ * @returns 无
16110
+ */
16111
+ function backupBeforePurge(db, cwd) {
16112
+ const target = archiveDbFile(cwd) + BACKUP_SUFFIX;
16113
+ try {
16114
+ rmSync(target, { force: true });
16115
+ db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
16116
+ } catch (error) {
16117
+ log.warn("归档库清理前备份失败(继续执行):" + String(error));
16118
+ }
16119
+ }
16120
+ /**
16121
+ * @public
16122
+ * @author ddj 2026-11-24
16123
+ * @description: 列出本机所有归档库对应的工作区:读每个库里的 metadata.cwd,
16124
+ * 不依赖有没有活跃会话。读不出来的库跳过并记日志。
16125
+ * @param home DSH home
16126
+ * @returns 工作区绝对路径清单
16127
+ */
16128
+ function listArchiveWorkspaces(home = dshHome()) {
16129
+ let names = [];
16130
+ try {
16131
+ names = readdirSync(join(home, PLUGIN_ID, "data", "archive")).filter((name) => name.endsWith(".sqlite"));
16132
+ } catch {
16133
+ return [];
16134
+ }
16135
+ const found = [];
16136
+ for (const name of names) {
16137
+ const file = join(home, PLUGIN_ID, "data", "archive", name);
16138
+ let db;
16139
+ try {
16140
+ db = new DatabaseSync(file, { readOnly: true });
16141
+ const row = db.prepare("SELECT value FROM metadata WHERE name='cwd'").get();
16142
+ if (row?.value) found.push(String(row.value));
16143
+ } catch (error) {
16144
+ log.debug("跳过不可读归档库:" + file + " " + String(error));
16145
+ } finally {
16146
+ try {
16147
+ db?.close();
16148
+ } catch {}
16149
+ }
16150
+ }
16151
+ return found;
16152
+ }
16153
+ /**
16154
+ * @public
16155
+ * @author ddj 2026-11-24 / 2026年11月25号
16156
+ * @description: 对所有工作区归档库跑一遍清理;删除在进程内做完(快),整库重写交给子进程。
16157
+ * 单个库失败只记日志,不影响其他库。
16158
+ * @param options 扫描选项
16159
+ * @returns 扫描到的库数与删除的行数合计
16160
+ */
16161
+ function sweepArchives(options = {}) {
16162
+ const run = options.run ?? purgeArchiveDb;
16163
+ const workspaces = listArchiveWorkspaces(options.home);
16164
+ const jobs = [];
16165
+ let removed = 0;
16166
+ for (const cwd of workspaces) try {
16167
+ const outcome = run(cwd, {
16168
+ dryRun: false,
16169
+ vacuum: false
16170
+ });
16171
+ removed += outcome.removed.batches + outcome.removed.history;
16172
+ if (!outcome.removed.batches && !outcome.removed.history) continue;
16173
+ jobs.push({
16174
+ file: archiveDbFile(cwd, options.home),
16175
+ backup: archiveDbFile(cwd, options.home) + BACKUP_SUFFIX
16176
+ });
16177
+ log.debug(`归档库清理:${cwd} 批次 ${outcome.removed.batches},历史 ${outcome.removed.history}`);
16178
+ } catch (error) {
16179
+ log.debug("归档库清理跳过:" + cwd + " " + String(error));
16180
+ }
16181
+ if (jobs.length) {
16182
+ const rewrite = options.rewrite ?? rewriteInChild;
16183
+ try {
16184
+ rewrite(jobs);
16185
+ } catch (error) {
16186
+ log.warn("归档库重写调度失败(库已删行,未回收空间):" + String(error));
16187
+ }
16188
+ }
16189
+ return {
16190
+ workspaces: workspaces.length,
16191
+ removed,
16192
+ rewrites: jobs.length
16193
+ };
16194
+ }
16195
+ /**
16196
+ * @private
16197
+ * @author ddj 2026年11月25号
16198
+ * @description: 起一个独立 Node 子进程做备份与 VACUUM。这两步是整库读写,留在宿主里会把
16199
+ * 事件循环堵住十几秒,所有 RPC(含文件读取、差异渲染)都会一起卡住。
16200
+ * 子进程只认「文件 + 备份路径」,不含任何业务规则,规则仍只有 {@link purgeArchiveDb} 一份。
16201
+ * @param jobs 重写任务
16202
+ * @returns 无(不等待完成)
16203
+ */
16204
+ function rewriteInChild(jobs) {
16205
+ try {
16206
+ closeArchiveDbs();
16207
+ } catch {}
16208
+ const script = [
16209
+ "const { DatabaseSync } = require('node:sqlite')",
16210
+ "const { rmSync } = require('node:fs')",
16211
+ "const jobs = JSON.parse(process.argv[1])",
16212
+ "for (const job of jobs) {",
16213
+ " let db",
16214
+ " try {",
16215
+ " db = new DatabaseSync(job.file, { timeout: 15000 })",
16216
+ " db.exec('PRAGMA busy_timeout=15000')",
16217
+ " if (job.backup) {",
16218
+ " try { rmSync(job.backup, { force: true }) } catch (e) { /* 备份覆盖失败不阻断 */ }",
16219
+ " db.exec(\"VACUUM INTO '\" + job.backup.replace(/'/g, \"''\") + \"'\")",
16220
+ " }",
16221
+ " db.exec('VACUUM')",
16222
+ " } catch (error) {",
16223
+ " console.error(String(error))",
16224
+ " process.exitCode = 1",
16225
+ " } finally {",
16226
+ " try { db && db.close() } catch (e) { /* 已关闭 */ }",
16227
+ " }",
16228
+ "}"
16229
+ ].join("\n");
16230
+ const child = spawn(process.execPath, [
16231
+ "-e",
16232
+ script,
16233
+ JSON.stringify(jobs)
16234
+ ], {
16235
+ stdio: [
16236
+ "ignore",
16237
+ "ignore",
16238
+ "pipe"
16239
+ ],
16240
+ windowsHide: true
16241
+ });
16242
+ let stderr = "";
16243
+ child.stderr?.on("data", (chunk) => {
16244
+ stderr += String(chunk);
16245
+ });
16246
+ child.on("error", (error) => log.warn("归档库重写子进程启动失败:" + String(error)));
16247
+ child.on("exit", (code) => {
16248
+ if (code === 0) log.debug("归档库重写完成:" + jobs.length + " 个库");
16249
+ else log.warn("归档库重写子进程退出码 " + String(code) + ":" + stderr.slice(0, 300));
16250
+ });
16251
+ if (typeof child.unref === "function") child.unref();
16252
+ }
16253
+ /**
16254
+ * @public
16255
+ * @author ddj 2026年11月25号
16256
+ * @description: 单个工作区库的备份与回收页交给子进程;RPC 层删完行后调它,不再原地 VACUUM。
16257
+ * @param cwd 工作区
16258
+ * @param home DSH home(测试可注入)
16259
+ * @returns 无
16260
+ */
16261
+ function scheduleArchiveRewrite(cwd, home = dshHome()) {
16262
+ const file = archiveDbFile(cwd, home);
16263
+ try {
16264
+ rewriteInChild([{
16265
+ file,
16266
+ backup: file + BACKUP_SUFFIX
16267
+ }]);
16268
+ } catch (error) {
16269
+ log.warn("归档库重写调度失败(库已删行,未回收空间):" + String(error));
16270
+ }
16271
+ }
16272
+ /**
16273
+ * @private
16274
+ * @author ddj 2026年11月25号
16275
+ * @description: 今日是否已经扫过:两个宿主(桌面端与 Web 端)共用同一份 home,避免一天扫两遍。
16276
+ * @param home DSH home
16277
+ * @returns 已扫过返回 true
16278
+ */
16279
+ function sweptToday(home) {
16280
+ const stamp = join(home, PLUGIN_ID, "data", "archive", ".sweep-" + (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
16281
+ try {
16282
+ if (existsSync(stamp)) return true;
16283
+ mkdirSync(dirname(stamp), { recursive: true });
16284
+ writeFileSync(stamp, (/* @__PURE__ */ new Date()).toISOString(), "utf8");
16285
+ return false;
16286
+ } catch {
16287
+ return false;
16288
+ }
16289
+ }
16290
+ /**
16291
+ * @public
16292
+ * @author ddj 2026-11-24
16293
+ * @description: 每日自动清理:启动后延迟跑一次,之后每 24 小时一次;返回可释放的句柄。
16294
+ * @param options 扫描选项
16295
+ * @returns 可释放句柄
16296
+ */
16297
+ function startArchiveSweep(options = {}) {
16298
+ let stopped = false;
16299
+ const run = () => {
16300
+ if (stopped) return;
16301
+ if (sweptToday(options.home ?? dshHome())) return;
16302
+ try {
16303
+ sweepArchives(options);
16304
+ } catch (error) {
16305
+ log.warn("归档库每日清理失败:" + String(error));
16306
+ }
16307
+ };
16308
+ const first = setTimeout(run, options.delayMs ?? 9e4);
16309
+ const timer = setInterval(run, options.intervalMs ?? 864e5);
16310
+ if (typeof first.unref === "function") first.unref();
16311
+ if (typeof timer.unref === "function") timer.unref();
16312
+ return { dispose() {
16313
+ stopped = true;
16314
+ clearTimeout(first);
16315
+ clearInterval(timer);
16316
+ } };
16317
+ }
16318
+ /** 最近一次超过阈值的操作,用于阻塞归因。 */
16319
+ let recent;
16320
+ /**
16321
+ * @public
16322
+ * @author ddj 2026年11月25号
16323
+ * @description: 记录一次操作耗时;超过阈值落一条 warn,并记住它供阻塞归因。
16324
+ * @param name 操作名(如 `rpc:edrv.review.list`)
16325
+ * @param ms 耗时毫秒
16326
+ * @param note 附加说明(如条目数)
16327
+ * @returns 无
16328
+ */
16329
+ function noteOperation(name, ms, note = "") {
16330
+ if (ms < 300) return;
16331
+ recent = {
16332
+ name,
16333
+ ms
16334
+ };
16335
+ log.warn(`[slow] ${name} ${Math.round(ms)}ms${note ? " " + note : ""}`);
16336
+ }
16337
+ /**
16338
+ * @public
16339
+ * @author ddj 2026年11月25号
16340
+ * @description: 开始计时;返回的函数在调用时结算。用闭包而不用 async 包装,避免改动既有返回类型。
16341
+ * @param name 操作名
16342
+ * @param note 附加说明
16343
+ * @returns 结算函数
16344
+ */
16345
+ function beginOperation(name, note = "") {
16346
+ const started = performance$1.now();
16347
+ return () => {
16348
+ noteOperation(name, performance$1.now() - started, note);
16349
+ };
16350
+ }
16351
+ /**
16352
+ * @public
16353
+ * @author ddj 2026年11月25号
16354
+ * @description: 启动事件循环看门狗:每个周期检查最大延迟,超过阈值就记一条并带上最近慢操作。
16355
+ * @param intervalMs 检查周期(毫秒)
16356
+ * @returns 可释放句柄
16357
+ */
16358
+ function startLoopWatchdog(intervalMs = 5e3) {
16359
+ const histogram = monitorEventLoopDelay({ resolution: 20 });
16360
+ try {
16361
+ histogram.enable();
16362
+ } catch {}
16363
+ const timer = setInterval(() => {
16364
+ try {
16365
+ const worst = histogram.max / 1e6;
16366
+ histogram.reset();
16367
+ if (!Number.isFinite(worst) || worst < 500) return;
16368
+ const cause = recent ? `;最近慢操作 ${recent.name} ${Math.round(recent.ms)}ms` : "";
16369
+ log.warn(`[slow] 事件循环阻塞 ${Math.round(worst)}ms${cause}`);
16370
+ } catch {}
16371
+ }, intervalMs);
16372
+ if (typeof timer.unref === "function") timer.unref();
16373
+ return { dispose() {
16374
+ clearInterval(timer);
16375
+ try {
16376
+ histogram.disable();
16377
+ } catch {}
16378
+ } };
16379
+ }
14884
16380
  //#endregion
14885
16381
  //#region src/revert.ts
14886
16382
  /**
@@ -20076,6 +21572,76 @@ function reviewHandlers(ctx, registry) {
20076
21572
  error: message
20077
21573
  };
20078
21574
  }
21575
+ },
21576
+ "edrv.review.undoAll": async (args) => {
21577
+ try {
21578
+ const scope = await scopeOf(args.sessionId);
21579
+ if (!scope.live) return {
21580
+ ok: false,
21581
+ error: UNDO_NEEDS_LIVE
21582
+ };
21583
+ const items = Array.isArray(args.items) ? args.items : [];
21584
+ if (!items.length) return {
21585
+ ok: false,
21586
+ error: "没有可撤销的记录"
21587
+ };
21588
+ if (items.length > BATCH_LIMIT) return {
21589
+ ok: false,
21590
+ error: `记录过多(${items.length} 条,上限 ${BATCH_LIMIT}),请先分批处理后重试`
21591
+ };
21592
+ if (items.some((item) => item.id.startsWith("pending:"))) return {
21593
+ ok: false,
21594
+ error: "待审条目请逐条判定;批量 Undo 只处理官方审查记录"
21595
+ };
21596
+ if (args.confirmed !== true) {
21597
+ const externals = items.filter((item) => reviewDetail(scope.cwd, item.id)?.capability.confirmUndo === true);
21598
+ if (externals.length) return {
21599
+ ok: true,
21600
+ result: {
21601
+ completed: 0,
21602
+ total: items.length,
21603
+ paths: [],
21604
+ needsConfirm: externals.length,
21605
+ error: ""
21606
+ }
21607
+ };
21608
+ }
21609
+ const result = {
21610
+ completed: 0,
21611
+ total: items.length,
21612
+ paths: [],
21613
+ error: ""
21614
+ };
21615
+ const session = sessionOf(ctx, args.sessionId);
21616
+ for (const item of items) try {
21617
+ await undoReview(ctx, session, scope.cwd, {
21618
+ sessionId: args.sessionId,
21619
+ id: item.id,
21620
+ seq: item.seq,
21621
+ revision: item.revision,
21622
+ operationId: item.operationId,
21623
+ decision: "rejected",
21624
+ scope: "file"
21625
+ });
21626
+ result.completed++;
21627
+ result.paths.push(item.display);
21628
+ } catch (error) {
21629
+ result.error = error instanceof Error ? error.message : String(error);
21630
+ break;
21631
+ }
21632
+ log.info(`[review] undoAll live=1 total=${result.total} done=${result.completed}`);
21633
+ return {
21634
+ ok: true,
21635
+ result
21636
+ };
21637
+ } catch (error) {
21638
+ const message = error instanceof Error ? error.message : String(error);
21639
+ log.warn(`[review] undoAll 失败: ${message}`);
21640
+ return {
21641
+ ok: false,
21642
+ error: message
21643
+ };
21644
+ }
20079
21645
  }
20080
21646
  };
20081
21647
  }
@@ -20322,6 +21888,33 @@ function refreshHandlers(kit) {
20322
21888
  changed: outcome.changed,
20323
21889
  gaps: outcome.gaps
20324
21890
  };
21891
+ },
21892
+ /**
21893
+ * @author ddj 2026-11-24
21894
+ * @description: 清掉指定通道的幽灵记录。dryRun 只报数;真删后按需 VACUUM,
21895
+ * 并重建「待审接管」集合,避免旧路径继续顶掉官方行。
21896
+ * @param args 清理请求
21897
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
21898
+ */
21899
+ "edrv.pending.purge": async (args) => {
21900
+ const cwd = await kit.write(args.sessionId);
21901
+ const outcome = purgePending(cwd, {
21902
+ sources: args.sources,
21903
+ baseKinds: args.baseKinds,
21904
+ before: args.before
21905
+ }, {
21906
+ dryRun: args.dryRun === true,
21907
+ vacuum: true
21908
+ });
21909
+ const page = loadPage(cwd, args.sessionId);
21910
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path));
21911
+ return {
21912
+ ok: true,
21913
+ matched: outcome.matched,
21914
+ removed: outcome.removed,
21915
+ kept: outcome.kept,
21916
+ vacuumMs: outcome.vacuumMs
21917
+ };
20325
21918
  }
20326
21919
  };
20327
21920
  }
@@ -22970,6 +24563,39 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
22970
24563
  };
22971
24564
  }
22972
24565
  },
24566
+ /**
24567
+ * @author ddj 2026-11-24
24568
+ * @description: 归档库清理:保留期 + 每文件上限 + 撤销栈截断。缺省 dryRun,显式传 false 才删。
24569
+ * @param args 清理参数
24570
+ * @returns 三个统计口径与删除行数
24571
+ */
24572
+ "edrv.archive.purge": async (args) => {
24573
+ const sc = await resolveScope(ctx, args.sessionId);
24574
+ if ("err" in sc) return {
24575
+ ok: false,
24576
+ error: sc.err
24577
+ };
24578
+ try {
24579
+ const outcome = purgeArchiveDb(sc.cwd, {
24580
+ dryRun: args.dryRun !== false,
24581
+ retentionDays: args.retentionDays,
24582
+ keepBatches: args.keepBatches,
24583
+ keepOps: args.keepOps,
24584
+ vacuum: false
24585
+ });
24586
+ const changed = outcome.removed.batches + outcome.removed.history;
24587
+ if (args.dryRun === false && changed && args.vacuum !== false) scheduleArchiveRewrite(sc.cwd);
24588
+ return {
24589
+ ok: true,
24590
+ ...outcome
24591
+ };
24592
+ } catch (error) {
24593
+ return {
24594
+ ok: false,
24595
+ error: "归档清理失败:" + String(error)
24596
+ };
24597
+ }
24598
+ },
22973
24599
  "edrv.archivePage": async (args) => {
22974
24600
  const sc = await resolveScope(ctx, args.sessionId);
22975
24601
  if ("err" in sc) return {
@@ -24378,13 +26004,18 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
24378
26004
  * @author ddj 2026年08月20号 / 2026年08月26号
24379
26005
  */
24380
26006
  async function handleRpc(ctx, registry, method, args, searcher = newSearcher(ctx), contentSearcher = newContentSearcher(ctx), lspHandlers, aiHandlers, fileVersions, svnHandlers, dapHandlers) {
24381
- const handlers = buildHandlers(ctx, registry, searcher, contentSearcher, lspHandlers, aiHandlers, fileVersions, svnHandlers, dapHandlers);
24382
- const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
24383
- if (typeof handler !== "function") return {
24384
- ok: false,
24385
- error: "未知方法: " + String(method)
24386
- };
24387
- return handler(args);
26007
+ const done = beginOperation("rpc:" + String(method));
26008
+ try {
26009
+ const handlers = buildHandlers(ctx, registry, searcher, contentSearcher, lspHandlers, aiHandlers, fileVersions, svnHandlers, dapHandlers);
26010
+ const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
26011
+ if (typeof handler !== "function") return {
26012
+ ok: false,
26013
+ error: "未知方法: " + String(method)
26014
+ };
26015
+ return await handler(args);
26016
+ } finally {
26017
+ done();
26018
+ }
24388
26019
  }
24389
26020
  //#endregion
24390
26021
  //#region src/svnPlanTool.ts
@@ -24451,6 +26082,108 @@ async function installPlanTool(ctx, submit) {
24451
26082
  ctx.effect(install, "vscode-mode:svn-plan-submit");
24452
26083
  }
24453
26084
  //#endregion
26085
+ //#region src/pending/noteTool.ts
26086
+ /** 只读编辑说明的工具入口:模型可以留一句话,但它不参与差异判定。 @author ddj 2026年11月25号 */
26087
+ /**
26088
+ * @author ddj 2026年11月25号
26089
+ * @description: 构造工具定义;只写进程内说明表,不碰磁盘、不碰工具参数。
26090
+ * @param ctx Host 上下文(取 fs 解析路径)
26091
+ * @param cwdOf 会话工作区解析
26092
+ * @returns 定义选项
26093
+ */
26094
+ function noteToolOptions(ctx, cwdOf) {
26095
+ /**
26096
+ * @author ddj 2026年11月25号
26097
+ * @description: 记录一条说明;非法输入返回可读原因,不抛错。
26098
+ * @param args 模型参数
26099
+ * @param exec 执行上下文
26100
+ * @returns 回执
26101
+ */
26102
+ async function execute(args, exec) {
26103
+ const path = typeof args.path === "string" ? args.path.trim() : "";
26104
+ const note = typeof args.note === "string" ? args.note.trim() : "";
26105
+ if (!path || !note) return {
26106
+ ok: false,
26107
+ error: "path 与 note 都必须是非空字符串"
26108
+ };
26109
+ if (note.length > 500) return {
26110
+ ok: false,
26111
+ error: "note 超过 500 个字符"
26112
+ };
26113
+ if (exec.signal?.aborted) return {
26114
+ ok: false,
26115
+ error: "说明已取消"
26116
+ };
26117
+ const cwd = cwdOf(exec.agent?.session);
26118
+ if (!cwd) return {
26119
+ ok: false,
26120
+ error: "编辑说明需要所属会话的工作区"
26121
+ };
26122
+ const target = await ctx.get("fs").resolve(path, { cwd });
26123
+ const identity = ctx.get("fs").processPath(target);
26124
+ if (typeof identity !== "string" || !identity) return {
26125
+ ok: false,
26126
+ error: "路径不可解析:" + path
26127
+ };
26128
+ declareNote(cwd, identity, note);
26129
+ return {
26130
+ ok: true,
26131
+ path,
26132
+ note
26133
+ };
26134
+ }
26135
+ /** @author ddj 2026年11月25号 @param _args 模型参数 @param result 回执 @returns 模型可见文本 */
26136
+ function render(_args, result) {
26137
+ return [{
26138
+ type: "text",
26139
+ text: result.ok ? "已记录只读说明:" + result.path : "说明未记录:" + result.error
26140
+ }];
26141
+ }
26142
+ return {
26143
+ name: "edit_note",
26144
+ description: "Record a read-only note on a file for the review panel: why this file was changed. It is display-only: it never decides whether a diff is real, never writes files, and never changes tool arguments.",
26145
+ parameters: {
26146
+ path: {
26147
+ type: "string",
26148
+ required: true,
26149
+ description: "File path, resolved by the filesystem backend in the session workspace."
26150
+ },
26151
+ note: {
26152
+ type: "string",
26153
+ required: true,
26154
+ description: "One sentence for the reviewer. At most 500 characters."
26155
+ }
26156
+ },
26157
+ output: {
26158
+ schema: { type: "json" },
26159
+ render
26160
+ },
26161
+ isConcurrencySafe: true,
26162
+ execute
26163
+ };
26164
+ }
26165
+ /**
26166
+ * @author ddj 2026年11月25号
26167
+ * @description: 注册工具;宿主缺少工具服务时静默跳过,不影响其余功能。
26168
+ * @param ctx Host 插件上下文
26169
+ * @param cwdOf 会话工作区解析
26170
+ * @returns 无
26171
+ */
26172
+ async function installNoteTool(ctx, cwdOf) {
26173
+ let module;
26174
+ try {
26175
+ module = await loadHostModule("@deepseek-ai/dsh-tools");
26176
+ } catch {
26177
+ return;
26178
+ }
26179
+ const definition = module.defineTool(noteToolOptions(ctx, cwdOf));
26180
+ /** @author ddj 2026年11月25号 @returns 注册释放器 */
26181
+ function install() {
26182
+ return ctx.get("tools").register(definition);
26183
+ }
26184
+ ctx.effect(install, "vscode-mode:edit-note");
26185
+ }
26186
+ //#endregion
24454
26187
  //#region src/lsp/jsonrpc.ts
24455
26188
  /**
24456
26189
  * dsh-vscode-mode host — LSP JSON-RPC 帧编解码(纯函数,node 可测)。
@@ -31205,7 +32938,7 @@ function messageErrorOf(message) {
31205
32938
  * @returns 文件绝对路径
31206
32939
  */
31207
32940
  function recentFileOf(root) {
31208
- return join(userCacheDir(), "svn-commit-msg", hashOf(root) + ".json");
32941
+ return join(userCacheDir(), "svn-commit-msg", hashOf$1(root) + ".json");
31209
32942
  }
31210
32943
  /**
31211
32944
  * 读取最近提交信息(缺失/损坏一律空表,不抛错)。
@@ -37267,6 +39000,8 @@ function attachRuntime(ctx, runtime) {
37267
39000
  settings: () => runtime.settings.external(),
37268
39001
  record: recordPendingWrite
37269
39002
  });
39003
+ const sweep = startArchiveSweep();
39004
+ const loopWatch = startLoopWatchdog();
37270
39005
  /**
37271
39006
  * @author ddj 2026年11月24号
37272
39007
  * @description: 任一工具调用期间都是 agent 写入窗口:bash / python 写盘落在窗口内时归属 agent。
@@ -37312,6 +39047,9 @@ function attachRuntime(ctx, runtime) {
37312
39047
  evidence.dispose();
37313
39048
  pending.dispose();
37314
39049
  external.dispose();
39050
+ clearNotes();
39051
+ sweep.dispose();
39052
+ loopWatch.dispose();
37315
39053
  windows.dispose();
37316
39054
  runtime.fileVersions.dispose();
37317
39055
  closeArchiveDbs();
@@ -37404,6 +39142,7 @@ async function apply(ctx, config) {
37404
39142
  }
37405
39143
  await installPlanTool(ctx, submitPlan);
37406
39144
  await installSvnTools(ctx, runtime.svnRpc.api);
39145
+ await installNoteTool(ctx, (session) => cwdOfSession(ctx, session));
37407
39146
  ctx.effect(mountInbox, "vscode-mode:open-inbox");
37408
39147
  ctx.effect(() => shellMenuLifecycle(ctx), "vscode-mode:integration");
37409
39148
  /** @author ddj 2026年10月12号 @returns Active-profile bridge disposer; failures never block boot. */