dsh-vscode-mode 0.35.0 → 0.37.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 (39) hide show
  1. package/README.md +28 -5
  2. package/lib/client.js +63 -63
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +1885 -54
  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 +319 -0
  9. package/src/capture.ts +3 -0
  10. package/src/client/addToConversation.ts +77 -18
  11. package/src/client/htmlPlan/HtmlPlanPanel.ts +9 -13
  12. package/src/client/htmlPlan/planActions.ts +97 -23
  13. package/src/client/htmlPlan/planPage.ts +2 -2
  14. package/src/client/reviewBatch.ts +8 -0
  15. package/src/client/state/diffSummary.ts +6 -1
  16. package/src/client/state/reviewFeed.ts +35 -4
  17. package/src/client/ui/EditorView.ts +7 -0
  18. package/src/client/ui/McpSettings.ts +21 -0
  19. package/src/client/ui/OfficialReview.ts +20 -2
  20. package/src/fileOpenSettings.ts +29 -0
  21. package/src/index.ts +78 -6
  22. package/src/mcpManaged.ts +12 -3
  23. package/src/mcpManagerBridge.ts +5 -1
  24. package/src/mcpRuntime.ts +33 -4
  25. package/src/pending/capture.ts +32 -4
  26. package/src/pending/decide.ts +12 -3
  27. package/src/pending/externalAlign.ts +297 -0
  28. package/src/pending/externalCapture.ts +677 -0
  29. package/src/pending/kernel.ts +19 -1
  30. package/src/pending/persist.ts +201 -12
  31. package/src/pending/provenance.ts +239 -0
  32. package/src/pending/store.ts +67 -6
  33. package/src/pending/vcs.ts +140 -0
  34. package/src/pendingCompat.ts +13 -6
  35. package/src/pendingRpc.ts +37 -2
  36. package/src/rpc.ts +30 -2
  37. package/src/shared/pendingReview.ts +19 -1
  38. package/src/shared/review.ts +3 -1
  39. package/src/shared/rpc.ts +8 -0
package/lib/index.js CHANGED
@@ -11,6 +11,18 @@ import { execFile, spawn, spawnSync } from "node:child_process";
11
11
  import z from "@deepseek-ai/schemastery";
12
12
  import { inflateRawSync } from "node:zlib";
13
13
  import { StringDecoder } from "node:string_decoder";
14
+ //#region \0rolldown/runtime.js
15
+ var __defProp = Object.defineProperty;
16
+ var __exportAll = (all, no_symbols) => {
17
+ let target = {};
18
+ for (var name in all) __defProp(target, name, {
19
+ get: all[name],
20
+ enumerable: true
21
+ });
22
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
23
+ return target;
24
+ };
25
+ //#endregion
14
26
  //#region src/mcpManagerBridge.ts
15
27
  /**
16
28
  * dsh-vscode-mode host — 官方 MCP 框架(ctx.mcpManager, DSH 0.2.3+)适配桥。
@@ -117,6 +129,7 @@ function toView(raw) {
117
129
  };
118
130
  if (message) result.error = message;
119
131
  if (phase) result.phase = phase;
132
+ if (typeof status.connectedAt === "number") result.connectedAt = status.connectedAt;
120
133
  return result;
121
134
  }
122
135
  /**
@@ -723,7 +736,8 @@ var ManagedProject = class {
723
736
  path,
724
737
  server,
725
738
  key: keyOf(def),
726
- refs
739
+ refs,
740
+ mountedAt: Date.now()
727
741
  };
728
742
  this.held.set(name, record);
729
743
  const reason = this.conflictOf(name);
@@ -796,7 +810,7 @@ var ManagedProject = class {
796
810
  if (record) await this.port.restart(record.name);
797
811
  }
798
812
  /**
799
- * 读一条托管的当前状态。
813
+ * 读一条托管的当前状态;挂载时刻与官方连上时刻一并带出。
800
814
  * @public @author ddj 2026年11月23号
801
815
  * @param path 工作区路径
802
816
  * @param server 服务器名
@@ -804,11 +818,17 @@ var ManagedProject = class {
804
818
  */
805
819
  stateOf(path, server) {
806
820
  const name = managedName(path, server);
821
+ const held = this.held.get(name);
807
822
  const view = this.views.get(name);
808
- if (!view) return { state: this.held.has(name) ? "unknown" : "idle" };
823
+ if (!view) return held ? {
824
+ state: "unknown",
825
+ since: held.mountedAt
826
+ } : { state: "idle" };
809
827
  const state = { state: view.state };
828
+ if (held) state.since = held.mountedAt;
810
829
  if (view.error) state.error = view.error;
811
830
  if (view.phase) state.phase = view.phase;
831
+ if (view.connectedAt !== void 0) state.connectedAt = view.connectedAt;
812
832
  return state;
813
833
  }
814
834
  /**
@@ -3021,6 +3041,181 @@ function pathKeyFor(path, foldCase) {
3021
3041
  return foldCase ? unified.toLowerCase() : unified;
3022
3042
  }
3023
3043
  //#endregion
3044
+ //#region src/pending/provenance.ts
3045
+ /** 工具调用结束后的归属尾巴:写完盘到 flush 之间还有事件延迟。 */
3046
+ const AGENT_TAIL_MS = 2e3;
3047
+ /** 路径标记表上限:超出按写入序逐出最旧。 */
3048
+ const MARK_MAX = 2e3;
3049
+ /** 写工具 → 采集通道。未列出的写工具按 `tool` 处理。 */
3050
+ const SOURCE_OF_TOOL = {
3051
+ edit: "edit",
3052
+ str_replace_editor: "edit",
3053
+ apply_patch: "edit",
3054
+ "ops_edit_file": "edit",
3055
+ write: "write",
3056
+ "ops_write_file": "write",
3057
+ "ops_remove": "write",
3058
+ "ops_copy": "write",
3059
+ "ops_move": "write",
3060
+ "ops_replace": "edit",
3061
+ remote_ssh_write: "remote_ssh_write",
3062
+ watch: "watch",
3063
+ scan: "scan",
3064
+ vcs: "vcs"
3065
+ };
3066
+ /** 通道强度:合并同一路径的两次采集时,强通道保留其来源标签。 */
3067
+ const SOURCE_RANK = {
3068
+ edit: 6,
3069
+ write: 6,
3070
+ remote_ssh_write: 5,
3071
+ tool: 4,
3072
+ watch: 3,
3073
+ scan: 2,
3074
+ vcs: 1
3075
+ };
3076
+ /**
3077
+ * @author ddj 2026-11-24
3078
+ * @description: Host 侧的路径比较键:盘符恒折叠大小写,其余按运行平台折叠。
3079
+ * @param path 路径
3080
+ * @returns 比较键
3081
+ */
3082
+ function pathKeyOf(path) {
3083
+ return pathKeyFor(path, process.platform === "win32");
3084
+ }
3085
+ /**
3086
+ * @author ddj 2026-11-24
3087
+ * @description: 写工具名 → 采集通道;未知工具统一按 `tool`。
3088
+ * @param tool 工具名
3089
+ * @returns 采集通道
3090
+ */
3091
+ function sourceOfTool(tool) {
3092
+ return SOURCE_OF_TOOL[typeof tool === "string" ? tool : ""] ?? "tool";
3093
+ }
3094
+ /**
3095
+ * @author ddj 2026-11-24
3096
+ * @description: 合并同一路径的两次采集来源:强通道优先,同级保留首次值。
3097
+ * @param earlier 已落库通道(可为空)
3098
+ * @param later 本次通道
3099
+ * @returns 应当落库的通道
3100
+ */
3101
+ function strongerSource(earlier, later) {
3102
+ const left = earlier ?? "tool";
3103
+ const right = later ?? "tool";
3104
+ return SOURCE_RANK[left] >= SOURCE_RANK[right] ? left : right;
3105
+ }
3106
+ /**
3107
+ * @author ddj 2026-11-24
3108
+ * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销。
3109
+ * @param origin 归属
3110
+ * @param baseKind 基线与可信度
3111
+ * @returns 可直接撤销 / 需确认 / 禁止
3112
+ */
3113
+ function revertPolicyOf(origin, baseKind) {
3114
+ if ((baseKind ?? "known") === "unknown") return "blocked";
3115
+ return (origin ?? "agent") === "agent" ? "direct" : "confirm";
3116
+ }
3117
+ /**
3118
+ * @author ddj 2026-11-24
3119
+ * @description: 条目来源徽标文案;官方行没有徽标。
3120
+ * @param entry 待审条目的来源字段
3121
+ * @returns 展示文案
3122
+ */
3123
+ function sourceLabelOf(entry) {
3124
+ const source = entry.source ?? "tool";
3125
+ 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 + " · 外部";
3130
+ }
3131
+ /**
3132
+ * 创建窗口注册表(不依赖 Host,可单测)。
3133
+ * @author ddj 2026-11-24
3134
+ * @returns 注册表能力
3135
+ */
3136
+ function createWindows() {
3137
+ const state = {
3138
+ depth: 0,
3139
+ until: 0,
3140
+ marks: /* @__PURE__ */ new Map()
3141
+ };
3142
+ /**
3143
+ * @description: 逐出超期标记,再压到上限内。
3144
+ * @param now 当前时间
3145
+ */
3146
+ function sweep(now) {
3147
+ for (const [key, mark] of state.marks) {
3148
+ const self = mark.selfAt !== void 0 && now - mark.selfAt <= 5e3;
3149
+ const editor = mark.editorAt !== void 0 && now - mark.editorAt <= 2e3;
3150
+ if (!self && !editor) state.marks.delete(key);
3151
+ }
3152
+ while (state.marks.size > MARK_MAX) {
3153
+ const oldest = state.marks.keys().next().value;
3154
+ if (oldest === void 0) break;
3155
+ state.marks.delete(oldest);
3156
+ }
3157
+ }
3158
+ /**
3159
+ * @description: 取(或建)一条路径的标记。
3160
+ * @param key 路径比较键
3161
+ * @param now 当前时间
3162
+ * @returns 可变标记对象
3163
+ */
3164
+ function markOf(key, now) {
3165
+ sweep(now);
3166
+ const existing = state.marks.get(key);
3167
+ if (existing) return existing;
3168
+ const created = {};
3169
+ state.marks.set(key, created);
3170
+ return created;
3171
+ }
3172
+ return {
3173
+ /** @returns 工具调用开始,进入 agent 窗口。 */
3174
+ enterTool(now = Date.now()) {
3175
+ state.depth += 1;
3176
+ state.until = now + AGENT_TAIL_MS;
3177
+ },
3178
+ /** @param now 当前时间 @returns 工具调用结束,留下尾巴。 */
3179
+ exitTool(now = Date.now()) {
3180
+ state.depth = Math.max(0, state.depth - 1);
3181
+ state.until = Math.max(state.until, now + AGENT_TAIL_MS);
3182
+ },
3183
+ /** @param now 当前时间 @returns 当前是否算 agent 写入窗口。 */
3184
+ inAgentWindow(now = Date.now()) {
3185
+ return state.depth > 0 || now <= state.until;
3186
+ },
3187
+ /** @param key 路径比较键 @param now 当前时间 @returns 打自写标记。 */
3188
+ markSelf(key, now = Date.now()) {
3189
+ markOf(key, now).selfAt = now;
3190
+ },
3191
+ /** @param key 路径比较键 @param now 当前时间 @returns 打编辑器保存标记。 */
3192
+ markEditor(key, now = Date.now()) {
3193
+ markOf(key, now).editorAt = now;
3194
+ },
3195
+ /**
3196
+ * @description: 取占用窗口的类别;自写优先于编辑器,两者都没有返回 null。
3197
+ * @param key 路径比较键
3198
+ * @param now 当前时间
3199
+ * @returns 窗口类别
3200
+ */
3201
+ windowOf(key, now = Date.now()) {
3202
+ const mark = state.marks.get(key);
3203
+ if (!mark) return null;
3204
+ if (mark.selfAt !== void 0 && now - mark.selfAt <= 5e3) return "self";
3205
+ if (mark.editorAt !== void 0 && now - mark.editorAt <= 2e3) return "editor";
3206
+ return null;
3207
+ },
3208
+ /** @returns 无。清空全部窗口(插件卸载)。 */
3209
+ dispose() {
3210
+ state.depth = 0;
3211
+ state.until = 0;
3212
+ state.marks.clear();
3213
+ }
3214
+ };
3215
+ }
3216
+ /** 进程级窗口注册表:capture.ts / rpc.ts / externalCapture.ts 共用同一份。 */
3217
+ const windows = createWindows();
3218
+ //#endregion
3024
3219
  //#region src/shared/pendingReview.ts
3025
3220
  /** 待审条目在面板列表里的 id 前缀;客户端与 Host 共用这一份口径。 */
3026
3221
  const PENDING_PREFIX = "pending:";
@@ -3099,7 +3294,7 @@ function pendingDisplay(cwd, path) {
3099
3294
  * @returns 面板列表项
3100
3295
  */
3101
3296
  function pendingItemOf(item, cwd) {
3102
- return {
3297
+ const row = {
3103
3298
  id: PENDING_PREFIX + item.id,
3104
3299
  sessionId: item.sessionId,
3105
3300
  turn: 0,
@@ -3114,6 +3309,8 @@ function pendingItemOf(item, cwd) {
3114
3309
  revision: item.revision,
3115
3310
  current: true
3116
3311
  };
3312
+ if (item.settled !== true) row.sourceLabel = sourceLabelOf(item);
3313
+ return row;
3117
3314
  }
3118
3315
  /**
3119
3316
  * @author ddj 2026年10月29号
@@ -3123,16 +3320,18 @@ function pendingItemOf(item, cwd) {
3123
3320
  * @returns 面板详情
3124
3321
  */
3125
3322
  function pendingDetailOf(detail, capturedAt, cwd) {
3323
+ const capability = {
3324
+ keep: detail.capability.keep,
3325
+ undo: detail.capability.revert,
3326
+ reason: detail.capability.reason
3327
+ };
3328
+ if (detail.capability.confirmRevert === true) capability.confirmUndo = true;
3126
3329
  return {
3127
3330
  item: pendingItemOf(detail.item, cwd),
3128
3331
  diff: detail.diff,
3129
3332
  capturedAt,
3130
3333
  blocks: detail.blocks,
3131
- capability: {
3132
- keep: detail.capability.keep,
3133
- undo: detail.capability.revert,
3134
- reason: detail.capability.reason
3135
- }
3334
+ capability
3136
3335
  };
3137
3336
  }
3138
3337
  /**
@@ -3226,8 +3425,29 @@ function mergedPage(official, pending, cwd) {
3226
3425
  }
3227
3426
  //#endregion
3228
3427
  //#region src/pending/persist.ts
3229
- /** 待审库版本号,写进 metadata 便于日后迁移。v3 给评论表加了引文与上下文列。 */
3230
- const SCHEMA_VERSION = "3";
3428
+ /** 待审库版本号,写进 metadata 便于日后迁移。v4 给条目加了采集来源与基线可信度。 */
3429
+ const SCHEMA_VERSION = "4";
3430
+ /** 工作区待审版本号:条目一落库就自增,供客户端轮询判断是否需要重读列表。 */
3431
+ const versions = /* @__PURE__ */ new Map();
3432
+ /**
3433
+ * @author ddj 2026-11-24
3434
+ * @description: 读工作区待审版本号;只在条目真正落库后自增,保证「先记录后通知 UI」。
3435
+ * @param cwd 工作区
3436
+ * @returns 单调递增的版本号
3437
+ */
3438
+ function pendingVersion(cwd) {
3439
+ return versions.get(cwd) ?? 0;
3440
+ }
3441
+ /**
3442
+ * @private
3443
+ * @author ddj 2026-11-24
3444
+ * @description: 条目状态变化后自增版本号(进程内计数,不落盘)。
3445
+ * @param cwd 工作区
3446
+ * @returns 无
3447
+ */
3448
+ function bumpVersion(cwd) {
3449
+ versions.set(cwd, (versions.get(cwd) ?? 0) + 1);
3450
+ }
3231
3451
  /**
3232
3452
  * @author ddj 2026年10月29号
3233
3453
  * @description: 打开工作区库并确保待审表存在;DDL 与版本标记在同一事务里提交。
@@ -3243,6 +3463,7 @@ function pendingDb(cwd) {
3243
3463
  try {
3244
3464
  db.exec(DDL);
3245
3465
  migrateHistory(db);
3466
+ migrateProvenance(db);
3246
3467
  db.prepare("INSERT INTO metadata(name,value) VALUES('pending_schema',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value").run(SCHEMA_VERSION);
3247
3468
  db.exec("COMMIT");
3248
3469
  } catch (error) {
@@ -3259,7 +3480,9 @@ CREATE TABLE IF NOT EXISTS pending_entries (
3259
3480
  unseen INTEGER NOT NULL DEFAULT 0, missing INTEGER NOT NULL DEFAULT 0,
3260
3481
  diverged INTEGER NOT NULL DEFAULT 0, oversized INTEGER NOT NULL DEFAULT 0,
3261
3482
  revision INTEGER NOT NULL DEFAULT 0, session_id TEXT NOT NULL,
3262
- session_ids TEXT NOT NULL, lineage TEXT);
3483
+ session_ids TEXT NOT NULL, lineage TEXT,
3484
+ source TEXT NOT NULL DEFAULT 'tool', origin TEXT NOT NULL DEFAULT 'agent',
3485
+ base_kind TEXT NOT NULL DEFAULT 'known');
3263
3486
  CREATE TABLE IF NOT EXISTS pending_blocks (
3264
3487
  entry_id TEXT NOT NULL, block_id TEXT NOT NULL, decision TEXT NOT NULL,
3265
3488
  PRIMARY KEY(entry_id,block_id));
@@ -3272,6 +3495,20 @@ CREATE TABLE IF NOT EXISTS pending_history (
3272
3495
  state TEXT NOT NULL DEFAULT 'applied');
3273
3496
  `;
3274
3497
  /**
3498
+ * @author ddj 2026-11-24
3499
+ * @description: v3 → v4:给条目补三列来源字段。旧行按默认值读成「工具链路 / agent / 已知内容」,
3500
+ * 与 v3 的语义一致,不需要回填。
3501
+ * @param db 已打开的工作区库
3502
+ * @returns 无
3503
+ */
3504
+ function migrateProvenance(db) {
3505
+ const columns = db.prepare("PRAGMA table_info(pending_entries)").all();
3506
+ const names = new Set(columns.map((column) => String(column.name)));
3507
+ if (!names.has("source")) db.exec("ALTER TABLE pending_entries ADD COLUMN source TEXT NOT NULL DEFAULT 'tool'");
3508
+ if (!names.has("origin")) db.exec("ALTER TABLE pending_entries ADD COLUMN origin TEXT NOT NULL DEFAULT 'agent'");
3509
+ if (!names.has("base_kind")) db.exec("ALTER TABLE pending_entries ADD COLUMN base_kind TEXT NOT NULL DEFAULT 'known'");
3510
+ }
3511
+ /**
3275
3512
  * @author ddj 2026年10月29号
3276
3513
  * @description: v1 历史表补 state 列(rebuild 成本高于一次 ALTER)。
3277
3514
  * @param db 已打开的工作区库
@@ -3301,7 +3538,7 @@ function loadEntries(cwd) {
3301
3538
  * @returns 无
3302
3539
  */
3303
3540
  function saveEntry(cwd, stored) {
3304
- upsertEntry(pendingDb(cwd), stored);
3541
+ upsertEntry(pendingDb(cwd), cwd, stored);
3305
3542
  }
3306
3543
  /**
3307
3544
  * @private
@@ -3311,15 +3548,18 @@ function saveEntry(cwd, stored) {
3311
3548
  * @param stored 条目与标记
3312
3549
  * @returns 无
3313
3550
  */
3314
- function upsertEntry(db, stored) {
3551
+ function upsertEntry(db, cwd, stored) {
3315
3552
  const { entry, flags } = stored;
3316
3553
  db.prepare(`INSERT INTO pending_entries
3317
- (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage)
3318
- VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
3554
+ (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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
3319
3557
  ON CONFLICT(id) DO UPDATE SET path=excluded.path,earlier=excluded.earlier,old_text=excluded.old_text,
3320
3558
  new_text=excluded.new_text,updated_at=excluded.updated_at,unseen=excluded.unseen,missing=excluded.missing,
3321
3559
  diverged=excluded.diverged,oversized=excluded.oversized,revision=excluded.revision,
3322
- session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage`).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);
3560
+ 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");
3562
+ bumpVersion(cwd);
3323
3563
  }
3324
3564
  /**
3325
3565
  * @author ddj 2026年10月29号
@@ -3335,6 +3575,7 @@ function dropEntry(cwd, id) {
3335
3575
  db.prepare("DELETE FROM pending_entries WHERE id=?").run(id);
3336
3576
  db.prepare("DELETE FROM pending_blocks WHERE entry_id=?").run(id);
3337
3577
  db.exec("COMMIT");
3578
+ bumpVersion(cwd);
3338
3579
  } catch (error) {
3339
3580
  if (db.isTransaction) db.exec("ROLLBACK");
3340
3581
  throw error;
@@ -3354,6 +3595,7 @@ function saveBlocks(cwd, entryId, blocks) {
3354
3595
  try {
3355
3596
  writeBlocks(db, entryId, blocks);
3356
3597
  db.exec("COMMIT");
3598
+ bumpVersion(cwd);
3357
3599
  } catch (error) {
3358
3600
  if (db.isTransaction) db.exec("ROLLBACK");
3359
3601
  throw error;
@@ -3492,13 +3734,49 @@ function entryOfRow(row) {
3492
3734
  newText: String(row.new_text),
3493
3735
  updatedAt: Number(row.updated_at),
3494
3736
  sessionId: String(row.session_id),
3495
- sessionIds: JSON.parse(String(row.session_ids))
3737
+ sessionIds: JSON.parse(String(row.session_ids)),
3738
+ source: sourceOfRow(row),
3739
+ origin: originOfRow(row),
3740
+ baseKind: baseKindOfRow(row)
3496
3741
  };
3497
3742
  if (Number(row.unseen) === 1) entry.unseen = true;
3498
3743
  if (lineage !== void 0) entry.lineage = lineage;
3499
3744
  return entry;
3500
3745
  }
3501
3746
  /**
3747
+ * @private
3748
+ * @author ddj 2026-11-24
3749
+ * @description: 读采集通道列;v3 旧库升级后该列有默认值,异常值按 `tool` 处理。
3750
+ * @param row 数据库行
3751
+ * @returns 采集通道
3752
+ */
3753
+ function sourceOfRow(row) {
3754
+ const value = String(row.source ?? "tool");
3755
+ return value === "edit" || value === "write" || value === "remote_ssh_write" || value === "watch" || value === "scan" || value === "vcs" ? value : "tool";
3756
+ }
3757
+ /**
3758
+ * @private
3759
+ * @author ddj 2026-11-24
3760
+ * @description: 读归属列;异常值按 `agent` 处理(与 v3 语义一致)。
3761
+ * @param row 数据库行
3762
+ * @returns 归属
3763
+ */
3764
+ function originOfRow(row) {
3765
+ const value = String(row.origin ?? "agent");
3766
+ return value === "editor" || value === "vcs" || value === "external" ? value : "agent";
3767
+ }
3768
+ /**
3769
+ * @private
3770
+ * @author ddj 2026-11-24
3771
+ * @description: 读基线可信度列;异常值按 `known` 处理。
3772
+ * @param row 数据库行
3773
+ * @returns 基线可信度
3774
+ */
3775
+ function baseKindOfRow(row) {
3776
+ const value = String(row.base_kind ?? "known");
3777
+ return value === "absent" || value === "vcs" || value === "unknown" ? value : "known";
3778
+ }
3779
+ /**
3502
3780
  * @author ddj 2026年10月29号
3503
3781
  * @description: 由数据库行还原标记。
3504
3782
  * @param row 数据库行
@@ -3526,13 +3804,14 @@ function saveDecisions(cwd, records) {
3526
3804
  const db = pendingDb(cwd);
3527
3805
  const skipped = [];
3528
3806
  const advance = db.prepare(`UPDATE pending_entries SET path=?,earlier=?,old_text=?,new_text=?,updated_at=?,unseen=?,
3529
- missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=? WHERE id=? AND revision=?`);
3807
+ missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?
3808
+ WHERE id=? AND revision=?`);
3530
3809
  db.exec("BEGIN IMMEDIATE");
3531
3810
  try {
3532
3811
  for (const record of records) {
3533
3812
  const { entry, flags } = record.next;
3534
3813
  const expected = record.stored.flags.revision;
3535
- 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, record.entryId, expected).changes !== 1) {
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) {
3536
3815
  skipped.push({
3537
3816
  id: record.entryId,
3538
3817
  reason: "待审条目已变化,请重试"
@@ -3543,12 +3822,82 @@ function saveDecisions(cwd, records) {
3543
3822
  insertHistory(db, "decide", record.entryId, record.snapshot, Date.now());
3544
3823
  }
3545
3824
  db.exec("COMMIT");
3825
+ if (records.length) bumpVersion(cwd);
3546
3826
  return skipped;
3547
3827
  } catch (error) {
3548
3828
  if (db.isTransaction) db.exec("ROLLBACK");
3549
3829
  throw error;
3550
3830
  }
3551
3831
  }
3832
+ /**
3833
+ * @public
3834
+ * @author ddj 2026-11-24
3835
+ * @description: 按条件清理待审条目(清幽灵记录用)。命中判定与删除在同一份读结果上做:
3836
+ * 有 pending_history 的条目(已经 Keep/Revert 过)一律保留,绝不按内容猜。
3837
+ * @param cwd 工作区
3838
+ * @param filter 筛选条件
3839
+ * @param dryRun 只数不删
3840
+ * @returns 命中、删除与保留条数
3841
+ * @throws 事务级异常整体回滚后抛出
3842
+ */
3843
+ function purgeEntries(cwd, filter = {}, dryRun = false) {
3844
+ const db = pendingDb(cwd);
3845
+ const sources = filter.sources && filter.sources.length ? new Set(filter.sources) : null;
3846
+ const baseKinds = filter.baseKinds && filter.baseKinds.length ? new Set(filter.baseKinds) : null;
3847
+ const before = typeof filter.before === "number" ? filter.before : null;
3848
+ const rows = db.prepare(`SELECT id, source, base_kind, updated_at,
3849
+ EXISTS(SELECT 1 FROM pending_history h WHERE h.entry_id = pending_entries.id) AS decided
3850
+ FROM pending_entries`).all();
3851
+ const hits = [];
3852
+ let kept = 0;
3853
+ for (const row of rows) {
3854
+ if (sources && !sources.has(String(row.source))) continue;
3855
+ if (baseKinds && !baseKinds.has(String(row.base_kind))) continue;
3856
+ if (before !== null && Number(row.updated_at) >= before) continue;
3857
+ if (Number(row.decided) === 1) kept += 1;
3858
+ else hits.push(String(row.id));
3859
+ }
3860
+ if (dryRun || !hits.length) return {
3861
+ matched: hits.length,
3862
+ removed: 0,
3863
+ kept
3864
+ };
3865
+ db.exec("BEGIN IMMEDIATE");
3866
+ try {
3867
+ const dropEntryRow = db.prepare("DELETE FROM pending_entries WHERE id=?");
3868
+ const dropBlockRows = db.prepare("DELETE FROM pending_blocks WHERE entry_id=?");
3869
+ for (const id of hits) {
3870
+ dropEntryRow.run(id);
3871
+ dropBlockRows.run(id);
3872
+ }
3873
+ db.exec("COMMIT");
3874
+ } catch (error) {
3875
+ if (db.isTransaction) db.exec("ROLLBACK");
3876
+ throw error;
3877
+ }
3878
+ bumpVersion(cwd);
3879
+ return {
3880
+ matched: hits.length,
3881
+ removed: hits.length,
3882
+ kept
3883
+ };
3884
+ }
3885
+ /**
3886
+ * @public
3887
+ * @author ddj 2026-11-24
3888
+ * @description: 回收已删行占用的页;失败只记日志,不影响已完成的删除。
3889
+ * @param cwd 工作区
3890
+ * @returns 耗时毫秒
3891
+ */
3892
+ function vacuumEntries(cwd) {
3893
+ const started = Date.now();
3894
+ try {
3895
+ pendingDb(cwd).exec("VACUUM");
3896
+ } catch (error) {
3897
+ log.warn("待审库 VACUUM 失败:" + String(error));
3898
+ }
3899
+ return Date.now() - started;
3900
+ }
3552
3901
  //#endregion
3553
3902
  //#region src/store.ts
3554
3903
  const READ_CAP$1 = 8388608;
@@ -4202,6 +4551,7 @@ var McpRuntime = class {
4202
4551
  if (!def.enabled || record.holds.has(name) || !path) continue;
4203
4552
  record.holds.set(name, managed.hold(path, name));
4204
4553
  }
4554
+ record.finishedAt ??= Date.now();
4205
4555
  this.changed();
4206
4556
  }
4207
4557
  /** @private @author ddj 2026年10月20号 @param agent Owner. @param record Scope record. Updates lazy resources and schedules explicit background services. */
@@ -4435,14 +4785,11 @@ var McpRuntime = class {
4435
4785
  }
4436
4786
  /** @private @author ddj 2026年10月20号 @param agent Owner. @param record Ledger. @returns Server phases with caller-local timing, not pooled connection age. */
4437
4787
  sessionServers(agent, record) {
4788
+ const managed = this.probeBackend() === "manager" ? this.managedOf() : void 0;
4789
+ const path = managed ? this.workspace(agent) ?? "" : "";
4438
4790
  return this.catalogue(agent).map(({ serverName, phase }) => {
4439
4791
  const instance = record.instances.get(serverName);
4440
- if (!instance) return {
4441
- serverName,
4442
- phase: "idle",
4443
- startedAt: record.finishedAt ?? record.startedAt,
4444
- phaseAt: record.finishedAt ?? record.startedAt
4445
- };
4792
+ if (!instance) return this.managedServer(record, serverName, phase, managed?.stateOf(path, serverName));
4446
4793
  const entry = instance.lease.entry;
4447
4794
  return {
4448
4795
  serverName,
@@ -4458,6 +4805,30 @@ var McpRuntime = class {
4458
4805
  };
4459
4806
  });
4460
4807
  }
4808
+ /**
4809
+ * 托管后端的一条服务器状态:阶段取 catalogue 的官方映射,时间取挂载时刻与官方连上时刻。
4810
+ * @private @author ddj 2026年11月24号
4811
+ * @param record 会话账目
4812
+ * @param serverName 服务器名
4813
+ * @param phase 官方状态映射后的阶段
4814
+ * @param state 官方托管状态;连接池后端不传
4815
+ * @returns 会话里的一条服务器状态
4816
+ */
4817
+ managedServer(record, serverName, phase, state) {
4818
+ const startedAt = state?.since ?? record.finishedAt ?? record.startedAt;
4819
+ let finishedAt;
4820
+ if (phase === "ready") finishedAt = state?.connectedAt ?? startedAt;
4821
+ else if (phase === "error") finishedAt = startedAt;
4822
+ const server = {
4823
+ serverName,
4824
+ phase,
4825
+ startedAt,
4826
+ phaseAt: finishedAt ?? startedAt,
4827
+ finishedAt
4828
+ };
4829
+ if (state?.error) server.error = state.error;
4830
+ return server;
4831
+ }
4461
4832
  /** @public @author ddj 2026年09月28号 @param path Workspace. @returns Masked configuration and pool/lease counts; initialization is not health. */
4462
4833
  views(path) {
4463
4834
  if (this.probeBackend() === "manager") return this.viewsManaged(path);
@@ -4558,6 +4929,13 @@ async function clearLegacy(ctx) {
4558
4929
  function leftoverOf(ctx) {
4559
4930
  return entriesOf(ctx).filter((entry) => isProjectEntryId(String(entry.id ?? entry.options?.id ?? ""))).map((entry) => String(entry.id));
4560
4931
  }
4932
+ /** 官方状态里算「还在起来」的那几个:连接中、重连退避、等凭据、等授权。 */
4933
+ const STARTING_STATES = /* @__PURE__ */ new Set([
4934
+ "connecting",
4935
+ "reconnecting",
4936
+ "waiting-credentials",
4937
+ "waiting-authorization"
4938
+ ]);
4561
4939
  /**
4562
4940
  * 官方状态 → 插件阶段:未知一律 idle,不假装连上。
4563
4941
  * @private @author ddj 2026年11月23号
@@ -4566,7 +4944,7 @@ function leftoverOf(ctx) {
4566
4944
  */
4567
4945
  function managedPhase(state) {
4568
4946
  if (state === "connected") return "ready";
4569
- if (state === "connecting") return "starting";
4947
+ if (STARTING_STATES.has(state)) return "starting";
4570
4948
  if (state === "failed") return "error";
4571
4949
  return "idle";
4572
4950
  }
@@ -4580,7 +4958,7 @@ function managedPhase(state) {
4580
4958
  function managedStatusOf(enabled, state) {
4581
4959
  if (!enabled) return "disabled";
4582
4960
  if (state === "connected") return "connected";
4583
- if (state === "connecting") return "connecting";
4961
+ if (STARTING_STATES.has(state)) return "connecting";
4584
4962
  if (state === "failed") return "error";
4585
4963
  return "configured";
4586
4964
  }
@@ -6340,7 +6718,9 @@ function buildSettingsSchema(z, options) {
6340
6718
  aiCommitStyle: withVol(z.string().default("plain")),
6341
6719
  nativeOpenExts: withVol(z.string().default(DEFAULT_NATIVE_CSV)),
6342
6720
  refIntake: withVol(z.boolean().default(true)),
6343
- searchReplace: withVol(z.boolean().default(true))
6721
+ searchReplace: withVol(z.boolean().default(true)),
6722
+ externalWatch: withVol(z.boolean().default(true)),
6723
+ externalScan: withVol(z.boolean().default(true))
6344
6724
  };
6345
6725
  if (wantVolatile) configVolatile = {
6346
6726
  requested: true,
@@ -6520,6 +6900,11 @@ function setupOpenSettings(ctx, config, onChange) {
6520
6900
  };
6521
6901
  /** AI 界面设置当前值(提交信息风格 / 整理是否默认按勾选范围)。 */
6522
6902
  let aiUiCurrent = { commitStyle: commitStyleValueOf(config) };
6903
+ /** 外部改动捕获开关当前值(settings 未就绪回退配置值)。 */
6904
+ let externalCurrent = {
6905
+ watch: boolValueOf(config, "externalWatch", true),
6906
+ scan: boolValueOf(config, "externalScan", true)
6907
+ };
6523
6908
  const svnSync = (stored) => {
6524
6909
  svnCurrent = {
6525
6910
  svnPath: svnPathValueOf(stored),
@@ -6530,6 +6915,10 @@ function setupOpenSettings(ctx, config, onChange) {
6530
6915
  autoDelete: boolValueOf(stored, "svnAutoDeleteMissing", true)
6531
6916
  };
6532
6917
  aiUiCurrent = { commitStyle: commitStyleValueOf(stored) };
6918
+ externalCurrent = {
6919
+ watch: boolValueOf(stored, "externalWatch", true),
6920
+ scan: boolValueOf(stored, "externalScan", true)
6921
+ };
6533
6922
  };
6534
6923
  /** 读取 settings 存储值(describe 未就绪返回 undefined)。 */
6535
6924
  const storedValue = () => {
@@ -6544,7 +6933,9 @@ function setupOpenSettings(ctx, config, onChange) {
6544
6933
  svnAutoAddUnversioned: svnCurrent.autoAdd,
6545
6934
  svnAutoDeleteMissing: svnCurrent.autoDelete,
6546
6935
  svnReadOnly: svnCurrent.readOnly,
6547
- aiCommitStyle: aiUiCurrent.commitStyle
6936
+ aiCommitStyle: aiUiCurrent.commitStyle,
6937
+ externalWatch: externalCurrent.watch,
6938
+ externalScan: externalCurrent.scan
6548
6939
  }, {
6549
6940
  setSource: (source) => {
6550
6941
  notify(source().fileOpenTool);
@@ -6585,6 +6976,7 @@ function setupOpenSettings(ctx, config, onChange) {
6585
6976
  autoDelete: svnCurrent.autoDelete
6586
6977
  }),
6587
6978
  aiUi: () => aiUiCurrent,
6979
+ external: () => externalCurrent,
6588
6980
  aiUpdate: async (patch, expectedRevision) => {
6589
6981
  const stored = { ...aiCurrent };
6590
6982
  const body = {};
@@ -8897,6 +9289,7 @@ async function syncMirrorFile(absPath, content) {
8897
9289
  try {
8898
9290
  await mkdir(dirname(absPath), { recursive: true });
8899
9291
  await writeFile(absPath, content, "utf8");
9292
+ windows.markSelf(pathKeyOf(absPath));
8900
9293
  return null;
8901
9294
  } catch (error) {
8902
9295
  return String(error);
@@ -11459,6 +11852,23 @@ function recordGap(scope, exec, path, error) {
11459
11852
  while (captureGaps.size > 500) captureGaps.delete(captureGaps.keys().next().value);
11460
11853
  }
11461
11854
  /**
11855
+ * @public
11856
+ * @author ddj 2026-11-24
11857
+ * @description: 外部采集(watch / 补扫)的缺口上报:非文本、超大、读取失败都记进同一份列表,
11858
+ * 让面板能把「没记下来」说清楚,而不是静默丢条目。
11859
+ * @param cwd 工作区
11860
+ * @param sessionId 会话
11861
+ * @param path 出问题的路径
11862
+ * @param error 原因
11863
+ * @returns 无
11864
+ */
11865
+ function noteCaptureGap(cwd, sessionId, path, error) {
11866
+ recordGap({
11867
+ cwd,
11868
+ sessionId
11869
+ }, { id: "external" }, path, error);
11870
+ }
11871
+ /**
11462
11872
  * @author ddj 2026年10月30号
11463
11873
  * @description: 安装写文件采集;读写失败只影响待审来源,绝不影响用户工具本身。
11464
11874
  * @param ctx Host 生命周期
@@ -11491,7 +11901,7 @@ function installPending(ctx, sink, options) {
11491
11901
  * @param exec 工具分发上下文
11492
11902
  * @returns 采集计划或 null
11493
11903
  */
11494
- async function planOf(scope, state, requested) {
11904
+ async function planOf(scope, state, requested, tool) {
11495
11905
  const { cwd, sessionId, fs } = scope;
11496
11906
  if (state.stopped || state.disposed.has(sessionId)) return null;
11497
11907
  const target = await fs.resolve(requested, { cwd });
@@ -11511,7 +11921,8 @@ async function planOf(scope, state, requested) {
11511
11921
  identity,
11512
11922
  before,
11513
11923
  target,
11514
- fs
11924
+ fs,
11925
+ tool
11515
11926
  };
11516
11927
  } catch (error) {
11517
11928
  state.busy.delete(identity);
@@ -11607,9 +12018,10 @@ async function reconcileBulk(scope, exec, result, plans) {
11607
12018
  */
11608
12019
  async function buildPlans(scope, state, exec, paths) {
11609
12020
  const plans = [];
12021
+ const tool = String(exec.name ?? "");
11610
12022
  for (const path of paths) try {
11611
12023
  if (plans.length >= 16) throw new Error("capture target budget exceeded");
11612
- const plan = await planOf(scope, state, path);
12024
+ const plan = await planOf(scope, state, path, tool);
11613
12025
  if (plan) plans.push(plan);
11614
12026
  } catch (error) {
11615
12027
  if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, path, error);
@@ -11690,7 +12102,8 @@ async function reportWrite(state, sink, plan) {
11690
12102
  identity: plan.identity,
11691
12103
  before: plan.before,
11692
12104
  after,
11693
- now: Date.now()
12105
+ now: Date.now(),
12106
+ tool: plan.tool
11694
12107
  });
11695
12108
  }
11696
12109
  /**
@@ -12061,6 +12474,132 @@ async function runCommand(shell, command, workdir, stdoutMaxBytes = STDOUT_BUDGE
12061
12474
  }
12062
12475
  }
12063
12476
  /**
12477
+ * @author ddj 2026-11-24
12478
+ * @description: 只读一条状态命令,取「工作副本相对基线有改动」的路径集合。补扫用它当候选与
12479
+ * 「干净」判据:不在集合里的路径,其内容变化只能来自版本库同步,不该记成 agent 改动。
12480
+ * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
12481
+ * @param shell shell 能力
12482
+ * @param cwd 工作区
12483
+ * @param onFailure 失败原因回调(可选):调用方用它把「为什么没有状态」写进采集缺口
12484
+ * @returns 状态集合或 null
12485
+ */
12486
+ async function vcsStatus(shell, cwd, onFailure) {
12487
+ const detected = await detectVcsRoot(cwd);
12488
+ if (!detected) {
12489
+ onFailure?.("不是 git/svn 工作副本");
12490
+ return null;
12491
+ }
12492
+ if (detected.kind === "p4") {
12493
+ onFailure?.("Perforce 工作副本不支持状态探测");
12494
+ return null;
12495
+ }
12496
+ return detected.kind === "git" ? gitStatus(shell, detected.root, onFailure) : svnStatus(shell, detected.root, onFailure);
12497
+ }
12498
+ /**
12499
+ * @private
12500
+ * @author ddj 2026-11-24
12501
+ * @description: git 状态:一条 status 命令解析出改动集合。
12502
+ * @param shell shell 能力
12503
+ * @param root 仓库根
12504
+ * @param onFailure 失败原因回调(可选)
12505
+ * @returns 状态集合或 null(命令失败)
12506
+ */
12507
+ async function gitStatus(shell, root, onFailure) {
12508
+ const status = await runCommand(shell, "git -c status.renames=false status --porcelain=v1 -z --untracked-files=all", root);
12509
+ if (!status.ok) {
12510
+ onFailure?.("git status 失败:" + status.stderr.slice(0, 200));
12511
+ return null;
12512
+ }
12513
+ const entries = /* @__PURE__ */ new Map();
12514
+ for (const entry of parseGitStatus(status.stdout)) {
12515
+ const absolute = join(root, ...entry.path.split(GIT_SEPARATOR));
12516
+ if (!insideRoot$1(root, absolute)) continue;
12517
+ entries.set(pathKeyOf(absolute), {
12518
+ path: absolute,
12519
+ status: gitStatusOf(entry.status)
12520
+ });
12521
+ }
12522
+ return {
12523
+ kind: "git",
12524
+ root,
12525
+ entries
12526
+ };
12527
+ }
12528
+ /**
12529
+ * @private
12530
+ * @author ddj 2026-11-24
12531
+ * @description: svn 状态:一条 status --xml 解析出改动集合。
12532
+ * @param shell shell 能力
12533
+ * @param root 工作副本根
12534
+ * @param onFailure 失败原因回调(可选)
12535
+ * @returns 状态集合或 null(命令失败)
12536
+ */
12537
+ async function svnStatus(shell, root, onFailure) {
12538
+ const status = await runCommand(shell, "svn status --xml", root);
12539
+ if (!status.ok) {
12540
+ onFailure?.("svn status 失败:" + status.stderr.slice(0, 200));
12541
+ return null;
12542
+ }
12543
+ const entries = /* @__PURE__ */ new Map();
12544
+ for (const entry of parseSvnStatus(status.stdout)) {
12545
+ const absolute = resolve(root, entry.path);
12546
+ if (!insideRoot$1(root, absolute)) continue;
12547
+ entries.set(pathKeyOf(absolute), {
12548
+ path: absolute,
12549
+ status: svnStatusOf(entry.status)
12550
+ });
12551
+ }
12552
+ return {
12553
+ kind: "svn",
12554
+ root,
12555
+ entries
12556
+ };
12557
+ }
12558
+ /**
12559
+ * @private
12560
+ * @author ddj 2026-11-24
12561
+ * @description: git 状态码归一:删除优先,其次新增/未跟踪,其余按修改。
12562
+ * @param status 两位状态码
12563
+ * @returns 归一状态
12564
+ */
12565
+ function gitStatusOf(status) {
12566
+ if (status.includes("D")) return "deleted";
12567
+ if (status === "??" || status.includes("A")) return "added";
12568
+ return "modified";
12569
+ }
12570
+ /**
12571
+ * @private
12572
+ * @author ddj 2026-11-24
12573
+ * @description: svn 条目状态归一。
12574
+ * @param status wc-status 的 item 值
12575
+ * @returns 归一状态
12576
+ */
12577
+ function svnStatusOf(status) {
12578
+ if (status === "deleted" || status === "missing") return "deleted";
12579
+ if (status === "added" || status === "unversioned" || status === "replaced") return "added";
12580
+ return "modified";
12581
+ }
12582
+ /**
12583
+ * @author ddj 2026-11-24
12584
+ * @description: 读某路径的版本库基线内容;只用于补录记录的修改前内容。
12585
+ * @param shell shell 能力
12586
+ * @param status 已探测的状态(给根目录与种类)
12587
+ * @param absolute 绝对路径
12588
+ * @returns 基线内容;读不到返回 null
12589
+ */
12590
+ async function vcsBaselineOf(shell, status, absolute) {
12591
+ const root = status.root;
12592
+ const relative = absolute.slice(root.length).replace(/^[\\/]+/, "").split(sep).join(GIT_SEPARATOR);
12593
+ if (!relative) return null;
12594
+ try {
12595
+ if (status.kind === "git") return await gitBaseline(shell, root, relative);
12596
+ const shown = await runCommand(shell, `svn cat -r BASE ${quote(absolute)}`, root);
12597
+ return shown.ok ? shown.stdout : null;
12598
+ } catch {
12599
+ return null;
12600
+ }
12601
+ }
12602
+ /**
12064
12603
  * @author ddj 2026年10月30号
12065
12604
  * @description: 读单元格文本,不存在时返回 null。
12066
12605
  * @param path 文件路径
@@ -12130,6 +12669,841 @@ function decodeXml(value) {
12130
12669
  return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&apos;/g, "'").replace(/&amp;/g, "&");
12131
12670
  }
12132
12671
  //#endregion
12672
+ //#region src/pending/externalAlign.ts
12673
+ /**
12674
+ * 外部改动补扫:拿版本库当基线,把「插件还没记录过」的工作副本改动用 `source='scan'` 补录,
12675
+ * 同时提供 watch 采集需要的两个只读能力(改动集合与基线内容)。
12676
+ *
12677
+ * 设计取舍:
12678
+ * - 候选只来自一条 `git status` / `svn status` 命令,不遍历目录树;因此 200 MB 仓库的启动对齐
12679
+ * 与定时补扫都只花「一条命令 + 少量读盘」。
12680
+ * - 不在版本库改动集合里的路径一律不建记录:内容变化只能来自版本库同步,记成 agent 改动会
12681
+ * 污染审查队列并让撤销误伤(见任务书验收 4)。
12682
+ * - 基线与读盘都有硬上限(条数、字节、截止时间),超限写 `gaps`,绝不静默截断。
12683
+ * 作者 ddj 2026-11-24
12684
+ */
12685
+ var externalAlign_exports = /* @__PURE__ */ __exportAll({
12686
+ ALIGN_BUDGET: () => ALIGN_BUDGET,
12687
+ ALIGN_FILE_MAX: () => ALIGN_FILE_MAX,
12688
+ alignExternal: () => alignExternal,
12689
+ alignInWorkspace: () => alignInWorkspace,
12690
+ vcsScopeOf: () => vcsScopeOf
12691
+ });
12692
+ /** 默认预算:大仓下也只是一条 status 命令加几十次读盘。 */
12693
+ const ALIGN_BUDGET = {
12694
+ paths: 2e3,
12695
+ bytes: 16 << 20,
12696
+ deadlineMs: 5e3,
12697
+ baselines: 32
12698
+ };
12699
+ /** 单文件读取上限:与待审采集一致,超出只标 oversized 不读全文。 */
12700
+ const ALIGN_FILE_MAX = 1048576;
12701
+ /**
12702
+ * @author ddj 2026-11-24
12703
+ * @description: 取本会话可用的版本库能力;没有 shell 服务或会话不存在时返回 null。
12704
+ * @param ctx Host 上下文
12705
+ * @param cwd 工作区
12706
+ * @param sessionId 会话
12707
+ * @returns 作用域或 null
12708
+ */
12709
+ function vcsScopeOf(ctx, cwd, sessionId) {
12710
+ const raw = ctx.get("shell");
12711
+ if (!raw || typeof raw.resolve !== "function") return null;
12712
+ const policy = policyOf(ctx, sessionOf(ctx, sessionId));
12713
+ return {
12714
+ cwd: String(cwd),
12715
+ sessionId,
12716
+ shell: {
12717
+ resolve: (request) => raw.resolve(policy ? {
12718
+ ...request,
12719
+ sandboxPolicy: policy
12720
+ } : request),
12721
+ execute: (spec) => raw.execute(spec)
12722
+ }
12723
+ };
12724
+ }
12725
+ /**
12726
+ * @author ddj 2026-11-24
12727
+ * @description: 一次补扫:版本库候选 → 逐条对比已知内容 → 未记录的补录(source='scan')。
12728
+ * 无版本库或状态命令不可用时降级为「只对齐已记录条目」,并把原因写进 gaps。
12729
+ * @param scope 版本库作用域(可为空:无 shell 时走降级)
12730
+ * @param deps 读盘与落库能力
12731
+ * @param budget 预算
12732
+ * @returns 结果
12733
+ */
12734
+ async function alignExternal(scope, deps, budget = ALIGN_BUDGET) {
12735
+ const started = Date.now();
12736
+ const now = deps.now ?? Date.now;
12737
+ const gaps = [];
12738
+ const known = deps.entries();
12739
+ const status = scope ? await vcsStatus(scope.shell, scope.cwd) : null;
12740
+ if (!status) {
12741
+ const reason = scope ? "版本库状态不可用(非 git/svn 或命令失败):补扫只对齐已记录条目" : "当前环境没有 shell 能力:补扫只对齐已记录条目";
12742
+ gaps.push(reason);
12743
+ return {
12744
+ imported: await reconcileKnown(scope, deps, known, budget, started, now, gaps),
12745
+ changed: 0,
12746
+ gaps
12747
+ };
12748
+ }
12749
+ const candidates = [...status.entries];
12750
+ if (candidates.length > budget.paths) gaps.push(`版本库报告 ${candidates.length} 个改动,本次只处理前 ${budget.paths} 个`);
12751
+ let imported = 0;
12752
+ let bytes = 0;
12753
+ let baselines = 0;
12754
+ for (const [key, entry] of candidates.slice(0, budget.paths)) {
12755
+ if (Date.now() - started > budget.deadlineMs) {
12756
+ gaps.push(`补扫超过 ${budget.deadlineMs}ms,剩余改动留到下一轮`);
12757
+ break;
12758
+ }
12759
+ const stored = known.get(key);
12760
+ const absolute = entry.path;
12761
+ try {
12762
+ if (entry.status === "deleted") {
12763
+ if (stored && stored.flags.missing) continue;
12764
+ deps.record(writeOf(scope, absolute, stored ? stored.entry.newText : null, null, now(), "external", stored ? "known" : "unknown"));
12765
+ imported += 1;
12766
+ continue;
12767
+ }
12768
+ const content = await deps.read(absolute);
12769
+ if (content === null) continue;
12770
+ if (content.length > 1048576) {
12771
+ gaps.push(absolute + ": 超过单文件上限,未补扫");
12772
+ continue;
12773
+ }
12774
+ if (stored && stored.entry.newText === content) continue;
12775
+ if (bytes + content.length > budget.bytes) {
12776
+ gaps.push(absolute + ": 补扫读取预算已用尽,未补扫");
12777
+ continue;
12778
+ }
12779
+ bytes += content.length;
12780
+ if (stored) {
12781
+ deps.record(writeOf(scope, absolute, stored.entry.newText, content, now(), "external", "known"));
12782
+ imported += 1;
12783
+ continue;
12784
+ }
12785
+ if (entry.status === "added") {
12786
+ deps.record(writeOf(scope, absolute, null, content, now(), "external", "absent"));
12787
+ imported += 1;
12788
+ continue;
12789
+ }
12790
+ let base = null;
12791
+ if (baselines < budget.baselines) {
12792
+ baselines += 1;
12793
+ base = await vcsBaselineOf(scope.shell, status, absolute);
12794
+ } else gaps.push(absolute + ": 基线读取预算已用尽,记为基线未知");
12795
+ deps.record(writeOf(scope, absolute, base, content, now(), "external", base === null ? "unknown" : "vcs"));
12796
+ imported += 1;
12797
+ } catch (error) {
12798
+ gaps.push(absolute + ": " + String(error));
12799
+ }
12800
+ }
12801
+ return {
12802
+ imported,
12803
+ changed: candidates.length,
12804
+ gaps
12805
+ };
12806
+ }
12807
+ /**
12808
+ * @private
12809
+ * @author ddj 2026-11-24
12810
+ * @description: 降级路径:只把已记录条目与磁盘对齐(条目数很小,不会遍历仓库)。
12811
+ * @param scope 版本库作用域
12812
+ * @param deps 读盘与落库能力
12813
+ * @param known 已落库条目
12814
+ * @param budget 预算
12815
+ * @param started 起始时间
12816
+ * @param now 时钟
12817
+ * @param gaps 缺口输出
12818
+ * @returns 无
12819
+ */
12820
+ async function reconcileKnown(scope, deps, known, budget, started, now, gaps) {
12821
+ let bytes = 0;
12822
+ let imported = 0;
12823
+ for (const stored of known.values()) {
12824
+ if (Date.now() - started > budget.deadlineMs) {
12825
+ gaps.push("降级补扫超过截止时间,剩余条目留到下一轮");
12826
+ break;
12827
+ }
12828
+ try {
12829
+ const content = await deps.read(stored.entry.id);
12830
+ if (content === null) {
12831
+ if (stored.flags.missing) continue;
12832
+ deps.record(writeOf(scope, stored.entry.path, stored.entry.newText, null, now(), "external", "known"));
12833
+ imported += 1;
12834
+ continue;
12835
+ }
12836
+ if (content === stored.entry.newText) continue;
12837
+ if (bytes + content.length > budget.bytes) {
12838
+ gaps.push(stored.entry.path + ": 补扫读取预算已用尽,未补扫");
12839
+ break;
12840
+ }
12841
+ bytes += content.length;
12842
+ deps.record(writeOf(scope, stored.entry.path, stored.entry.newText, content, now(), "external", "known"));
12843
+ imported += 1;
12844
+ } catch (error) {
12845
+ gaps.push(stored.entry.path + ": " + String(error));
12846
+ }
12847
+ }
12848
+ return imported;
12849
+ }
12850
+ /**
12851
+ * @private
12852
+ * @author ddj 2026-11-24
12853
+ * @description: 组装一条待审写入;补扫只产出 `source='scan'` 的记录。
12854
+ * @param scope 版本库作用域
12855
+ * @param absolute 绝对路径
12856
+ * @param before 修改前内容(null = 当时不存在或未知,由 baseKind 区分)
12857
+ * @param after 当前内容(null = 已删除)
12858
+ * @param at 时间
12859
+ * @param origin 归属
12860
+ * @param baseKind 基线可信度
12861
+ * @returns 待审写入
12862
+ */
12863
+ function writeOf(scope, absolute, before, after, at, origin, baseKind) {
12864
+ return {
12865
+ cwd: scope?.cwd ?? "",
12866
+ sessionId: scope?.sessionId ?? "",
12867
+ path: absolute,
12868
+ identity: absolute,
12869
+ before,
12870
+ after,
12871
+ now: at,
12872
+ tool: "scan",
12873
+ origin,
12874
+ baseKind
12875
+ };
12876
+ }
12877
+ /**
12878
+ * @author ddj 2026-11-24
12879
+ * @description: 用 Host 能力跑一次补扫:版本库候选 + 待审库条目 + ctx.fs 读盘。
12880
+ * @param ctx Host 上下文
12881
+ * @param cwd 工作区
12882
+ * @param sessionId 会话
12883
+ * @param record 落库回调(复用待审采集 sink)
12884
+ * @param budget 预算
12885
+ * @returns 结果
12886
+ */
12887
+ async function alignInWorkspace(ctx, cwd, sessionId, record, budget = ALIGN_BUDGET) {
12888
+ const fs = ctx.get("fs");
12889
+ if (!fs) return {
12890
+ imported: 0,
12891
+ changed: 0,
12892
+ gaps: ["缺少 fs 服务:补扫未执行"]
12893
+ };
12894
+ const entries = /* @__PURE__ */ new Map();
12895
+ for (const stored of loadEntries(cwd)) entries.set(pathKeyOf(stored.entry.id), stored);
12896
+ const deps = {
12897
+ read: async (absolute) => {
12898
+ try {
12899
+ const target = await fs.resolve(absolute, { cwd });
12900
+ return await readText$1(fs, target);
12901
+ } catch (error) {
12902
+ noteCaptureGap(cwd, sessionId, absolute, error);
12903
+ throw error;
12904
+ }
12905
+ },
12906
+ record,
12907
+ entries: () => entries
12908
+ };
12909
+ try {
12910
+ const outcome = await alignExternal(vcsScopeOf(ctx, cwd, sessionId), deps, budget);
12911
+ for (const gap of outcome.gaps) log.debug("补扫:" + gap);
12912
+ return outcome;
12913
+ } catch (error) {
12914
+ log.warn("补扫失败:" + String(error));
12915
+ return {
12916
+ imported: 0,
12917
+ changed: 0,
12918
+ gaps: ["补扫失败:" + String(error)]
12919
+ };
12920
+ }
12921
+ }
12922
+ /** 保存风暴的封顶:从首个事件算起最多等这么久就开跑。 */
12923
+ const MAX_WAIT_MS$1 = 2e3;
12924
+ /** 内存基线表上限(路径比较键数)。 */
12925
+ const SEEN_MAX = 5e3;
12926
+ /** 定时补扫间隔。 */
12927
+ const ALIGN_INTERVAL_MS = 6e5;
12928
+ /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
12929
+ const ALIGN_AFTER_VCS_MS = 1500;
12930
+ /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
12931
+ const VCS_WRITE_METHODS = /* @__PURE__ */ new Set([
12932
+ "svn.revert",
12933
+ "svn.resolve",
12934
+ "svn.add",
12935
+ "svn.cleanup",
12936
+ "svn.update",
12937
+ "svn.ignore",
12938
+ "svn.commit"
12939
+ ]);
12940
+ /** 会改动工作副本的版本库工具名。 */
12941
+ const VCS_WRITE_TOOLS = /* @__PURE__ */ new Set([
12942
+ "svn_add",
12943
+ "svn_delete",
12944
+ "svn_revert",
12945
+ "svn_commit",
12946
+ "svn_update",
12947
+ "svn_resolve",
12948
+ "svn_cleanup",
12949
+ "svn_propset",
12950
+ "svn_propdel",
12951
+ "svn_changelist",
12952
+ "remote_ssh_write"
12953
+ ]);
12954
+ /**
12955
+ * 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。
12956
+ * 只收版本库元数据、Unity 缓存与构建产物:第三方与代码生成目录不在忽略之列,
12957
+ * 它们的改动靠「mtime 证据 + 版本库状态」两道闸门拦,而不是按目录名一刀切。
12958
+ */
12959
+ const EXTRA_IGNORE_SEGMENTS = [
12960
+ ".svn",
12961
+ ".hg",
12962
+ ".p4config",
12963
+ "Library",
12964
+ "Temp",
12965
+ "obj",
12966
+ "Logs"
12967
+ ];
12968
+ /** 忽略集合:目录段 + 文件名模式。 */
12969
+ const IGNORE_SEGMENTS = /* @__PURE__ */ new Set([...EXCLUDES, ...EXTRA_IGNORE_SEGMENTS]);
12970
+ /** 忽略文件名(glob 只有这几条,直接判后缀/全名,不引第三方匹配器)。 */
12971
+ const IGNORE_FILES = new Set(FILE_EXCLUDES.map((pattern) => pattern.replace(/^\*\*\//, "")));
12972
+ /**
12973
+ * @public
12974
+ * @author ddj 2026-11-24
12975
+ * @description: 判断绝对路径是否不进记录:工作区外、忽略目录段、插件自身 sidecar、构建产物、`.map`、
12976
+ * 以及计划页打包临时目录 `plans/<slug>/runtime/`。
12977
+ * @param cwd 工作区根
12978
+ * @param absolute 绝对路径
12979
+ * @returns 忽略返回 true
12980
+ */
12981
+ function isIgnoredPath(cwd, absolute) {
12982
+ const root = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
12983
+ const unified = absolute.replace(/\\/g, "/");
12984
+ if (root && !(unified === root || unified.toLowerCase().startsWith(root.toLowerCase() + "/"))) return true;
12985
+ const segments = (root && unified.length > root.length ? unified.slice(root.length + 1) : unified).split("/").filter(Boolean);
12986
+ if (!segments.length) return true;
12987
+ for (const segment of segments.slice(0, -1)) if (IGNORE_SEGMENTS.has(segment)) return true;
12988
+ const name = segments[segments.length - 1];
12989
+ if (IGNORE_SEGMENTS.has(name)) return true;
12990
+ if (IGNORE_FILES.has(name)) return true;
12991
+ if (name.endsWith(".map")) return true;
12992
+ for (let index = 0; index + 2 < segments.length; index++) if (segments[index] === "plans" && segments[index + 2] === "runtime") return true;
12993
+ return false;
12994
+ }
12995
+ /**
12996
+ * @public
12997
+ * @author ddj 2026-11-24
12998
+ * @description: 装配外部改动采集:watch 进队、合并读盘、按判定链落库;可整体卸载。
12999
+ * @param deps Host 能力与测试接缝
13000
+ * @returns 采集器
13001
+ */
13002
+ function installExternalCapture(deps) {
13003
+ const spaces = /* @__PURE__ */ new Map();
13004
+ const now = deps.now ?? Date.now;
13005
+ let seq = 0;
13006
+ let stopped = false;
13007
+ /**
13008
+ * @private
13009
+ * @description: 取(或建)工作区运行时状态。
13010
+ * @param cwd 工作区
13011
+ * @param sessionId 会话
13012
+ * @returns 状态
13013
+ */
13014
+ function spaceOf(cwd, sessionId) {
13015
+ const key = pathKeyOf(cwd);
13016
+ const existing = spaces.get(key);
13017
+ if (existing) return existing;
13018
+ const created = {
13019
+ cwd: String(cwd),
13020
+ sessionId,
13021
+ watchers: [],
13022
+ dirty: /* @__PURE__ */ new Map(),
13023
+ seen: /* @__PURE__ */ new Map(),
13024
+ timer: null,
13025
+ firstAt: 0,
13026
+ flushing: false,
13027
+ again: false,
13028
+ degraded: "",
13029
+ statusAt: 0,
13030
+ status: void 0,
13031
+ alignedAt: 0,
13032
+ alignTimer: null,
13033
+ requestTimer: null,
13034
+ startedAt: 0,
13035
+ gapKeys: /* @__PURE__ */ new Set(),
13036
+ statusNoteAt: 0
13037
+ };
13038
+ spaces.set(key, created);
13039
+ return created;
13040
+ }
13041
+ /**
13042
+ * @private
13043
+ * @description: 事件分发:只收文件名,忽略目录与忽略清单。
13044
+ * @param space 工作区状态
13045
+ * @param base 被监听目录
13046
+ * @param name 事件文件名
13047
+ * @returns 无
13048
+ */
13049
+ function onEvent(space, base, name) {
13050
+ if (stopped || !name) return;
13051
+ enqueue(space.cwd, resolve(base, String(name)));
13052
+ }
13053
+ /**
13054
+ * @private
13055
+ * @description: 关闭一个工作区的全部监听器。
13056
+ * @param space 工作区状态
13057
+ * @returns 无
13058
+ */
13059
+ function closeWatchers(space) {
13060
+ for (const watcher of space.watchers) try {
13061
+ watcher.close();
13062
+ } catch {}
13063
+ space.watchers = [];
13064
+ }
13065
+ /**
13066
+ * @private
13067
+ * @description: 开始监听;递归可用就用递归,否则逐一级子目录监听,都不可用时只留补扫。
13068
+ * @param space 工作区状态
13069
+ * @returns 无
13070
+ */
13071
+ function startWatch(space) {
13072
+ if (space.watchers.length || stopped) return;
13073
+ space.startedAt = now();
13074
+ try {
13075
+ const watcher = watch(space.cwd, {
13076
+ recursive: true,
13077
+ persistent: false
13078
+ }, (_event, name) => onEvent(space, space.cwd, name));
13079
+ watcher.on("error", (error) => {
13080
+ log.warn("外部改动监听中断(改为只靠补扫):" + String(error));
13081
+ closeWatchers(space);
13082
+ });
13083
+ space.watchers.push(watcher);
13084
+ return;
13085
+ } catch (error) {
13086
+ log.debug("递归监听不可用,降级逐目录监听:" + String(error));
13087
+ }
13088
+ try {
13089
+ const entries = readdirSync(space.cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !IGNORE_SEGMENTS.has(entry.name)).slice(0, 64);
13090
+ for (const entry of entries) {
13091
+ const dir = join(space.cwd, entry.name);
13092
+ const watcher = watch(dir, { persistent: false }, (_event, name) => onEvent(space, dir, name));
13093
+ watcher.on("error", (error) => log.debug("目录监听中断:" + dir + " " + String(error)));
13094
+ space.watchers.push(watcher);
13095
+ }
13096
+ if (!space.watchers.length) space.degraded = "目录监听不可用";
13097
+ } catch (error) {
13098
+ space.degraded = "目录监听不可用:" + String(error);
13099
+ log.warn("外部改动监听不可用(改为只靠补扫):" + String(error));
13100
+ }
13101
+ }
13102
+ /**
13103
+ * @private
13104
+ * @description: 重新安排本批处理时刻:静默 300ms,但不超过首个事件后 2000ms。
13105
+ * @param space 工作区状态
13106
+ * @returns 无
13107
+ */
13108
+ function schedule(space) {
13109
+ const at = now();
13110
+ if (!space.firstAt) space.firstAt = at;
13111
+ if (space.timer) clearTimeout(space.timer);
13112
+ const wait = Math.max(0, Math.min(300, space.firstAt + MAX_WAIT_MS$1 - at));
13113
+ space.timer = setTimeout(() => {
13114
+ space.timer = null;
13115
+ flushSpace(space);
13116
+ }, wait);
13117
+ }
13118
+ /**
13119
+ * @private
13120
+ * @description: 取条目集合:真实路径读待审库,测试可注入。
13121
+ * @param cwd 工作区
13122
+ * @returns 路径比较键 → 条目
13123
+ */
13124
+ function entriesOf(cwd) {
13125
+ if (deps.entries) return deps.entries(cwd);
13126
+ const map = /* @__PURE__ */ new Map();
13127
+ for (const stored of loadEntries(cwd)) map.set(pathKeyOf(stored.entry.id), stored);
13128
+ return map;
13129
+ }
13130
+ /**
13131
+ * @private
13132
+ * @description: 读磁盘内容;缺失返回 null,其它失败抛出(由调用点记缺口)。
13133
+ * @param cwd 工作区
13134
+ * @param absolute 绝对路径
13135
+ * @returns 内容或 null
13136
+ */
13137
+ async function readOf(cwd, absolute) {
13138
+ if (deps.read) return deps.read(cwd, absolute);
13139
+ const fs = deps.ctx.get("fs");
13140
+ if (!fs) throw new Error("缺少 fs 服务");
13141
+ return readText$1(fs, await fs.resolve(absolute, { cwd }));
13142
+ }
13143
+ /**
13144
+ * @private
13145
+ * @description: 取版本库状态(带最小间隔缓存);无 shell 或非 git/svn 时返回 null。
13146
+ * @param space 工作区状态
13147
+ * @returns 状态或 null
13148
+ */
13149
+ async function statusOf(space) {
13150
+ const at = now();
13151
+ if (space.status !== void 0 && at - space.statusAt < 5e3) return space.status;
13152
+ space.statusAt = at;
13153
+ if (deps.status) {
13154
+ space.status = await deps.status(space.cwd, space.sessionId);
13155
+ return space.status;
13156
+ }
13157
+ const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId);
13158
+ if (!scope) {
13159
+ noteStatusOnce(space, "没有 shell 能力,版本库状态不可用");
13160
+ space.status = null;
13161
+ return space.status;
13162
+ }
13163
+ space.status = await vcsStatus(scope.shell, space.cwd, (reason) => noteStatusOnce(space, reason));
13164
+ return space.status;
13165
+ }
13166
+ /**
13167
+ * @private
13168
+ * @author ddj 2026-11-24
13169
+ * @description: 读文件修改时间(测试可注入);读不到返回 undefined。
13170
+ * @param space 工作区状态
13171
+ * @param absolute 绝对路径
13172
+ * @returns 毫秒时间戳或 undefined
13173
+ */
13174
+ function mtimeOf(space, absolute) {
13175
+ if (deps.mtime) return deps.mtime(space.cwd, absolute);
13176
+ try {
13177
+ return statSync(absolute).mtimeMs;
13178
+ } catch {
13179
+ return;
13180
+ }
13181
+ }
13182
+ /**
13183
+ * @private
13184
+ * @author ddj 2026-11-24
13185
+ * @description: 判断文件是否在本次监听开始之后被写过:这是「拿不到版本库状态」时唯一的外部证据。
13186
+ * @param space 工作区状态
13187
+ * @param absolute 绝对路径
13188
+ * @returns 刚被写过返回 true
13189
+ */
13190
+ function recentlyWritten(space, absolute) {
13191
+ if (!space.startedAt) return false;
13192
+ const mtime = mtimeOf(space, absolute);
13193
+ return mtime !== void 0 && mtime >= space.startedAt - 2e3;
13194
+ }
13195
+ /**
13196
+ * @private
13197
+ * @author ddj 2026-11-24
13198
+ * @description: 同一条缺口只上报一次;去重表满了就丢最早的键,保证内存有界。
13199
+ * @param space 工作区状态
13200
+ * @param key 去重键
13201
+ * @param absolute 出问题的路径
13202
+ * @param message 原因
13203
+ * @returns 无
13204
+ */
13205
+ function noteGapOnce(space, key, absolute, message) {
13206
+ if (space.gapKeys.has(key)) return;
13207
+ if (space.gapKeys.size >= 500) {
13208
+ const oldest = space.gapKeys.values().next().value;
13209
+ if (oldest !== void 0) space.gapKeys.delete(oldest);
13210
+ }
13211
+ space.gapKeys.add(key);
13212
+ noteCaptureGap(space.cwd, space.sessionId, absolute, message);
13213
+ }
13214
+ /**
13215
+ * @private
13216
+ * @author ddj 2026-11-24
13217
+ * @description: 「版本库状态不可用」按工作区节流上报,让面板能说清为什么没拦住噪声。
13218
+ * @param space 工作区状态
13219
+ * @param reason 失败原因(命令回执头 200 字)
13220
+ * @returns 无
13221
+ */
13222
+ function noteStatusOnce(space, reason) {
13223
+ const at = now();
13224
+ if (at - space.statusNoteAt < 3e5) return;
13225
+ space.statusNoteAt = at;
13226
+ noteCaptureGap(space.cwd, space.sessionId, space.cwd, "版本库状态不可用:" + reason.slice(0, 200));
13227
+ }
13228
+ /**
13229
+ * @private
13230
+ * @description: 处理一个路径:判定链见文件头注释。
13231
+ * @param space 工作区状态
13232
+ * @param absolute 绝对路径
13233
+ * @param entries 本批共享的条目表
13234
+ * @returns 是否新增或更新了条目
13235
+ */
13236
+ async function handleOne(space, absolute, entries) {
13237
+ const key = pathKeyOf(absolute);
13238
+ const at = now();
13239
+ const content = await readOf(space.cwd, absolute);
13240
+ const stored = entries.get(key);
13241
+ const sameContent = stored !== void 0 && stored.entry.newText === (content ?? "");
13242
+ const sameMissing = stored !== void 0 && stored.flags.missing === (content === null);
13243
+ if (stored && sameContent && sameMissing) {
13244
+ space.seen.set(key, content);
13245
+ return false;
13246
+ }
13247
+ const window = windows.windowOf(key, at);
13248
+ if (window === "self") {
13249
+ space.seen.set(key, content);
13250
+ return false;
13251
+ }
13252
+ if (window === "editor") {
13253
+ space.seen.set(key, content);
13254
+ if (!stored) return false;
13255
+ deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "watch", "editor", "known"));
13256
+ return true;
13257
+ }
13258
+ const status = await statusOf(space);
13259
+ if (status && !status.entries.has(key)) {
13260
+ space.seen.set(key, content);
13261
+ if (!stored) return false;
13262
+ deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "vcs", "vcs", "known"));
13263
+ return true;
13264
+ }
13265
+ if (!status && !stored && !space.seen.has(key) && !recentlyWritten(space, absolute)) {
13266
+ noteGapOnce(space, "absent:" + key, absolute, "无版本库状态且文件未改动,未建档");
13267
+ space.seen.set(key, content);
13268
+ return false;
13269
+ }
13270
+ const before = await beforeOf(space, key, absolute, stored, status, content);
13271
+ if (before.text === null && content === null) {
13272
+ space.seen.set(key, null);
13273
+ return false;
13274
+ }
13275
+ deps.record(writeOf(space, absolute, before.text, content, at, "watch", windows.inAgentWindow(at) ? "agent" : "external", before.kind));
13276
+ space.seen.set(key, content);
13277
+ return true;
13278
+ }
13279
+ /**
13280
+ * @private
13281
+ * @description: 求修改前内容:已知内容 → 首次观察 → 版本库新增/基线 → 未知。
13282
+ * @param space 工作区状态
13283
+ * @param key 路径比较键
13284
+ * @param absolute 绝对路径
13285
+ * @param stored 既有条目
13286
+ * @param status 版本库状态
13287
+ * @param content 当前内容
13288
+ * @returns 修改前内容与可信度
13289
+ */
13290
+ async function beforeOf(space, key, absolute, stored, status, content) {
13291
+ if (stored) return {
13292
+ text: stored.flags.missing ? null : stored.entry.newText,
13293
+ kind: "known"
13294
+ };
13295
+ if (space.seen.has(key)) {
13296
+ const seen = space.seen.get(key) ?? null;
13297
+ return {
13298
+ text: seen,
13299
+ kind: seen === null ? "absent" : "known"
13300
+ };
13301
+ }
13302
+ const entry = status?.entries.get(key);
13303
+ if (entry?.status === "added") return {
13304
+ text: null,
13305
+ kind: "absent"
13306
+ };
13307
+ if (entry && content !== null) {
13308
+ const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId);
13309
+ if (scope && status) {
13310
+ const base = await vcsBaselineOf(scope.shell, status, absolute);
13311
+ if (base !== null) return {
13312
+ text: base,
13313
+ kind: "vcs"
13314
+ };
13315
+ }
13316
+ }
13317
+ return {
13318
+ text: null,
13319
+ kind: "unknown"
13320
+ };
13321
+ }
13322
+ /**
13323
+ * @private
13324
+ * @description: 组装一条待审写入(watch 通道)。
13325
+ * @param space 工作区状态
13326
+ * @param absolute 绝对路径
13327
+ * @param before 修改前内容
13328
+ * @param after 当前内容
13329
+ * @param at 时间
13330
+ * @param source 采集通道
13331
+ * @param origin 归属
13332
+ * @param baseKind 基线可信度
13333
+ * @returns 待审写入
13334
+ */
13335
+ function writeOf(space, absolute, before, after, at, source, origin, baseKind) {
13336
+ return {
13337
+ cwd: space.cwd,
13338
+ sessionId: space.sessionId,
13339
+ path: absolute,
13340
+ identity: absolute,
13341
+ before,
13342
+ after,
13343
+ now: at,
13344
+ tool: source,
13345
+ origin,
13346
+ baseKind
13347
+ };
13348
+ }
13349
+ /**
13350
+ * @private
13351
+ * @description: 处理本工作区的一个批次:取一批 → 读盘判定 → 落库 → 失效目录树。
13352
+ * @param space 工作区状态
13353
+ * @returns 无
13354
+ */
13355
+ async function flushSpace(space) {
13356
+ if (stopped) return;
13357
+ if (space.flushing) {
13358
+ space.again = true;
13359
+ return;
13360
+ }
13361
+ space.flushing = true;
13362
+ space.firstAt = 0;
13363
+ let bytes = 0;
13364
+ let recorded = 0;
13365
+ try {
13366
+ const entries = entriesOf(space.cwd);
13367
+ const batch = [...space.dirty.entries()].slice(0, 64);
13368
+ for (const [key] of batch) space.dirty.delete(key);
13369
+ const ordered = batch.sort((left, right) => left[1].seq - right[1].seq);
13370
+ const touched = [];
13371
+ for (const [, item] of ordered) {
13372
+ if (stopped) break;
13373
+ try {
13374
+ const size = item.path.length;
13375
+ if (bytes + size > 8388608) {
13376
+ space.dirty.set(pathKeyOf(item.path), item);
13377
+ continue;
13378
+ }
13379
+ bytes += size;
13380
+ if (await handleOne(space, item.path, entries)) {
13381
+ recorded += 1;
13382
+ touched.push(item.path);
13383
+ }
13384
+ } catch (error) {
13385
+ noteCaptureGap(space.cwd, space.sessionId, item.path, error);
13386
+ log.debug("外部改动跳过:" + item.path + ": " + String(error));
13387
+ }
13388
+ }
13389
+ for (const path of touched) invalidateIndex(deps.ctx, space.cwd, path);
13390
+ if (recorded) log.debug(`外部改动记录 ${recorded} 条(${space.cwd})`);
13391
+ } catch (error) {
13392
+ log.warn("外部改动处理失败:" + String(error));
13393
+ } finally {
13394
+ space.flushing = false;
13395
+ if (space.seen.size > 5e3) for (const key of [...space.seen.keys()].slice(0, space.seen.size - SEEN_MAX)) space.seen.delete(key);
13396
+ if (space.dirty.size) schedule(space);
13397
+ else if (space.again) {
13398
+ space.again = false;
13399
+ schedule(space);
13400
+ }
13401
+ }
13402
+ }
13403
+ /**
13404
+ * @private
13405
+ * @description: 收一个写事件进队并重新排期;忽略清单命中直接丢。
13406
+ * @param cwd 工作区
13407
+ * @param absolute 绝对路径
13408
+ * @returns 无
13409
+ */
13410
+ function enqueue(cwd, absolute) {
13411
+ if (stopped || !absolute || !cwd || !deps.settings().watch) return;
13412
+ if (isIgnoredPath(cwd, absolute)) return;
13413
+ const space = spaces.get(pathKeyOf(cwd)) ?? spaceOf(cwd, "");
13414
+ seq += 1;
13415
+ space.dirty.set(pathKeyOf(absolute), {
13416
+ path: absolute,
13417
+ seq
13418
+ });
13419
+ schedule(space);
13420
+ }
13421
+ return {
13422
+ ensure(cwd, sessionId) {
13423
+ if (stopped || !cwd) return;
13424
+ const space = spaceOf(cwd, sessionId);
13425
+ if (!deps.settings().watch) return;
13426
+ startWatch(space);
13427
+ if (!deps.settings().scan || space.alignedAt) return;
13428
+ space.alignedAt = now();
13429
+ const timer = setTimeout(() => {
13430
+ alignNow(space);
13431
+ }, 0);
13432
+ if (typeof timer.unref === "function") timer.unref();
13433
+ if (!space.alignTimer) space.alignTimer = setInterval(() => {
13434
+ alignNow(space);
13435
+ }, ALIGN_INTERVAL_MS);
13436
+ if (typeof space.alignTimer.unref === "function") space.alignTimer.unref();
13437
+ },
13438
+ dismiss(cwd) {
13439
+ const key = pathKeyOf(cwd);
13440
+ const space = spaces.get(key);
13441
+ if (!space) return;
13442
+ closeWatchers(space);
13443
+ if (space.timer) clearTimeout(space.timer);
13444
+ if (space.requestTimer) clearTimeout(space.requestTimer);
13445
+ if (space.alignTimer) clearInterval(space.alignTimer);
13446
+ spaces.delete(key);
13447
+ },
13448
+ requestAlign(cwd, delayMs = ALIGN_AFTER_VCS_MS) {
13449
+ if (stopped || !cwd || !deps.settings().scan) return;
13450
+ const space = spaces.get(pathKeyOf(cwd));
13451
+ if (!space) return;
13452
+ if (space.requestTimer) clearTimeout(space.requestTimer);
13453
+ const timer = setTimeout(() => {
13454
+ space.requestTimer = null;
13455
+ alignNow(space);
13456
+ }, Math.max(0, delayMs));
13457
+ if (typeof timer.unref === "function") timer.unref();
13458
+ space.requestTimer = timer;
13459
+ },
13460
+ enqueue(cwd, absolute) {
13461
+ enqueue(cwd, absolute);
13462
+ },
13463
+ async flush(cwd) {
13464
+ for (const [key, space] of spaces) {
13465
+ if (cwd && key !== pathKeyOf(cwd)) continue;
13466
+ if (space.timer) {
13467
+ clearTimeout(space.timer);
13468
+ space.timer = null;
13469
+ }
13470
+ await flushSpace(space);
13471
+ }
13472
+ },
13473
+ dispose() {
13474
+ stopped = true;
13475
+ for (const space of spaces.values()) {
13476
+ closeWatchers(space);
13477
+ if (space.timer) clearTimeout(space.timer);
13478
+ if (space.alignTimer) clearInterval(space.alignTimer);
13479
+ space.dirty.clear();
13480
+ space.seen.clear();
13481
+ }
13482
+ spaces.clear();
13483
+ }
13484
+ };
13485
+ /**
13486
+ * @private
13487
+ * @description: 后台补扫一次(复用 externalAlign 的候选与预算)。
13488
+ * @param space 工作区状态
13489
+ * @returns 无
13490
+ */
13491
+ async function alignNow(space) {
13492
+ if (stopped || !deps.settings().scan) return;
13493
+ try {
13494
+ if (deps.align) {
13495
+ await deps.align(space.cwd, space.sessionId);
13496
+ return;
13497
+ }
13498
+ const { alignInWorkspace } = await Promise.resolve().then(() => externalAlign_exports);
13499
+ const outcome = await alignInWorkspace(deps.ctx, space.cwd, space.sessionId, deps.record);
13500
+ if (outcome.gaps.length) log.debug("补扫缺口:" + outcome.gaps.join(";"));
13501
+ } catch (error) {
13502
+ log.debug("后台补扫失败:" + String(error));
13503
+ }
13504
+ }
13505
+ }
13506
+ //#endregion
12133
13507
  //#region src/pending/lineDiff.ts
12134
13508
  /** 单窗口 LCS 单元格上限:超过先找锚点;4 MB 表实测约 7 ms。 */
12135
13509
  const LCS_CELLS = 1e6;
@@ -12659,7 +14033,10 @@ function mergeEntries(earlier, later) {
12659
14033
  const merged = {
12660
14034
  ...later,
12661
14035
  updatedAt: later.updatedAt,
12662
- sessionIds: unionSessions(earlier, later)
14036
+ sessionIds: unionSessions(earlier, later),
14037
+ source: strongerSource(earlier.source, later.source),
14038
+ origin: later.origin ?? earlier.origin,
14039
+ baseKind: later.baseKind ?? earlier.baseKind
12663
14040
  };
12664
14041
  if (later.lineage === void 0 && earlier.lineage !== void 0) merged.lineage = earlier.lineage;
12665
14042
  if (earlier.earlierVersion === "none" && later.earlierVersion === "none") {
@@ -12689,6 +14066,9 @@ function entryFromNew(input) {
12689
14066
  sessionIds: [input.sessionId]
12690
14067
  };
12691
14068
  if (input.lineage !== void 0) entry.lineage = input.lineage;
14069
+ if (input.source !== void 0) entry.source = input.source;
14070
+ if (input.origin !== void 0) entry.origin = input.origin;
14071
+ if (input.baseKind !== void 0) entry.baseKind = input.baseKind;
12692
14072
  return entry;
12693
14073
  }
12694
14074
  /**
@@ -12902,8 +14282,9 @@ function markAll(states, targets, decision) {
12902
14282
  return next;
12903
14283
  }
12904
14284
  /**
12905
- * @author ddj 2026年10月29号
12906
- * @description: 能力口径:Keep 恒可;Revert 受超大/缺失/已解决限制,拒绝原因要能展示。
14285
+ * @author ddj 2026年10月29号 / 2026年11月24号
14286
+ * @description: 能力口径:Keep 恒可;Revert 受超大/缺失/已解决/来源限制,拒绝原因要能展示。
14287
+ * 撤销白名单:只有 agent 来源且基线可信时直接可撤销,其它来源要求客户端显式确认。
12907
14288
  * @param entry 待审条目
12908
14289
  * @param flags 持久标记
12909
14290
  * @returns 能力与原因
@@ -12919,11 +14300,22 @@ function capabilityOf$1(entry, flags) {
12919
14300
  revert: false,
12920
14301
  reason: "oversized"
12921
14302
  };
14303
+ if (entry.baseKind === "unknown") return {
14304
+ keep: true,
14305
+ revert: false,
14306
+ reason: "未捕获修改前内容(外部写入):留档可见,但不能撤销,否则会删掉现有代码"
14307
+ };
12922
14308
  if (entry.earlierVersion === "none" && entry.newText.length === 0) return {
12923
14309
  keep: true,
12924
14310
  revert: false,
12925
14311
  reason: "empty-create"
12926
14312
  };
14313
+ if (revertPolicyOf(entry.origin, entry.baseKind) === "confirm") return {
14314
+ keep: true,
14315
+ revert: true,
14316
+ confirmRevert: true,
14317
+ reason: "该改动不是本会话工具写的(" + sourceLabelOf(entry) + "):撤销前请确认"
14318
+ };
12927
14319
  return {
12928
14320
  keep: true,
12929
14321
  revert: true,
@@ -13004,7 +14396,10 @@ function foldWrite(stored, write) {
13004
14396
  earlierVersion: write.before === null ? "none" : "file",
13005
14397
  oldText: write.before ?? "",
13006
14398
  newText: write.after ?? "",
13007
- updatedAt: write.now
14399
+ updatedAt: write.now,
14400
+ source: sourceOfTool(write.tool),
14401
+ origin: originOf(write),
14402
+ baseKind: write.before === null ? "absent" : write.baseKind ?? "known"
13008
14403
  });
13009
14404
  if (!stored) return {
13010
14405
  entry: fresh,
@@ -13028,6 +14423,20 @@ function foldWrite(stored, write) {
13028
14423
  };
13029
14424
  }
13030
14425
  /**
14426
+ * @private
14427
+ * @author ddj 2026-11-24
14428
+ * @description: 本次写入的归属:显式指定优先,否则按窗口判定(工具链路默认 agent)。
14429
+ * @param write 采集到的写入
14430
+ * @returns 归属
14431
+ */
14432
+ function originOf(write) {
14433
+ if (write.origin) return write.origin;
14434
+ const window = windows.windowOf(pathKeyOf(write.identity));
14435
+ if (window === "self") return "agent";
14436
+ if (window === "editor") return "editor";
14437
+ return "agent";
14438
+ }
14439
+ /**
13031
14440
  * @author ddj 2026年10月29号
13032
14441
  * @description: 条目转列表投影,已解决条目仍保留但不可再决定。
13033
14442
  * @param stored 条目与标记
@@ -13051,7 +14460,10 @@ function itemOf(stored, baselineEmpty = false) {
13051
14460
  revision: flags.revision,
13052
14461
  updatedAt: entry.updatedAt,
13053
14462
  sessionId: entry.sessionId,
13054
- sessionIds: entry.sessionIds
14463
+ sessionIds: entry.sessionIds,
14464
+ source: entry.source ?? "tool",
14465
+ origin: entry.origin ?? "agent",
14466
+ baseKind: entry.baseKind ?? "known"
13055
14467
  };
13056
14468
  if (entry.lineage !== void 0) item.lineage = entry.lineage;
13057
14469
  return item;
@@ -13137,14 +14549,16 @@ function recordWrite(write) {
13137
14549
  * @param now 时间
13138
14550
  * @returns 新条目与标记
13139
14551
  */
13140
- function absorbed(stored, content, now) {
14552
+ function absorbed(stored, content, now, origin) {
14553
+ const entry = {
14554
+ ...stored.entry,
14555
+ newText: content,
14556
+ updatedAt: now,
14557
+ unseen: true
14558
+ };
14559
+ if (origin) entry.origin = origin;
13141
14560
  return {
13142
- entry: {
13143
- ...stored.entry,
13144
- newText: content,
13145
- updatedAt: now,
13146
- unseen: true
13147
- },
14561
+ entry,
13148
14562
  flags: {
13149
14563
  ...stored.flags,
13150
14564
  diverged: true,
@@ -13274,7 +14688,7 @@ async function applyDecide(fs, cwd, request, signal, policy) {
13274
14688
  now: Date.now(),
13275
14689
  write: (content) => {
13276
14690
  if (content === null) return deleteTarget(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy);
13277
- return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy)(content);
14691
+ return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy, true)(content);
13278
14692
  }
13279
14693
  });
13280
14694
  if (!outcome.ok) return {
@@ -13622,6 +15036,32 @@ function removeEntry(cwd, id, revision) {
13622
15036
  dropEntry(cwd, id);
13623
15037
  return true;
13624
15038
  }
15039
+ /** 清库默认口径:只清 watch 通道、空基线的条目——幽灵记录就长这样。 */
15040
+ const PURGE_DEFAULT_SOURCES = ["watch"];
15041
+ /** 清库默认基线口径:空基线(改前内容缺失)。 */
15042
+ const PURGE_DEFAULT_BASE_KINDS = ["absent"];
15043
+ /**
15044
+ * @public
15045
+ * @author ddj 2026-11-24
15046
+ * @description: 清掉指定通道的待审条目(幽灵记录治理入口)。dryRun 只报数;
15047
+ * 真删之后按需 VACUUM,把已删行占的页还给磁盘。
15048
+ * @param cwd 工作区
15049
+ * @param filter 筛选条件(缺省 watch + absent)
15050
+ * @param options dryRun 只数不删;vacuum 删除后是否回收
15051
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
15052
+ */
15053
+ function purgePending(cwd, filter = {}, options = {}) {
15054
+ const outcome = purgeEntries(cwd, {
15055
+ sources: filter.sources && filter.sources.length ? filter.sources : PURGE_DEFAULT_SOURCES,
15056
+ baseKinds: filter.baseKinds && filter.baseKinds.length ? filter.baseKinds : PURGE_DEFAULT_BASE_KINDS,
15057
+ before: filter.before
15058
+ }, options.dryRun === true);
15059
+ if (options.dryRun || !outcome.removed || !options.vacuum) return outcome;
15060
+ return {
15061
+ ...outcome,
15062
+ vacuumMs: vacuumEntries(cwd)
15063
+ };
15064
+ }
13625
15065
  /**
13626
15066
  * @author ddj 2026年10月29号
13627
15067
  * @description: 取错误码用于拒绝原因,没有则回落到消息文本。
@@ -13632,6 +15072,253 @@ function reasonOf(error) {
13632
15072
  const code = error.code;
13633
15073
  return typeof code === "string" ? code : String(error);
13634
15074
  }
15075
+ /** 真删前备份文件名后缀。 */
15076
+ const BACKUP_SUFFIX = ".before-purge.bak";
15077
+ /**
15078
+ * @author ddj 2026-11-24
15079
+ * @description: 挑出要删的批次:先按保留期,再按每路径上限,未判完的整批跳过。
15080
+ * @param db 工作区归档库连接
15081
+ * @param options 清理选项
15082
+ * @returns 候选批次 id 与两个统计口径
15083
+ */
15084
+ function pickCandidates(db, options) {
15085
+ const retentionDays = options.retentionDays ?? 30;
15086
+ const keepBatches = options.keepBatches ?? 20;
15087
+ const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1e3;
15088
+ const rows = db.prepare(`SELECT b.id, b.path, b.at, b.pending,
15089
+ (SELECT COUNT(*) FROM records r WHERE r.batch_id = b.id AND r.pending > 0) AS open_records
15090
+ FROM batches b ORDER BY b.path, b.at DESC, b.id DESC`).all();
15091
+ const seen = /* @__PURE__ */ new Map();
15092
+ const picked = /* @__PURE__ */ new Set();
15093
+ let expired = 0;
15094
+ let overCap = 0;
15095
+ let keptPending = 0;
15096
+ for (const row of rows) {
15097
+ const id = Number(row.id);
15098
+ const path = String(row.path);
15099
+ const order = (seen.get(path) ?? 0) + 1;
15100
+ seen.set(path, order);
15101
+ const at = Date.parse(String(row.at));
15102
+ const isExpired = Number.isFinite(at) && at < cutoff;
15103
+ const isOverCap = order > keepBatches;
15104
+ if (!isExpired && !isOverCap) continue;
15105
+ if (isExpired) expired += 1;
15106
+ if (isOverCap) overCap += 1;
15107
+ if (Number(row.pending) > 0 || Number(row.open_records) > 0) {
15108
+ keptPending += 1;
15109
+ continue;
15110
+ }
15111
+ picked.add(id);
15112
+ }
15113
+ return {
15114
+ ids: [...picked],
15115
+ expired,
15116
+ overCap,
15117
+ keptPending
15118
+ };
15119
+ }
15120
+ /**
15121
+ * @author ddj 2026-11-24
15122
+ * @description: 截断撤销栈与幂等表:每个条目只留最近若干步,避免这两张表跟着天长日久。
15123
+ * @param db 工作区归档库连接
15124
+ * @param keepHistory 每条目保留步数
15125
+ * @returns 删除的历史行数
15126
+ */
15127
+ function trimPendingTables(db, keepHistory) {
15128
+ const trimmed = db.prepare(`DELETE FROM pending_history WHERE id NOT IN (
15129
+ SELECT id FROM (
15130
+ SELECT id, ROW_NUMBER() OVER (PARTITION BY entry_id ORDER BY id DESC) AS rn FROM pending_history
15131
+ ) WHERE rn <= ?)`).run(keepHistory);
15132
+ db.prepare(`DELETE FROM pending_ops WHERE rowid NOT IN (
15133
+ SELECT rowid FROM pending_ops ORDER BY rowid DESC LIMIT ?)`).run(500);
15134
+ return Number(trimmed.changes);
15135
+ }
15136
+ /**
15137
+ * @author ddj 2026-11-24
15138
+ * @description: 真删:单事务内按「撤销意图 → 记录 → 批次」顺序清,备份在事务之前做。
15139
+ * @param db 工作区归档库连接
15140
+ * @param ids 候选批次 id
15141
+ * @returns 删除的记录数与批次数
15142
+ */
15143
+ function removeBatches(db, ids) {
15144
+ const callIds = db.prepare("SELECT call_id FROM records WHERE batch_id = ?");
15145
+ const dropIntent = db.prepare("DELETE FROM revert_intents WHERE call_id = ?");
15146
+ const dropRecords = db.prepare("DELETE FROM records WHERE batch_id = ?");
15147
+ const dropBatch = db.prepare("DELETE FROM batches WHERE id = ?");
15148
+ let records = 0;
15149
+ let batches = 0;
15150
+ db.exec("BEGIN IMMEDIATE");
15151
+ try {
15152
+ for (const id of ids) {
15153
+ for (const row of callIds.all(id)) dropIntent.run(String(row.call_id));
15154
+ records += Number(dropRecords.run(id).changes);
15155
+ batches += Number(dropBatch.run(id).changes);
15156
+ }
15157
+ db.exec("COMMIT");
15158
+ } catch (error) {
15159
+ if (db.isTransaction) db.exec("ROLLBACK");
15160
+ throw error;
15161
+ }
15162
+ return {
15163
+ records,
15164
+ batches
15165
+ };
15166
+ }
15167
+ /**
15168
+ * @public
15169
+ * @author ddj 2026-11-24
15170
+ * @description: 归档库清理入口:保留期 + 每文件上限 + 撤销栈截断,可选 VACUUM。
15171
+ * @param cwd 工作区
15172
+ * @param options 清理选项
15173
+ * @returns 三个统计口径与实际删除行数
15174
+ * @throws 归档库不可用或事务失败
15175
+ */
15176
+ function purgeArchiveDb(cwd, options = {}) {
15177
+ const db = dbFor(cwd);
15178
+ const { ids, expired, overCap, keptPending } = pickCandidates(db, options);
15179
+ const dryRun = options.dryRun !== false;
15180
+ const keepHistory = options.keepHistory ?? 10;
15181
+ if (dryRun) return {
15182
+ expired,
15183
+ overCap,
15184
+ keptPending,
15185
+ removed: {
15186
+ records: 0,
15187
+ batches: 0,
15188
+ history: 0
15189
+ }
15190
+ };
15191
+ if (ids.length) backupBeforePurge(db, cwd);
15192
+ const removedBatches = removeBatches(db, ids);
15193
+ const history = activeReady(cwd) ? trimPendingTables(db, keepHistory) : 0;
15194
+ const outcome = {
15195
+ expired,
15196
+ overCap,
15197
+ keptPending,
15198
+ removed: {
15199
+ ...removedBatches,
15200
+ history
15201
+ }
15202
+ };
15203
+ if (options.vacuum !== false && (removedBatches.batches || history)) outcome.vacuumMs = vacuumOf(db);
15204
+ return outcome;
15205
+ }
15206
+ /**
15207
+ * @private
15208
+ * @author ddj 2026-11-24
15209
+ * @description: 回收已删行占用的页;失败只记日志,不影响已完成的删除。
15210
+ * @param db 工作区归档库连接
15211
+ * @returns 耗时毫秒
15212
+ */
15213
+ function vacuumOf(db) {
15214
+ const started = Date.now();
15215
+ try {
15216
+ db.exec("VACUUM");
15217
+ } catch (error) {
15218
+ log.warn("归档库 VACUUM 失败:" + String(error));
15219
+ }
15220
+ return Date.now() - started;
15221
+ }
15222
+ /**
15223
+ * @private
15224
+ * @author ddj 2026-11-24
15225
+ * @description: 真删前留一份备份;同名覆盖,每个工作区只占一份。
15226
+ * @param db 工作区归档库连接
15227
+ * @param cwd 工作区
15228
+ * @returns 无
15229
+ */
15230
+ function backupBeforePurge(db, cwd) {
15231
+ const target = archiveDbFile(cwd) + BACKUP_SUFFIX;
15232
+ try {
15233
+ rmSync(target, { force: true });
15234
+ db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
15235
+ } catch (error) {
15236
+ log.warn("归档库清理前备份失败(继续执行):" + String(error));
15237
+ }
15238
+ }
15239
+ /**
15240
+ * @public
15241
+ * @author ddj 2026-11-24
15242
+ * @description: 列出本机所有归档库对应的工作区:读每个库里的 metadata.cwd,
15243
+ * 不依赖有没有活跃会话。读不出来的库跳过并记日志。
15244
+ * @param home DSH home
15245
+ * @returns 工作区绝对路径清单
15246
+ */
15247
+ function listArchiveWorkspaces(home = dshHome()) {
15248
+ let names = [];
15249
+ try {
15250
+ names = readdirSync(join(home, PLUGIN_ID, "data", "archive")).filter((name) => name.endsWith(".sqlite"));
15251
+ } catch {
15252
+ return [];
15253
+ }
15254
+ const found = [];
15255
+ for (const name of names) {
15256
+ const file = join(home, PLUGIN_ID, "data", "archive", name);
15257
+ let db;
15258
+ try {
15259
+ db = new DatabaseSync(file, { readOnly: true });
15260
+ const row = db.prepare("SELECT value FROM metadata WHERE name='cwd'").get();
15261
+ if (row?.value) found.push(String(row.value));
15262
+ } catch (error) {
15263
+ log.debug("跳过不可读归档库:" + file + " " + String(error));
15264
+ } finally {
15265
+ try {
15266
+ db?.close();
15267
+ } catch {}
15268
+ }
15269
+ }
15270
+ return found;
15271
+ }
15272
+ /**
15273
+ * @public
15274
+ * @author ddj 2026-11-24
15275
+ * @description: 对所有工作区归档库跑一遍清理;单个库失败只记日志,不影响其他库。
15276
+ * @param options 扫描选项
15277
+ * @returns 扫描到的库数与删除的行数合计
15278
+ */
15279
+ function sweepArchives(options = {}) {
15280
+ const run = options.run ?? purgeArchiveDb;
15281
+ const workspaces = listArchiveWorkspaces(options.home);
15282
+ let removed = 0;
15283
+ for (const cwd of workspaces) try {
15284
+ const outcome = run(cwd, { dryRun: false });
15285
+ removed += outcome.removed.batches + outcome.removed.history;
15286
+ if (outcome.removed.batches || outcome.removed.history) log.debug(`归档库清理:${cwd} 批次 ${outcome.removed.batches},历史 ${outcome.removed.history},VACUUM ${outcome.vacuumMs ?? 0}ms`);
15287
+ } catch (error) {
15288
+ log.debug("归档库清理跳过:" + cwd + " " + String(error));
15289
+ }
15290
+ return {
15291
+ workspaces: workspaces.length,
15292
+ removed
15293
+ };
15294
+ }
15295
+ /**
15296
+ * @public
15297
+ * @author ddj 2026-11-24
15298
+ * @description: 每日自动清理:启动后延迟跑一次,之后每 24 小时一次;返回可释放的句柄。
15299
+ * @param options 扫描选项
15300
+ * @returns 可释放句柄
15301
+ */
15302
+ function startArchiveSweep(options = {}) {
15303
+ let stopped = false;
15304
+ const run = () => {
15305
+ if (stopped) return;
15306
+ try {
15307
+ sweepArchives(options);
15308
+ } catch (error) {
15309
+ log.warn("归档库每日清理失败:" + String(error));
15310
+ }
15311
+ };
15312
+ const first = setTimeout(run, options.delayMs ?? 9e4);
15313
+ const timer = setInterval(run, options.intervalMs ?? 864e5);
15314
+ if (typeof first.unref === "function") first.unref();
15315
+ if (typeof timer.unref === "function") timer.unref();
15316
+ return { dispose() {
15317
+ stopped = true;
15318
+ clearTimeout(first);
15319
+ clearInterval(timer);
15320
+ } };
15321
+ }
13635
15322
  //#endregion
13636
15323
  //#region src/revert.ts
13637
15324
  /**
@@ -18910,6 +20597,12 @@ function readHandlers(kit) {
18910
20597
  ok: false,
18911
20598
  error: "待审条目不存在"
18912
20599
  };
20600
+ },
20601
+ "edrv.pending.version": async (args) => {
20602
+ return {
20603
+ ok: true,
20604
+ version: pendingVersion(await kit.read(args.sessionId))
20605
+ };
18913
20606
  }
18914
20607
  };
18915
20608
  }
@@ -19050,6 +20743,50 @@ function refreshHandlers(kit) {
19050
20743
  ok: true,
19051
20744
  item: itemOf(next ?? stored)
19052
20745
  };
20746
+ },
20747
+ "edrv.pending.align": async (args) => {
20748
+ const cwd = await kit.write(args.sessionId);
20749
+ const outcome = await alignInWorkspace(kit.ctx, cwd, args.sessionId, (write) => {
20750
+ try {
20751
+ trackPendingCover(write.cwd, write.path, true, write.sessionId);
20752
+ } catch {}
20753
+ recordWrite(write);
20754
+ });
20755
+ const page = loadPage(cwd, args.sessionId);
20756
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path));
20757
+ return {
20758
+ ok: true,
20759
+ imported: outcome.imported,
20760
+ changed: outcome.changed,
20761
+ gaps: outcome.gaps
20762
+ };
20763
+ },
20764
+ /**
20765
+ * @author ddj 2026-11-24
20766
+ * @description: 清掉指定通道的幽灵记录。dryRun 只报数;真删后按需 VACUUM,
20767
+ * 并重建「待审接管」集合,避免旧路径继续顶掉官方行。
20768
+ * @param args 清理请求
20769
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
20770
+ */
20771
+ "edrv.pending.purge": async (args) => {
20772
+ const cwd = await kit.write(args.sessionId);
20773
+ const outcome = purgePending(cwd, {
20774
+ sources: args.sources,
20775
+ baseKinds: args.baseKinds,
20776
+ before: args.before
20777
+ }, {
20778
+ dryRun: args.dryRun === true,
20779
+ vacuum: true
20780
+ });
20781
+ const page = loadPage(cwd, args.sessionId);
20782
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path));
20783
+ return {
20784
+ ok: true,
20785
+ matched: outcome.matched,
20786
+ removed: outcome.removed,
20787
+ kept: outcome.kept,
20788
+ vacuumMs: outcome.vacuumMs
20789
+ };
19053
20790
  }
19054
20791
  };
19055
20792
  }
@@ -20688,8 +22425,9 @@ function isStaleVersion(error) {
20688
22425
  * @param sc requireSession 成功结果(session + cwd)
20689
22426
  * @param path 保存的文件路径
20690
22427
  */
20691
- async function afterManualSave(ctx, registry, sc, path) {
22428
+ async function afterManualSave(ctx, registry, sc, path, identity) {
20692
22429
  invalidateIndex(ctx, sc.cwd, path);
22430
+ windows.markEditor(pathKeyOf(identity ?? path));
20693
22431
  }
20694
22432
  /**
20695
22433
  * 批量决策核心:一次会话/桶解析 + 逐项处理 + 统一落盘(accept/reject 单条与 decideBatch 共用)。
@@ -21611,7 +23349,7 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
21611
23349
  version: rev
21612
23350
  } : void 0;
21613
23351
  const outcome = await fs.writeText(target, args.content, intent, void 0, policyOf(ctx, sc.session));
21614
- await afterManualSave(ctx, registry, sc, args.path);
23352
+ await afterManualSave(ctx, registry, sc, args.path, fs.processPath(target));
21615
23353
  return {
21616
23354
  ok: true,
21617
23355
  rev: outcome?.version ? String(outcome.version) : rev ?? void 0
@@ -21666,7 +23404,7 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
21666
23404
  error: "内容过大(>32MB),拒绝写回"
21667
23405
  };
21668
23406
  await writeFile(fs.processPath(target), bytes);
21669
- await afterManualSave(ctx, registry, sc, args.path);
23407
+ await afterManualSave(ctx, registry, sc, args.path, fs.processPath(target));
21670
23408
  return { ok: true };
21671
23409
  } catch (error) {
21672
23410
  return {
@@ -21697,6 +23435,36 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
21697
23435
  };
21698
23436
  }
21699
23437
  },
23438
+ /**
23439
+ * @author ddj 2026-11-24
23440
+ * @description: 归档库清理:保留期 + 每文件上限 + 撤销栈截断。缺省 dryRun,显式传 false 才删。
23441
+ * @param args 清理参数
23442
+ * @returns 三个统计口径与删除行数
23443
+ */
23444
+ "edrv.archive.purge": async (args) => {
23445
+ const sc = await resolveScope(ctx, args.sessionId);
23446
+ if ("err" in sc) return {
23447
+ ok: false,
23448
+ error: sc.err
23449
+ };
23450
+ try {
23451
+ return {
23452
+ ok: true,
23453
+ ...purgeArchiveDb(sc.cwd, {
23454
+ dryRun: args.dryRun !== false,
23455
+ retentionDays: args.retentionDays,
23456
+ keepBatches: args.keepBatches,
23457
+ keepHistory: args.keepHistory,
23458
+ vacuum: args.vacuum
23459
+ })
23460
+ };
23461
+ } catch (error) {
23462
+ return {
23463
+ ok: false,
23464
+ error: "归档清理失败:" + String(error)
23465
+ };
23466
+ }
23467
+ },
21700
23468
  "edrv.archivePage": async (args) => {
21701
23469
  const sc = await resolveScope(ctx, args.sessionId);
21702
23470
  if ("err" in sc) return {
@@ -35961,7 +37729,8 @@ function createRuntime(ctx, config) {
35961
37729
  settings
35962
37730
  }),
35963
37731
  dapRpc: createDapRpc(ctx),
35964
- fileVersions: createFileVersions(ctx)
37732
+ fileVersions: createFileVersions(ctx),
37733
+ settings
35965
37734
  };
35966
37735
  }
35967
37736
  /**
@@ -35976,7 +37745,8 @@ function attachRuntime(ctx, runtime) {
35976
37745
  evidence.persist(cwd, snapshot);
35977
37746
  return true;
35978
37747
  });
35979
- const pending = installPending(ctx, (write) => {
37748
+ /** @author ddj 2026年11月24号 @param write 已确认的一次写入 @returns 无;落库失败不打断用户工具调用 */
37749
+ function recordPendingWrite(write) {
35980
37750
  try {
35981
37751
  trackPendingCover(write.cwd, write.path, true, write.sessionId);
35982
37752
  } catch {}
@@ -35985,7 +37755,37 @@ function attachRuntime(ctx, runtime) {
35985
37755
  } catch (error) {
35986
37756
  log.warn("待审差异落库失败:" + String(error));
35987
37757
  }
37758
+ }
37759
+ const pending = installPending(ctx, recordPendingWrite);
37760
+ const external = installExternalCapture({
37761
+ ctx,
37762
+ settings: () => runtime.settings.external(),
37763
+ record: recordPendingWrite
35988
37764
  });
37765
+ const sweep = startArchiveSweep();
37766
+ /**
37767
+ * @author ddj 2026年11月24号
37768
+ * @description: 任一工具调用期间都是 agent 写入窗口:bash / python 写盘落在窗口内时归属 agent。
37769
+ * 版本库写工具结束后再补扫一次,把命令造成的成片变化对齐进待审投影。
37770
+ * @param exec 工具执行描述
37771
+ * @param next 原始分发
37772
+ * @returns 原始结果
37773
+ */
37774
+ function aroundToolWindow(exec, next) {
37775
+ windows.enterTool();
37776
+ return Promise.resolve().then(next).finally(() => {
37777
+ windows.exitTool();
37778
+ if (!VCS_WRITE_TOOLS.has(String(exec.name ?? ""))) return;
37779
+ const cwd = cwdOfSession(ctx, exec.agent?.session);
37780
+ if (cwd) external.requestAlign(cwd);
37781
+ });
37782
+ }
37783
+ /** @author ddj 2026年11月24号 @param session 新建会话 @returns 无;工作区可用即开始监听 */
37784
+ function onCreated(session) {
37785
+ if (typeof session.id !== "string") return;
37786
+ const cwd = cwdOfSession(ctx, session);
37787
+ if (cwd) external.ensure(cwd, session.id);
37788
+ }
35989
37789
  /** @author ddj 2026年09月28号 @param exec Tool execution. @param result Tool result. */
35990
37790
  function onResult(exec, result) {
35991
37791
  captureToolResult(ctx, runtime.registry, exec, result);
@@ -35994,6 +37794,7 @@ function attachRuntime(ctx, runtime) {
35994
37794
  function onDisposed(session) {
35995
37795
  const cwd = cwdOf(session);
35996
37796
  if (cwd) {
37797
+ external.dismiss(cwd);
35997
37798
  runtime.registry.delete(cwd);
35998
37799
  runtime.searcher.dispose(cwd);
35999
37800
  runtime.contentSearcher.dispose(cwd);
@@ -36006,6 +37807,9 @@ function attachRuntime(ctx, runtime) {
36006
37807
  await stopCapture();
36007
37808
  evidence.dispose();
36008
37809
  pending.dispose();
37810
+ external.dispose();
37811
+ sweep.dispose();
37812
+ windows.dispose();
36009
37813
  runtime.fileVersions.dispose();
36010
37814
  closeArchiveDbs();
36011
37815
  disposeAllServers();
@@ -36016,9 +37820,13 @@ function attachRuntime(ctx, runtime) {
36016
37820
  ].map((run) => Promise.resolve().then(run)));
36017
37821
  }
36018
37822
  ctx.on("tools/result", onResult);
37823
+ ctx.on("tools/execute", aroundToolWindow);
37824
+ ctx.on("session/created", onCreated);
36019
37825
  ctx.on("session/disposed", onDisposed);
37826
+ for (const session of ctx.get("sessions").list()) onCreated(session);
36020
37827
  ctx.effect(() => cleanup, "vscode-mode:runtime");
36021
37828
  hookExitReclaim();
37829
+ return { external };
36022
37830
  }
36023
37831
  /**
36024
37832
  * Add user rules and bundled skills without requiring them on older Hosts.
@@ -36041,12 +37849,35 @@ async function apply(ctx, config) {
36041
37849
  bindHostLog(ctx);
36042
37850
  const runtime = createRuntime(ctx, config);
36043
37851
  const warnings = [];
36044
- attachRuntime(ctx, runtime);
37852
+ const capture = attachRuntime(ctx, runtime);
36045
37853
  installContent(ctx);
37854
+ /** 版本库写操作后的补扫串行链:并发 RPC 也不会叠出多次补扫。 */
37855
+ let alignChain = Promise.resolve();
36046
37856
  /** @author ddj 2026年09月28号 @param method RPC name. @param args Typed request. @returns RPC result. */
36047
37857
  function dispatch(method, args) {
36048
37858
  const { registry, searcher, contentSearcher, lspRpc, aiRpc, fileVersions, svnRpc, dapRpc } = runtime;
36049
- return handleRpc(ctx, registry, method, args, searcher, contentSearcher, lspRpc.handlers, aiRpc.handlers, fileVersions, svnRpc.handlers, dapRpc.handlers);
37859
+ const pendingResult = handleRpc(ctx, registry, method, args, searcher, contentSearcher, lspRpc.handlers, aiRpc.handlers, fileVersions, svnRpc.handlers, dapRpc.handlers);
37860
+ if (!VCS_WRITE_METHODS.has(method)) return pendingResult;
37861
+ alignChain = alignChain.then(async () => {
37862
+ const cwd = await workspaceOfSession(args?.sessionId);
37863
+ if (cwd) capture.external.requestAlign(cwd);
37864
+ }).catch(() => {});
37865
+ return pendingResult;
37866
+ }
37867
+ /**
37868
+ * @author ddj 2026年11月24号
37869
+ * @description: 取 RPC 参数里的会话工作区;取不到就跳过补扫,绝不影响 RPC 本身。
37870
+ * @param sessionId 请求会话
37871
+ * @returns 工作区路径或 null
37872
+ */
37873
+ async function workspaceOfSession(sessionId) {
37874
+ try {
37875
+ if (!sessionId) return null;
37876
+ const scope = await resolveScope(ctx, sessionId);
37877
+ return "err" in scope ? null : scope.cwd;
37878
+ } catch {
37879
+ return null;
37880
+ }
36050
37881
  }
36051
37882
  /** @author ddj 2026年09月28号 @param warning Startup compatibility diagnostic. */
36052
37883
  function noteWarning(warning) {