dsh-vscode-mode 0.35.0 → 0.36.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.
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,6 +3822,7 @@ 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");
@@ -4202,6 +4482,7 @@ var McpRuntime = class {
4202
4482
  if (!def.enabled || record.holds.has(name) || !path) continue;
4203
4483
  record.holds.set(name, managed.hold(path, name));
4204
4484
  }
4485
+ record.finishedAt ??= Date.now();
4205
4486
  this.changed();
4206
4487
  }
4207
4488
  /** @private @author ddj 2026年10月20号 @param agent Owner. @param record Scope record. Updates lazy resources and schedules explicit background services. */
@@ -4435,14 +4716,11 @@ var McpRuntime = class {
4435
4716
  }
4436
4717
  /** @private @author ddj 2026年10月20号 @param agent Owner. @param record Ledger. @returns Server phases with caller-local timing, not pooled connection age. */
4437
4718
  sessionServers(agent, record) {
4719
+ const managed = this.probeBackend() === "manager" ? this.managedOf() : void 0;
4720
+ const path = managed ? this.workspace(agent) ?? "" : "";
4438
4721
  return this.catalogue(agent).map(({ serverName, phase }) => {
4439
4722
  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
- };
4723
+ if (!instance) return this.managedServer(record, serverName, phase, managed?.stateOf(path, serverName));
4446
4724
  const entry = instance.lease.entry;
4447
4725
  return {
4448
4726
  serverName,
@@ -4458,6 +4736,30 @@ var McpRuntime = class {
4458
4736
  };
4459
4737
  });
4460
4738
  }
4739
+ /**
4740
+ * 托管后端的一条服务器状态:阶段取 catalogue 的官方映射,时间取挂载时刻与官方连上时刻。
4741
+ * @private @author ddj 2026年11月24号
4742
+ * @param record 会话账目
4743
+ * @param serverName 服务器名
4744
+ * @param phase 官方状态映射后的阶段
4745
+ * @param state 官方托管状态;连接池后端不传
4746
+ * @returns 会话里的一条服务器状态
4747
+ */
4748
+ managedServer(record, serverName, phase, state) {
4749
+ const startedAt = state?.since ?? record.finishedAt ?? record.startedAt;
4750
+ let finishedAt;
4751
+ if (phase === "ready") finishedAt = state?.connectedAt ?? startedAt;
4752
+ else if (phase === "error") finishedAt = startedAt;
4753
+ const server = {
4754
+ serverName,
4755
+ phase,
4756
+ startedAt,
4757
+ phaseAt: finishedAt ?? startedAt,
4758
+ finishedAt
4759
+ };
4760
+ if (state?.error) server.error = state.error;
4761
+ return server;
4762
+ }
4461
4763
  /** @public @author ddj 2026年09月28号 @param path Workspace. @returns Masked configuration and pool/lease counts; initialization is not health. */
4462
4764
  views(path) {
4463
4765
  if (this.probeBackend() === "manager") return this.viewsManaged(path);
@@ -4558,6 +4860,13 @@ async function clearLegacy(ctx) {
4558
4860
  function leftoverOf(ctx) {
4559
4861
  return entriesOf(ctx).filter((entry) => isProjectEntryId(String(entry.id ?? entry.options?.id ?? ""))).map((entry) => String(entry.id));
4560
4862
  }
4863
+ /** 官方状态里算「还在起来」的那几个:连接中、重连退避、等凭据、等授权。 */
4864
+ const STARTING_STATES = /* @__PURE__ */ new Set([
4865
+ "connecting",
4866
+ "reconnecting",
4867
+ "waiting-credentials",
4868
+ "waiting-authorization"
4869
+ ]);
4561
4870
  /**
4562
4871
  * 官方状态 → 插件阶段:未知一律 idle,不假装连上。
4563
4872
  * @private @author ddj 2026年11月23号
@@ -4566,7 +4875,7 @@ function leftoverOf(ctx) {
4566
4875
  */
4567
4876
  function managedPhase(state) {
4568
4877
  if (state === "connected") return "ready";
4569
- if (state === "connecting") return "starting";
4878
+ if (STARTING_STATES.has(state)) return "starting";
4570
4879
  if (state === "failed") return "error";
4571
4880
  return "idle";
4572
4881
  }
@@ -4580,7 +4889,7 @@ function managedPhase(state) {
4580
4889
  function managedStatusOf(enabled, state) {
4581
4890
  if (!enabled) return "disabled";
4582
4891
  if (state === "connected") return "connected";
4583
- if (state === "connecting") return "connecting";
4892
+ if (STARTING_STATES.has(state)) return "connecting";
4584
4893
  if (state === "failed") return "error";
4585
4894
  return "configured";
4586
4895
  }
@@ -6340,7 +6649,9 @@ function buildSettingsSchema(z, options) {
6340
6649
  aiCommitStyle: withVol(z.string().default("plain")),
6341
6650
  nativeOpenExts: withVol(z.string().default(DEFAULT_NATIVE_CSV)),
6342
6651
  refIntake: withVol(z.boolean().default(true)),
6343
- searchReplace: withVol(z.boolean().default(true))
6652
+ searchReplace: withVol(z.boolean().default(true)),
6653
+ externalWatch: withVol(z.boolean().default(true)),
6654
+ externalScan: withVol(z.boolean().default(true))
6344
6655
  };
6345
6656
  if (wantVolatile) configVolatile = {
6346
6657
  requested: true,
@@ -6520,6 +6831,11 @@ function setupOpenSettings(ctx, config, onChange) {
6520
6831
  };
6521
6832
  /** AI 界面设置当前值(提交信息风格 / 整理是否默认按勾选范围)。 */
6522
6833
  let aiUiCurrent = { commitStyle: commitStyleValueOf(config) };
6834
+ /** 外部改动捕获开关当前值(settings 未就绪回退配置值)。 */
6835
+ let externalCurrent = {
6836
+ watch: boolValueOf(config, "externalWatch", true),
6837
+ scan: boolValueOf(config, "externalScan", true)
6838
+ };
6523
6839
  const svnSync = (stored) => {
6524
6840
  svnCurrent = {
6525
6841
  svnPath: svnPathValueOf(stored),
@@ -6530,6 +6846,10 @@ function setupOpenSettings(ctx, config, onChange) {
6530
6846
  autoDelete: boolValueOf(stored, "svnAutoDeleteMissing", true)
6531
6847
  };
6532
6848
  aiUiCurrent = { commitStyle: commitStyleValueOf(stored) };
6849
+ externalCurrent = {
6850
+ watch: boolValueOf(stored, "externalWatch", true),
6851
+ scan: boolValueOf(stored, "externalScan", true)
6852
+ };
6533
6853
  };
6534
6854
  /** 读取 settings 存储值(describe 未就绪返回 undefined)。 */
6535
6855
  const storedValue = () => {
@@ -6544,7 +6864,9 @@ function setupOpenSettings(ctx, config, onChange) {
6544
6864
  svnAutoAddUnversioned: svnCurrent.autoAdd,
6545
6865
  svnAutoDeleteMissing: svnCurrent.autoDelete,
6546
6866
  svnReadOnly: svnCurrent.readOnly,
6547
- aiCommitStyle: aiUiCurrent.commitStyle
6867
+ aiCommitStyle: aiUiCurrent.commitStyle,
6868
+ externalWatch: externalCurrent.watch,
6869
+ externalScan: externalCurrent.scan
6548
6870
  }, {
6549
6871
  setSource: (source) => {
6550
6872
  notify(source().fileOpenTool);
@@ -6585,6 +6907,7 @@ function setupOpenSettings(ctx, config, onChange) {
6585
6907
  autoDelete: svnCurrent.autoDelete
6586
6908
  }),
6587
6909
  aiUi: () => aiUiCurrent,
6910
+ external: () => externalCurrent,
6588
6911
  aiUpdate: async (patch, expectedRevision) => {
6589
6912
  const stored = { ...aiCurrent };
6590
6913
  const body = {};
@@ -8897,6 +9220,7 @@ async function syncMirrorFile(absPath, content) {
8897
9220
  try {
8898
9221
  await mkdir(dirname(absPath), { recursive: true });
8899
9222
  await writeFile(absPath, content, "utf8");
9223
+ windows.markSelf(pathKeyOf(absPath));
8900
9224
  return null;
8901
9225
  } catch (error) {
8902
9226
  return String(error);
@@ -11459,6 +11783,23 @@ function recordGap(scope, exec, path, error) {
11459
11783
  while (captureGaps.size > 500) captureGaps.delete(captureGaps.keys().next().value);
11460
11784
  }
11461
11785
  /**
11786
+ * @public
11787
+ * @author ddj 2026-11-24
11788
+ * @description: 外部采集(watch / 补扫)的缺口上报:非文本、超大、读取失败都记进同一份列表,
11789
+ * 让面板能把「没记下来」说清楚,而不是静默丢条目。
11790
+ * @param cwd 工作区
11791
+ * @param sessionId 会话
11792
+ * @param path 出问题的路径
11793
+ * @param error 原因
11794
+ * @returns 无
11795
+ */
11796
+ function noteCaptureGap(cwd, sessionId, path, error) {
11797
+ recordGap({
11798
+ cwd,
11799
+ sessionId
11800
+ }, { id: "external" }, path, error);
11801
+ }
11802
+ /**
11462
11803
  * @author ddj 2026年10月30号
11463
11804
  * @description: 安装写文件采集;读写失败只影响待审来源,绝不影响用户工具本身。
11464
11805
  * @param ctx Host 生命周期
@@ -11491,7 +11832,7 @@ function installPending(ctx, sink, options) {
11491
11832
  * @param exec 工具分发上下文
11492
11833
  * @returns 采集计划或 null
11493
11834
  */
11494
- async function planOf(scope, state, requested) {
11835
+ async function planOf(scope, state, requested, tool) {
11495
11836
  const { cwd, sessionId, fs } = scope;
11496
11837
  if (state.stopped || state.disposed.has(sessionId)) return null;
11497
11838
  const target = await fs.resolve(requested, { cwd });
@@ -11511,7 +11852,8 @@ async function planOf(scope, state, requested) {
11511
11852
  identity,
11512
11853
  before,
11513
11854
  target,
11514
- fs
11855
+ fs,
11856
+ tool
11515
11857
  };
11516
11858
  } catch (error) {
11517
11859
  state.busy.delete(identity);
@@ -11607,9 +11949,10 @@ async function reconcileBulk(scope, exec, result, plans) {
11607
11949
  */
11608
11950
  async function buildPlans(scope, state, exec, paths) {
11609
11951
  const plans = [];
11952
+ const tool = String(exec.name ?? "");
11610
11953
  for (const path of paths) try {
11611
11954
  if (plans.length >= 16) throw new Error("capture target budget exceeded");
11612
- const plan = await planOf(scope, state, path);
11955
+ const plan = await planOf(scope, state, path, tool);
11613
11956
  if (plan) plans.push(plan);
11614
11957
  } catch (error) {
11615
11958
  if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, path, error);
@@ -11690,7 +12033,8 @@ async function reportWrite(state, sink, plan) {
11690
12033
  identity: plan.identity,
11691
12034
  before: plan.before,
11692
12035
  after,
11693
- now: Date.now()
12036
+ now: Date.now(),
12037
+ tool: plan.tool
11694
12038
  });
11695
12039
  }
11696
12040
  /**
@@ -12061,6 +12405,116 @@ async function runCommand(shell, command, workdir, stdoutMaxBytes = STDOUT_BUDGE
12061
12405
  }
12062
12406
  }
12063
12407
  /**
12408
+ * @author ddj 2026-11-24
12409
+ * @description: 只读一条状态命令,取「工作副本相对基线有改动」的路径集合。补扫用它当候选与
12410
+ * 「干净」判据:不在集合里的路径,其内容变化只能来自版本库同步,不该记成 agent 改动。
12411
+ * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
12412
+ * @param shell shell 能力
12413
+ * @param cwd 工作区
12414
+ * @returns 状态集合或 null
12415
+ */
12416
+ async function vcsStatus(shell, cwd) {
12417
+ const detected = await detectVcsRoot(cwd);
12418
+ if (!detected || detected.kind === "p4") return null;
12419
+ return detected.kind === "git" ? gitStatus(shell, detected.root) : svnStatus(shell, detected.root);
12420
+ }
12421
+ /**
12422
+ * @private
12423
+ * @author ddj 2026-11-24
12424
+ * @description: git 状态:一条 status 命令解析出改动集合。
12425
+ * @param shell shell 能力
12426
+ * @param root 仓库根
12427
+ * @returns 状态集合或 null(命令失败)
12428
+ */
12429
+ async function gitStatus(shell, root) {
12430
+ const status = await runCommand(shell, "git -c status.renames=false status --porcelain=v1 -z --untracked-files=all", root);
12431
+ if (!status.ok) return null;
12432
+ const entries = /* @__PURE__ */ new Map();
12433
+ for (const entry of parseGitStatus(status.stdout)) {
12434
+ const absolute = join(root, ...entry.path.split(GIT_SEPARATOR));
12435
+ if (!insideRoot$1(root, absolute)) continue;
12436
+ entries.set(pathKeyOf(absolute), {
12437
+ path: absolute,
12438
+ status: gitStatusOf(entry.status)
12439
+ });
12440
+ }
12441
+ return {
12442
+ kind: "git",
12443
+ root,
12444
+ entries
12445
+ };
12446
+ }
12447
+ /**
12448
+ * @private
12449
+ * @author ddj 2026-11-24
12450
+ * @description: svn 状态:一条 status --xml 解析出改动集合。
12451
+ * @param shell shell 能力
12452
+ * @param root 工作副本根
12453
+ * @returns 状态集合或 null(命令失败)
12454
+ */
12455
+ async function svnStatus(shell, root) {
12456
+ const status = await runCommand(shell, "svn status --xml", root);
12457
+ if (!status.ok) return null;
12458
+ const entries = /* @__PURE__ */ new Map();
12459
+ for (const entry of parseSvnStatus(status.stdout)) {
12460
+ const absolute = resolve(root, entry.path);
12461
+ if (!insideRoot$1(root, absolute)) continue;
12462
+ entries.set(pathKeyOf(absolute), {
12463
+ path: absolute,
12464
+ status: svnStatusOf(entry.status)
12465
+ });
12466
+ }
12467
+ return {
12468
+ kind: "svn",
12469
+ root,
12470
+ entries
12471
+ };
12472
+ }
12473
+ /**
12474
+ * @private
12475
+ * @author ddj 2026-11-24
12476
+ * @description: git 状态码归一:删除优先,其次新增/未跟踪,其余按修改。
12477
+ * @param status 两位状态码
12478
+ * @returns 归一状态
12479
+ */
12480
+ function gitStatusOf(status) {
12481
+ if (status.includes("D")) return "deleted";
12482
+ if (status === "??" || status.includes("A")) return "added";
12483
+ return "modified";
12484
+ }
12485
+ /**
12486
+ * @private
12487
+ * @author ddj 2026-11-24
12488
+ * @description: svn 条目状态归一。
12489
+ * @param status wc-status 的 item 值
12490
+ * @returns 归一状态
12491
+ */
12492
+ function svnStatusOf(status) {
12493
+ if (status === "deleted" || status === "missing") return "deleted";
12494
+ if (status === "added" || status === "unversioned" || status === "replaced") return "added";
12495
+ return "modified";
12496
+ }
12497
+ /**
12498
+ * @author ddj 2026-11-24
12499
+ * @description: 读某路径的版本库基线内容;只用于补录记录的修改前内容。
12500
+ * @param shell shell 能力
12501
+ * @param status 已探测的状态(给根目录与种类)
12502
+ * @param absolute 绝对路径
12503
+ * @returns 基线内容;读不到返回 null
12504
+ */
12505
+ async function vcsBaselineOf(shell, status, absolute) {
12506
+ const root = status.root;
12507
+ const relative = absolute.slice(root.length).replace(/^[\\/]+/, "").split(sep).join(GIT_SEPARATOR);
12508
+ if (!relative) return null;
12509
+ try {
12510
+ if (status.kind === "git") return await gitBaseline(shell, root, relative);
12511
+ const shown = await runCommand(shell, `svn cat -r BASE ${quote(absolute)}`, root);
12512
+ return shown.ok ? shown.stdout : null;
12513
+ } catch {
12514
+ return null;
12515
+ }
12516
+ }
12517
+ /**
12064
12518
  * @author ddj 2026年10月30号
12065
12519
  * @description: 读单元格文本,不存在时返回 null。
12066
12520
  * @param path 文件路径
@@ -12130,6 +12584,761 @@ function decodeXml(value) {
12130
12584
  return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&apos;/g, "'").replace(/&amp;/g, "&");
12131
12585
  }
12132
12586
  //#endregion
12587
+ //#region src/pending/externalAlign.ts
12588
+ /**
12589
+ * 外部改动补扫:拿版本库当基线,把「插件还没记录过」的工作副本改动用 `source='scan'` 补录,
12590
+ * 同时提供 watch 采集需要的两个只读能力(改动集合与基线内容)。
12591
+ *
12592
+ * 设计取舍:
12593
+ * - 候选只来自一条 `git status` / `svn status` 命令,不遍历目录树;因此 200 MB 仓库的启动对齐
12594
+ * 与定时补扫都只花「一条命令 + 少量读盘」。
12595
+ * - 不在版本库改动集合里的路径一律不建记录:内容变化只能来自版本库同步,记成 agent 改动会
12596
+ * 污染审查队列并让撤销误伤(见任务书验收 4)。
12597
+ * - 基线与读盘都有硬上限(条数、字节、截止时间),超限写 `gaps`,绝不静默截断。
12598
+ * 作者 ddj 2026-11-24
12599
+ */
12600
+ var externalAlign_exports = /* @__PURE__ */ __exportAll({
12601
+ ALIGN_BUDGET: () => ALIGN_BUDGET,
12602
+ ALIGN_FILE_MAX: () => ALIGN_FILE_MAX,
12603
+ alignExternal: () => alignExternal,
12604
+ alignInWorkspace: () => alignInWorkspace,
12605
+ vcsScopeOf: () => vcsScopeOf
12606
+ });
12607
+ /** 默认预算:大仓下也只是一条 status 命令加几十次读盘。 */
12608
+ const ALIGN_BUDGET = {
12609
+ paths: 2e3,
12610
+ bytes: 16 << 20,
12611
+ deadlineMs: 5e3,
12612
+ baselines: 32
12613
+ };
12614
+ /** 单文件读取上限:与待审采集一致,超出只标 oversized 不读全文。 */
12615
+ const ALIGN_FILE_MAX = 1048576;
12616
+ /**
12617
+ * @author ddj 2026-11-24
12618
+ * @description: 取本会话可用的版本库能力;没有 shell 服务或会话不存在时返回 null。
12619
+ * @param ctx Host 上下文
12620
+ * @param cwd 工作区
12621
+ * @param sessionId 会话
12622
+ * @returns 作用域或 null
12623
+ */
12624
+ function vcsScopeOf(ctx, cwd, sessionId) {
12625
+ const raw = ctx.get("shell");
12626
+ if (!raw || typeof raw.resolve !== "function") return null;
12627
+ const policy = policyOf(ctx, sessionOf(ctx, sessionId));
12628
+ return {
12629
+ cwd: String(cwd),
12630
+ sessionId,
12631
+ shell: {
12632
+ resolve: (request) => raw.resolve(policy ? {
12633
+ ...request,
12634
+ sandboxPolicy: policy
12635
+ } : request),
12636
+ execute: (spec) => raw.execute(spec)
12637
+ }
12638
+ };
12639
+ }
12640
+ /**
12641
+ * @author ddj 2026-11-24
12642
+ * @description: 一次补扫:版本库候选 → 逐条对比已知内容 → 未记录的补录(source='scan')。
12643
+ * 无版本库或状态命令不可用时降级为「只对齐已记录条目」,并把原因写进 gaps。
12644
+ * @param scope 版本库作用域(可为空:无 shell 时走降级)
12645
+ * @param deps 读盘与落库能力
12646
+ * @param budget 预算
12647
+ * @returns 结果
12648
+ */
12649
+ async function alignExternal(scope, deps, budget = ALIGN_BUDGET) {
12650
+ const started = Date.now();
12651
+ const now = deps.now ?? Date.now;
12652
+ const gaps = [];
12653
+ const known = deps.entries();
12654
+ const status = scope ? await vcsStatus(scope.shell, scope.cwd) : null;
12655
+ if (!status) {
12656
+ const reason = scope ? "版本库状态不可用(非 git/svn 或命令失败):补扫只对齐已记录条目" : "当前环境没有 shell 能力:补扫只对齐已记录条目";
12657
+ gaps.push(reason);
12658
+ return {
12659
+ imported: await reconcileKnown(scope, deps, known, budget, started, now, gaps),
12660
+ changed: 0,
12661
+ gaps
12662
+ };
12663
+ }
12664
+ const candidates = [...status.entries];
12665
+ if (candidates.length > budget.paths) gaps.push(`版本库报告 ${candidates.length} 个改动,本次只处理前 ${budget.paths} 个`);
12666
+ let imported = 0;
12667
+ let bytes = 0;
12668
+ let baselines = 0;
12669
+ for (const [key, entry] of candidates.slice(0, budget.paths)) {
12670
+ if (Date.now() - started > budget.deadlineMs) {
12671
+ gaps.push(`补扫超过 ${budget.deadlineMs}ms,剩余改动留到下一轮`);
12672
+ break;
12673
+ }
12674
+ const stored = known.get(key);
12675
+ const absolute = entry.path;
12676
+ try {
12677
+ if (entry.status === "deleted") {
12678
+ if (stored && stored.flags.missing) continue;
12679
+ deps.record(writeOf(scope, absolute, stored ? stored.entry.newText : null, null, now(), "external", stored ? "known" : "unknown"));
12680
+ imported += 1;
12681
+ continue;
12682
+ }
12683
+ const content = await deps.read(absolute);
12684
+ if (content === null) continue;
12685
+ if (content.length > 1048576) {
12686
+ gaps.push(absolute + ": 超过单文件上限,未补扫");
12687
+ continue;
12688
+ }
12689
+ if (stored && stored.entry.newText === content) continue;
12690
+ if (bytes + content.length > budget.bytes) {
12691
+ gaps.push(absolute + ": 补扫读取预算已用尽,未补扫");
12692
+ continue;
12693
+ }
12694
+ bytes += content.length;
12695
+ if (stored) {
12696
+ deps.record(writeOf(scope, absolute, stored.entry.newText, content, now(), "external", "known"));
12697
+ imported += 1;
12698
+ continue;
12699
+ }
12700
+ if (entry.status === "added") {
12701
+ deps.record(writeOf(scope, absolute, null, content, now(), "external", "absent"));
12702
+ imported += 1;
12703
+ continue;
12704
+ }
12705
+ let base = null;
12706
+ if (baselines < budget.baselines) {
12707
+ baselines += 1;
12708
+ base = await vcsBaselineOf(scope.shell, status, absolute);
12709
+ } else gaps.push(absolute + ": 基线读取预算已用尽,记为基线未知");
12710
+ deps.record(writeOf(scope, absolute, base, content, now(), "external", base === null ? "unknown" : "vcs"));
12711
+ imported += 1;
12712
+ } catch (error) {
12713
+ gaps.push(absolute + ": " + String(error));
12714
+ }
12715
+ }
12716
+ return {
12717
+ imported,
12718
+ changed: candidates.length,
12719
+ gaps
12720
+ };
12721
+ }
12722
+ /**
12723
+ * @private
12724
+ * @author ddj 2026-11-24
12725
+ * @description: 降级路径:只把已记录条目与磁盘对齐(条目数很小,不会遍历仓库)。
12726
+ * @param scope 版本库作用域
12727
+ * @param deps 读盘与落库能力
12728
+ * @param known 已落库条目
12729
+ * @param budget 预算
12730
+ * @param started 起始时间
12731
+ * @param now 时钟
12732
+ * @param gaps 缺口输出
12733
+ * @returns 无
12734
+ */
12735
+ async function reconcileKnown(scope, deps, known, budget, started, now, gaps) {
12736
+ let bytes = 0;
12737
+ let imported = 0;
12738
+ for (const stored of known.values()) {
12739
+ if (Date.now() - started > budget.deadlineMs) {
12740
+ gaps.push("降级补扫超过截止时间,剩余条目留到下一轮");
12741
+ break;
12742
+ }
12743
+ try {
12744
+ const content = await deps.read(stored.entry.id);
12745
+ if (content === null) {
12746
+ if (stored.flags.missing) continue;
12747
+ deps.record(writeOf(scope, stored.entry.path, stored.entry.newText, null, now(), "external", "known"));
12748
+ imported += 1;
12749
+ continue;
12750
+ }
12751
+ if (content === stored.entry.newText) continue;
12752
+ if (bytes + content.length > budget.bytes) {
12753
+ gaps.push(stored.entry.path + ": 补扫读取预算已用尽,未补扫");
12754
+ break;
12755
+ }
12756
+ bytes += content.length;
12757
+ deps.record(writeOf(scope, stored.entry.path, stored.entry.newText, content, now(), "external", "known"));
12758
+ imported += 1;
12759
+ } catch (error) {
12760
+ gaps.push(stored.entry.path + ": " + String(error));
12761
+ }
12762
+ }
12763
+ return imported;
12764
+ }
12765
+ /**
12766
+ * @private
12767
+ * @author ddj 2026-11-24
12768
+ * @description: 组装一条待审写入;补扫只产出 `source='scan'` 的记录。
12769
+ * @param scope 版本库作用域
12770
+ * @param absolute 绝对路径
12771
+ * @param before 修改前内容(null = 当时不存在或未知,由 baseKind 区分)
12772
+ * @param after 当前内容(null = 已删除)
12773
+ * @param at 时间
12774
+ * @param origin 归属
12775
+ * @param baseKind 基线可信度
12776
+ * @returns 待审写入
12777
+ */
12778
+ function writeOf(scope, absolute, before, after, at, origin, baseKind) {
12779
+ return {
12780
+ cwd: scope?.cwd ?? "",
12781
+ sessionId: scope?.sessionId ?? "",
12782
+ path: absolute,
12783
+ identity: absolute,
12784
+ before,
12785
+ after,
12786
+ now: at,
12787
+ tool: "scan",
12788
+ origin,
12789
+ baseKind
12790
+ };
12791
+ }
12792
+ /**
12793
+ * @author ddj 2026-11-24
12794
+ * @description: 用 Host 能力跑一次补扫:版本库候选 + 待审库条目 + ctx.fs 读盘。
12795
+ * @param ctx Host 上下文
12796
+ * @param cwd 工作区
12797
+ * @param sessionId 会话
12798
+ * @param record 落库回调(复用待审采集 sink)
12799
+ * @param budget 预算
12800
+ * @returns 结果
12801
+ */
12802
+ async function alignInWorkspace(ctx, cwd, sessionId, record, budget = ALIGN_BUDGET) {
12803
+ const fs = ctx.get("fs");
12804
+ if (!fs) return {
12805
+ imported: 0,
12806
+ changed: 0,
12807
+ gaps: ["缺少 fs 服务:补扫未执行"]
12808
+ };
12809
+ const entries = /* @__PURE__ */ new Map();
12810
+ for (const stored of loadEntries(cwd)) entries.set(pathKeyOf(stored.entry.id), stored);
12811
+ const deps = {
12812
+ read: async (absolute) => {
12813
+ try {
12814
+ const target = await fs.resolve(absolute, { cwd });
12815
+ return await readText$1(fs, target);
12816
+ } catch (error) {
12817
+ noteCaptureGap(cwd, sessionId, absolute, error);
12818
+ throw error;
12819
+ }
12820
+ },
12821
+ record,
12822
+ entries: () => entries
12823
+ };
12824
+ try {
12825
+ const outcome = await alignExternal(vcsScopeOf(ctx, cwd, sessionId), deps, budget);
12826
+ for (const gap of outcome.gaps) log.debug("补扫:" + gap);
12827
+ return outcome;
12828
+ } catch (error) {
12829
+ log.warn("补扫失败:" + String(error));
12830
+ return {
12831
+ imported: 0,
12832
+ changed: 0,
12833
+ gaps: ["补扫失败:" + String(error)]
12834
+ };
12835
+ }
12836
+ }
12837
+ /** 保存风暴的封顶:从首个事件算起最多等这么久就开跑。 */
12838
+ const MAX_WAIT_MS$1 = 2e3;
12839
+ /** 内存基线表上限(路径比较键数)。 */
12840
+ const SEEN_MAX = 5e3;
12841
+ /** 定时补扫间隔。 */
12842
+ const ALIGN_INTERVAL_MS = 6e5;
12843
+ /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
12844
+ const ALIGN_AFTER_VCS_MS = 1500;
12845
+ /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
12846
+ const VCS_WRITE_METHODS = /* @__PURE__ */ new Set([
12847
+ "svn.revert",
12848
+ "svn.resolve",
12849
+ "svn.add",
12850
+ "svn.cleanup",
12851
+ "svn.update",
12852
+ "svn.ignore",
12853
+ "svn.commit"
12854
+ ]);
12855
+ /** 会改动工作副本的版本库工具名。 */
12856
+ const VCS_WRITE_TOOLS = /* @__PURE__ */ new Set([
12857
+ "svn_add",
12858
+ "svn_delete",
12859
+ "svn_revert",
12860
+ "svn_commit",
12861
+ "svn_update",
12862
+ "svn_resolve",
12863
+ "svn_cleanup",
12864
+ "svn_propset",
12865
+ "svn_propdel",
12866
+ "svn_changelist",
12867
+ "remote_ssh_write"
12868
+ ]);
12869
+ /** 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。 */
12870
+ const EXTRA_IGNORE_SEGMENTS = [
12871
+ ".svn",
12872
+ ".hg",
12873
+ ".p4config",
12874
+ "Library",
12875
+ "Temp",
12876
+ "obj",
12877
+ "Logs"
12878
+ ];
12879
+ /** 忽略集合:目录段 + 文件名模式。 */
12880
+ const IGNORE_SEGMENTS = /* @__PURE__ */ new Set([...EXCLUDES, ...EXTRA_IGNORE_SEGMENTS]);
12881
+ /** 忽略文件名(glob 只有这几条,直接判后缀/全名,不引第三方匹配器)。 */
12882
+ const IGNORE_FILES = new Set(FILE_EXCLUDES.map((pattern) => pattern.replace(/^\*\*\//, "")));
12883
+ /**
12884
+ * @public
12885
+ * @author ddj 2026-11-24
12886
+ * @description: 判断绝对路径是否不进记录:工作区外、忽略目录段、插件自身 sidecar、构建产物、`.map`、
12887
+ * 以及计划页打包临时目录 `plans/<slug>/runtime/`。
12888
+ * @param cwd 工作区根
12889
+ * @param absolute 绝对路径
12890
+ * @returns 忽略返回 true
12891
+ */
12892
+ function isIgnoredPath(cwd, absolute) {
12893
+ const root = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
12894
+ const unified = absolute.replace(/\\/g, "/");
12895
+ if (root && !(unified === root || unified.toLowerCase().startsWith(root.toLowerCase() + "/"))) return true;
12896
+ const segments = (root && unified.length > root.length ? unified.slice(root.length + 1) : unified).split("/").filter(Boolean);
12897
+ if (!segments.length) return true;
12898
+ for (const segment of segments.slice(0, -1)) if (IGNORE_SEGMENTS.has(segment)) return true;
12899
+ const name = segments[segments.length - 1];
12900
+ if (IGNORE_SEGMENTS.has(name)) return true;
12901
+ if (IGNORE_FILES.has(name)) return true;
12902
+ if (name.endsWith(".map")) return true;
12903
+ for (let index = 0; index + 2 < segments.length; index++) if (segments[index] === "plans" && segments[index + 2] === "runtime") return true;
12904
+ return false;
12905
+ }
12906
+ /**
12907
+ * @public
12908
+ * @author ddj 2026-11-24
12909
+ * @description: 装配外部改动采集:watch 进队、合并读盘、按判定链落库;可整体卸载。
12910
+ * @param deps Host 能力与测试接缝
12911
+ * @returns 采集器
12912
+ */
12913
+ function installExternalCapture(deps) {
12914
+ const spaces = /* @__PURE__ */ new Map();
12915
+ const now = deps.now ?? Date.now;
12916
+ let seq = 0;
12917
+ let stopped = false;
12918
+ /**
12919
+ * @private
12920
+ * @description: 取(或建)工作区运行时状态。
12921
+ * @param cwd 工作区
12922
+ * @param sessionId 会话
12923
+ * @returns 状态
12924
+ */
12925
+ function spaceOf(cwd, sessionId) {
12926
+ const key = pathKeyOf(cwd);
12927
+ const existing = spaces.get(key);
12928
+ if (existing) return existing;
12929
+ const created = {
12930
+ cwd: String(cwd),
12931
+ sessionId,
12932
+ watchers: [],
12933
+ dirty: /* @__PURE__ */ new Map(),
12934
+ seen: /* @__PURE__ */ new Map(),
12935
+ timer: null,
12936
+ firstAt: 0,
12937
+ flushing: false,
12938
+ again: false,
12939
+ degraded: "",
12940
+ statusAt: 0,
12941
+ status: void 0,
12942
+ alignedAt: 0,
12943
+ alignTimer: null,
12944
+ requestTimer: null
12945
+ };
12946
+ spaces.set(key, created);
12947
+ return created;
12948
+ }
12949
+ /**
12950
+ * @private
12951
+ * @description: 事件分发:只收文件名,忽略目录与忽略清单。
12952
+ * @param space 工作区状态
12953
+ * @param base 被监听目录
12954
+ * @param name 事件文件名
12955
+ * @returns 无
12956
+ */
12957
+ function onEvent(space, base, name) {
12958
+ if (stopped || !name) return;
12959
+ enqueue(space.cwd, resolve(base, String(name)));
12960
+ }
12961
+ /**
12962
+ * @private
12963
+ * @description: 关闭一个工作区的全部监听器。
12964
+ * @param space 工作区状态
12965
+ * @returns 无
12966
+ */
12967
+ function closeWatchers(space) {
12968
+ for (const watcher of space.watchers) try {
12969
+ watcher.close();
12970
+ } catch {}
12971
+ space.watchers = [];
12972
+ }
12973
+ /**
12974
+ * @private
12975
+ * @description: 开始监听;递归可用就用递归,否则逐一级子目录监听,都不可用时只留补扫。
12976
+ * @param space 工作区状态
12977
+ * @returns 无
12978
+ */
12979
+ function startWatch(space) {
12980
+ if (space.watchers.length || stopped) return;
12981
+ try {
12982
+ const watcher = watch(space.cwd, {
12983
+ recursive: true,
12984
+ persistent: false
12985
+ }, (_event, name) => onEvent(space, space.cwd, name));
12986
+ watcher.on("error", (error) => {
12987
+ log.warn("外部改动监听中断(改为只靠补扫):" + String(error));
12988
+ closeWatchers(space);
12989
+ });
12990
+ space.watchers.push(watcher);
12991
+ return;
12992
+ } catch (error) {
12993
+ log.debug("递归监听不可用,降级逐目录监听:" + String(error));
12994
+ }
12995
+ try {
12996
+ const entries = readdirSync(space.cwd, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !IGNORE_SEGMENTS.has(entry.name)).slice(0, 64);
12997
+ for (const entry of entries) {
12998
+ const dir = join(space.cwd, entry.name);
12999
+ const watcher = watch(dir, { persistent: false }, (_event, name) => onEvent(space, dir, name));
13000
+ watcher.on("error", (error) => log.debug("目录监听中断:" + dir + " " + String(error)));
13001
+ space.watchers.push(watcher);
13002
+ }
13003
+ if (!space.watchers.length) space.degraded = "目录监听不可用";
13004
+ } catch (error) {
13005
+ space.degraded = "目录监听不可用:" + String(error);
13006
+ log.warn("外部改动监听不可用(改为只靠补扫):" + String(error));
13007
+ }
13008
+ }
13009
+ /**
13010
+ * @private
13011
+ * @description: 重新安排本批处理时刻:静默 300ms,但不超过首个事件后 2000ms。
13012
+ * @param space 工作区状态
13013
+ * @returns 无
13014
+ */
13015
+ function schedule(space) {
13016
+ const at = now();
13017
+ if (!space.firstAt) space.firstAt = at;
13018
+ if (space.timer) clearTimeout(space.timer);
13019
+ const wait = Math.max(0, Math.min(300, space.firstAt + MAX_WAIT_MS$1 - at));
13020
+ space.timer = setTimeout(() => {
13021
+ space.timer = null;
13022
+ flushSpace(space);
13023
+ }, wait);
13024
+ }
13025
+ /**
13026
+ * @private
13027
+ * @description: 取条目集合:真实路径读待审库,测试可注入。
13028
+ * @param cwd 工作区
13029
+ * @returns 路径比较键 → 条目
13030
+ */
13031
+ function entriesOf(cwd) {
13032
+ if (deps.entries) return deps.entries(cwd);
13033
+ const map = /* @__PURE__ */ new Map();
13034
+ for (const stored of loadEntries(cwd)) map.set(pathKeyOf(stored.entry.id), stored);
13035
+ return map;
13036
+ }
13037
+ /**
13038
+ * @private
13039
+ * @description: 读磁盘内容;缺失返回 null,其它失败抛出(由调用点记缺口)。
13040
+ * @param cwd 工作区
13041
+ * @param absolute 绝对路径
13042
+ * @returns 内容或 null
13043
+ */
13044
+ async function readOf(cwd, absolute) {
13045
+ if (deps.read) return deps.read(cwd, absolute);
13046
+ const fs = deps.ctx.get("fs");
13047
+ if (!fs) throw new Error("缺少 fs 服务");
13048
+ return readText$1(fs, await fs.resolve(absolute, { cwd }));
13049
+ }
13050
+ /**
13051
+ * @private
13052
+ * @description: 取版本库状态(带最小间隔缓存);无 shell 或非 git/svn 时返回 null。
13053
+ * @param space 工作区状态
13054
+ * @returns 状态或 null
13055
+ */
13056
+ async function statusOf(space) {
13057
+ const at = now();
13058
+ if (space.status !== void 0 && at - space.statusAt < 5e3) return space.status;
13059
+ space.statusAt = at;
13060
+ if (deps.status) {
13061
+ space.status = await deps.status(space.cwd, space.sessionId);
13062
+ return space.status;
13063
+ }
13064
+ const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId);
13065
+ space.status = scope ? await vcsStatus(scope.shell, space.cwd) : null;
13066
+ return space.status;
13067
+ }
13068
+ /**
13069
+ * @private
13070
+ * @description: 处理一个路径:判定链见文件头注释。
13071
+ * @param space 工作区状态
13072
+ * @param absolute 绝对路径
13073
+ * @param entries 本批共享的条目表
13074
+ * @returns 是否新增或更新了条目
13075
+ */
13076
+ async function handleOne(space, absolute, entries) {
13077
+ const key = pathKeyOf(absolute);
13078
+ const at = now();
13079
+ const content = await readOf(space.cwd, absolute);
13080
+ const stored = entries.get(key);
13081
+ const sameContent = stored !== void 0 && stored.entry.newText === (content ?? "");
13082
+ const sameMissing = stored !== void 0 && stored.flags.missing === (content === null);
13083
+ if (stored && sameContent && sameMissing) {
13084
+ space.seen.set(key, content);
13085
+ return false;
13086
+ }
13087
+ const window = windows.windowOf(key, at);
13088
+ if (window === "self") {
13089
+ space.seen.set(key, content);
13090
+ return false;
13091
+ }
13092
+ if (window === "editor") {
13093
+ space.seen.set(key, content);
13094
+ if (!stored) return false;
13095
+ deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "watch", "editor", "known"));
13096
+ return true;
13097
+ }
13098
+ const status = await statusOf(space);
13099
+ if (status && !status.entries.has(key)) {
13100
+ space.seen.set(key, content);
13101
+ if (!stored) return false;
13102
+ deps.record(writeOf(space, absolute, stored.entry.newText, content, at, "vcs", "vcs", "known"));
13103
+ return true;
13104
+ }
13105
+ const before = await beforeOf(space, key, absolute, stored, status, content);
13106
+ if (before.text === null && content === null) {
13107
+ space.seen.set(key, null);
13108
+ return false;
13109
+ }
13110
+ deps.record(writeOf(space, absolute, before.text, content, at, "watch", windows.inAgentWindow(at) ? "agent" : "external", before.kind));
13111
+ space.seen.set(key, content);
13112
+ return true;
13113
+ }
13114
+ /**
13115
+ * @private
13116
+ * @description: 求修改前内容:已知内容 → 首次观察 → 版本库新增/基线 → 未知。
13117
+ * @param space 工作区状态
13118
+ * @param key 路径比较键
13119
+ * @param absolute 绝对路径
13120
+ * @param stored 既有条目
13121
+ * @param status 版本库状态
13122
+ * @param content 当前内容
13123
+ * @returns 修改前内容与可信度
13124
+ */
13125
+ async function beforeOf(space, key, absolute, stored, status, content) {
13126
+ if (stored) return {
13127
+ text: stored.flags.missing ? null : stored.entry.newText,
13128
+ kind: "known"
13129
+ };
13130
+ if (space.seen.has(key)) {
13131
+ const seen = space.seen.get(key) ?? null;
13132
+ return {
13133
+ text: seen,
13134
+ kind: seen === null ? "absent" : "known"
13135
+ };
13136
+ }
13137
+ const entry = status?.entries.get(key);
13138
+ if (entry?.status === "added") return {
13139
+ text: null,
13140
+ kind: "absent"
13141
+ };
13142
+ if (entry && content !== null) {
13143
+ const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId);
13144
+ if (scope && status) {
13145
+ const base = await vcsBaselineOf(scope.shell, status, absolute);
13146
+ if (base !== null) return {
13147
+ text: base,
13148
+ kind: "vcs"
13149
+ };
13150
+ }
13151
+ }
13152
+ return {
13153
+ text: null,
13154
+ kind: "unknown"
13155
+ };
13156
+ }
13157
+ /**
13158
+ * @private
13159
+ * @description: 组装一条待审写入(watch 通道)。
13160
+ * @param space 工作区状态
13161
+ * @param absolute 绝对路径
13162
+ * @param before 修改前内容
13163
+ * @param after 当前内容
13164
+ * @param at 时间
13165
+ * @param source 采集通道
13166
+ * @param origin 归属
13167
+ * @param baseKind 基线可信度
13168
+ * @returns 待审写入
13169
+ */
13170
+ function writeOf(space, absolute, before, after, at, source, origin, baseKind) {
13171
+ return {
13172
+ cwd: space.cwd,
13173
+ sessionId: space.sessionId,
13174
+ path: absolute,
13175
+ identity: absolute,
13176
+ before,
13177
+ after,
13178
+ now: at,
13179
+ tool: source,
13180
+ origin,
13181
+ baseKind
13182
+ };
13183
+ }
13184
+ /**
13185
+ * @private
13186
+ * @description: 处理本工作区的一个批次:取一批 → 读盘判定 → 落库 → 失效目录树。
13187
+ * @param space 工作区状态
13188
+ * @returns 无
13189
+ */
13190
+ async function flushSpace(space) {
13191
+ if (stopped) return;
13192
+ if (space.flushing) {
13193
+ space.again = true;
13194
+ return;
13195
+ }
13196
+ space.flushing = true;
13197
+ space.firstAt = 0;
13198
+ let bytes = 0;
13199
+ let recorded = 0;
13200
+ try {
13201
+ const entries = entriesOf(space.cwd);
13202
+ const batch = [...space.dirty.entries()].slice(0, 64);
13203
+ for (const [key] of batch) space.dirty.delete(key);
13204
+ const ordered = batch.sort((left, right) => left[1].seq - right[1].seq);
13205
+ const touched = [];
13206
+ for (const [, item] of ordered) {
13207
+ if (stopped) break;
13208
+ try {
13209
+ const size = item.path.length;
13210
+ if (bytes + size > 8388608) {
13211
+ space.dirty.set(pathKeyOf(item.path), item);
13212
+ continue;
13213
+ }
13214
+ bytes += size;
13215
+ if (await handleOne(space, item.path, entries)) {
13216
+ recorded += 1;
13217
+ touched.push(item.path);
13218
+ }
13219
+ } catch (error) {
13220
+ noteCaptureGap(space.cwd, space.sessionId, item.path, error);
13221
+ log.debug("外部改动跳过:" + item.path + ": " + String(error));
13222
+ }
13223
+ }
13224
+ for (const path of touched) invalidateIndex(deps.ctx, space.cwd, path);
13225
+ if (recorded) log.debug(`外部改动记录 ${recorded} 条(${space.cwd})`);
13226
+ } catch (error) {
13227
+ log.warn("外部改动处理失败:" + String(error));
13228
+ } finally {
13229
+ space.flushing = false;
13230
+ if (space.seen.size > 5e3) for (const key of [...space.seen.keys()].slice(0, space.seen.size - SEEN_MAX)) space.seen.delete(key);
13231
+ if (space.dirty.size) schedule(space);
13232
+ else if (space.again) {
13233
+ space.again = false;
13234
+ schedule(space);
13235
+ }
13236
+ }
13237
+ }
13238
+ /**
13239
+ * @private
13240
+ * @description: 收一个写事件进队并重新排期;忽略清单命中直接丢。
13241
+ * @param cwd 工作区
13242
+ * @param absolute 绝对路径
13243
+ * @returns 无
13244
+ */
13245
+ function enqueue(cwd, absolute) {
13246
+ if (stopped || !absolute || !cwd || !deps.settings().watch) return;
13247
+ if (isIgnoredPath(cwd, absolute)) return;
13248
+ const space = spaces.get(pathKeyOf(cwd)) ?? spaceOf(cwd, "");
13249
+ seq += 1;
13250
+ space.dirty.set(pathKeyOf(absolute), {
13251
+ path: absolute,
13252
+ seq
13253
+ });
13254
+ schedule(space);
13255
+ }
13256
+ return {
13257
+ ensure(cwd, sessionId) {
13258
+ if (stopped || !cwd) return;
13259
+ const space = spaceOf(cwd, sessionId);
13260
+ if (!deps.settings().watch) return;
13261
+ startWatch(space);
13262
+ if (!deps.settings().scan || space.alignedAt) return;
13263
+ space.alignedAt = now();
13264
+ const timer = setTimeout(() => {
13265
+ alignNow(space);
13266
+ }, 0);
13267
+ if (typeof timer.unref === "function") timer.unref();
13268
+ if (!space.alignTimer) space.alignTimer = setInterval(() => {
13269
+ alignNow(space);
13270
+ }, ALIGN_INTERVAL_MS);
13271
+ if (typeof space.alignTimer.unref === "function") space.alignTimer.unref();
13272
+ },
13273
+ dismiss(cwd) {
13274
+ const key = pathKeyOf(cwd);
13275
+ const space = spaces.get(key);
13276
+ if (!space) return;
13277
+ closeWatchers(space);
13278
+ if (space.timer) clearTimeout(space.timer);
13279
+ if (space.requestTimer) clearTimeout(space.requestTimer);
13280
+ if (space.alignTimer) clearInterval(space.alignTimer);
13281
+ spaces.delete(key);
13282
+ },
13283
+ requestAlign(cwd, delayMs = ALIGN_AFTER_VCS_MS) {
13284
+ if (stopped || !cwd || !deps.settings().scan) return;
13285
+ const space = spaces.get(pathKeyOf(cwd));
13286
+ if (!space) return;
13287
+ if (space.requestTimer) clearTimeout(space.requestTimer);
13288
+ const timer = setTimeout(() => {
13289
+ space.requestTimer = null;
13290
+ alignNow(space);
13291
+ }, Math.max(0, delayMs));
13292
+ if (typeof timer.unref === "function") timer.unref();
13293
+ space.requestTimer = timer;
13294
+ },
13295
+ enqueue(cwd, absolute) {
13296
+ enqueue(cwd, absolute);
13297
+ },
13298
+ async flush(cwd) {
13299
+ for (const [key, space] of spaces) {
13300
+ if (cwd && key !== pathKeyOf(cwd)) continue;
13301
+ if (space.timer) {
13302
+ clearTimeout(space.timer);
13303
+ space.timer = null;
13304
+ }
13305
+ await flushSpace(space);
13306
+ }
13307
+ },
13308
+ dispose() {
13309
+ stopped = true;
13310
+ for (const space of spaces.values()) {
13311
+ closeWatchers(space);
13312
+ if (space.timer) clearTimeout(space.timer);
13313
+ if (space.alignTimer) clearInterval(space.alignTimer);
13314
+ space.dirty.clear();
13315
+ space.seen.clear();
13316
+ }
13317
+ spaces.clear();
13318
+ }
13319
+ };
13320
+ /**
13321
+ * @private
13322
+ * @description: 后台补扫一次(复用 externalAlign 的候选与预算)。
13323
+ * @param space 工作区状态
13324
+ * @returns 无
13325
+ */
13326
+ async function alignNow(space) {
13327
+ if (stopped || !deps.settings().scan) return;
13328
+ try {
13329
+ if (deps.align) {
13330
+ await deps.align(space.cwd, space.sessionId);
13331
+ return;
13332
+ }
13333
+ const { alignInWorkspace } = await Promise.resolve().then(() => externalAlign_exports);
13334
+ const outcome = await alignInWorkspace(deps.ctx, space.cwd, space.sessionId, deps.record);
13335
+ if (outcome.gaps.length) log.debug("补扫缺口:" + outcome.gaps.join(";"));
13336
+ } catch (error) {
13337
+ log.debug("后台补扫失败:" + String(error));
13338
+ }
13339
+ }
13340
+ }
13341
+ //#endregion
12133
13342
  //#region src/pending/lineDiff.ts
12134
13343
  /** 单窗口 LCS 单元格上限:超过先找锚点;4 MB 表实测约 7 ms。 */
12135
13344
  const LCS_CELLS = 1e6;
@@ -12659,7 +13868,10 @@ function mergeEntries(earlier, later) {
12659
13868
  const merged = {
12660
13869
  ...later,
12661
13870
  updatedAt: later.updatedAt,
12662
- sessionIds: unionSessions(earlier, later)
13871
+ sessionIds: unionSessions(earlier, later),
13872
+ source: strongerSource(earlier.source, later.source),
13873
+ origin: later.origin ?? earlier.origin,
13874
+ baseKind: later.baseKind ?? earlier.baseKind
12663
13875
  };
12664
13876
  if (later.lineage === void 0 && earlier.lineage !== void 0) merged.lineage = earlier.lineage;
12665
13877
  if (earlier.earlierVersion === "none" && later.earlierVersion === "none") {
@@ -12689,6 +13901,9 @@ function entryFromNew(input) {
12689
13901
  sessionIds: [input.sessionId]
12690
13902
  };
12691
13903
  if (input.lineage !== void 0) entry.lineage = input.lineage;
13904
+ if (input.source !== void 0) entry.source = input.source;
13905
+ if (input.origin !== void 0) entry.origin = input.origin;
13906
+ if (input.baseKind !== void 0) entry.baseKind = input.baseKind;
12692
13907
  return entry;
12693
13908
  }
12694
13909
  /**
@@ -12902,8 +14117,9 @@ function markAll(states, targets, decision) {
12902
14117
  return next;
12903
14118
  }
12904
14119
  /**
12905
- * @author ddj 2026年10月29号
12906
- * @description: 能力口径:Keep 恒可;Revert 受超大/缺失/已解决限制,拒绝原因要能展示。
14120
+ * @author ddj 2026年10月29号 / 2026年11月24号
14121
+ * @description: 能力口径:Keep 恒可;Revert 受超大/缺失/已解决/来源限制,拒绝原因要能展示。
14122
+ * 撤销白名单:只有 agent 来源且基线可信时直接可撤销,其它来源要求客户端显式确认。
12907
14123
  * @param entry 待审条目
12908
14124
  * @param flags 持久标记
12909
14125
  * @returns 能力与原因
@@ -12919,11 +14135,22 @@ function capabilityOf$1(entry, flags) {
12919
14135
  revert: false,
12920
14136
  reason: "oversized"
12921
14137
  };
14138
+ if (entry.baseKind === "unknown") return {
14139
+ keep: true,
14140
+ revert: false,
14141
+ reason: "未捕获修改前内容(外部写入):留档可见,但不能撤销,否则会删掉现有代码"
14142
+ };
12922
14143
  if (entry.earlierVersion === "none" && entry.newText.length === 0) return {
12923
14144
  keep: true,
12924
14145
  revert: false,
12925
14146
  reason: "empty-create"
12926
14147
  };
14148
+ if (revertPolicyOf(entry.origin, entry.baseKind) === "confirm") return {
14149
+ keep: true,
14150
+ revert: true,
14151
+ confirmRevert: true,
14152
+ reason: "该改动不是本会话工具写的(" + sourceLabelOf(entry) + "):撤销前请确认"
14153
+ };
12927
14154
  return {
12928
14155
  keep: true,
12929
14156
  revert: true,
@@ -13004,7 +14231,10 @@ function foldWrite(stored, write) {
13004
14231
  earlierVersion: write.before === null ? "none" : "file",
13005
14232
  oldText: write.before ?? "",
13006
14233
  newText: write.after ?? "",
13007
- updatedAt: write.now
14234
+ updatedAt: write.now,
14235
+ source: sourceOfTool(write.tool),
14236
+ origin: originOf(write),
14237
+ baseKind: write.before === null ? "absent" : write.baseKind ?? "known"
13008
14238
  });
13009
14239
  if (!stored) return {
13010
14240
  entry: fresh,
@@ -13028,6 +14258,20 @@ function foldWrite(stored, write) {
13028
14258
  };
13029
14259
  }
13030
14260
  /**
14261
+ * @private
14262
+ * @author ddj 2026-11-24
14263
+ * @description: 本次写入的归属:显式指定优先,否则按窗口判定(工具链路默认 agent)。
14264
+ * @param write 采集到的写入
14265
+ * @returns 归属
14266
+ */
14267
+ function originOf(write) {
14268
+ if (write.origin) return write.origin;
14269
+ const window = windows.windowOf(pathKeyOf(write.identity));
14270
+ if (window === "self") return "agent";
14271
+ if (window === "editor") return "editor";
14272
+ return "agent";
14273
+ }
14274
+ /**
13031
14275
  * @author ddj 2026年10月29号
13032
14276
  * @description: 条目转列表投影,已解决条目仍保留但不可再决定。
13033
14277
  * @param stored 条目与标记
@@ -13051,7 +14295,10 @@ function itemOf(stored, baselineEmpty = false) {
13051
14295
  revision: flags.revision,
13052
14296
  updatedAt: entry.updatedAt,
13053
14297
  sessionId: entry.sessionId,
13054
- sessionIds: entry.sessionIds
14298
+ sessionIds: entry.sessionIds,
14299
+ source: entry.source ?? "tool",
14300
+ origin: entry.origin ?? "agent",
14301
+ baseKind: entry.baseKind ?? "known"
13055
14302
  };
13056
14303
  if (entry.lineage !== void 0) item.lineage = entry.lineage;
13057
14304
  return item;
@@ -13137,14 +14384,16 @@ function recordWrite(write) {
13137
14384
  * @param now 时间
13138
14385
  * @returns 新条目与标记
13139
14386
  */
13140
- function absorbed(stored, content, now) {
14387
+ function absorbed(stored, content, now, origin) {
14388
+ const entry = {
14389
+ ...stored.entry,
14390
+ newText: content,
14391
+ updatedAt: now,
14392
+ unseen: true
14393
+ };
14394
+ if (origin) entry.origin = origin;
13141
14395
  return {
13142
- entry: {
13143
- ...stored.entry,
13144
- newText: content,
13145
- updatedAt: now,
13146
- unseen: true
13147
- },
14396
+ entry,
13148
14397
  flags: {
13149
14398
  ...stored.flags,
13150
14399
  diverged: true,
@@ -13274,7 +14523,7 @@ async function applyDecide(fs, cwd, request, signal, policy) {
13274
14523
  now: Date.now(),
13275
14524
  write: (content) => {
13276
14525
  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);
14526
+ return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy, true)(content);
13278
14527
  }
13279
14528
  });
13280
14529
  if (!outcome.ok) return {
@@ -18910,6 +20159,12 @@ function readHandlers(kit) {
18910
20159
  ok: false,
18911
20160
  error: "待审条目不存在"
18912
20161
  };
20162
+ },
20163
+ "edrv.pending.version": async (args) => {
20164
+ return {
20165
+ ok: true,
20166
+ version: pendingVersion(await kit.read(args.sessionId))
20167
+ };
18913
20168
  }
18914
20169
  };
18915
20170
  }
@@ -19050,6 +20305,23 @@ function refreshHandlers(kit) {
19050
20305
  ok: true,
19051
20306
  item: itemOf(next ?? stored)
19052
20307
  };
20308
+ },
20309
+ "edrv.pending.align": async (args) => {
20310
+ const cwd = await kit.write(args.sessionId);
20311
+ const outcome = await alignInWorkspace(kit.ctx, cwd, args.sessionId, (write) => {
20312
+ try {
20313
+ trackPendingCover(write.cwd, write.path, true, write.sessionId);
20314
+ } catch {}
20315
+ recordWrite(write);
20316
+ });
20317
+ const page = loadPage(cwd, args.sessionId);
20318
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path));
20319
+ return {
20320
+ ok: true,
20321
+ imported: outcome.imported,
20322
+ changed: outcome.changed,
20323
+ gaps: outcome.gaps
20324
+ };
19053
20325
  }
19054
20326
  };
19055
20327
  }
@@ -20688,8 +21960,9 @@ function isStaleVersion(error) {
20688
21960
  * @param sc requireSession 成功结果(session + cwd)
20689
21961
  * @param path 保存的文件路径
20690
21962
  */
20691
- async function afterManualSave(ctx, registry, sc, path) {
21963
+ async function afterManualSave(ctx, registry, sc, path, identity) {
20692
21964
  invalidateIndex(ctx, sc.cwd, path);
21965
+ windows.markEditor(pathKeyOf(identity ?? path));
20693
21966
  }
20694
21967
  /**
20695
21968
  * 批量决策核心:一次会话/桶解析 + 逐项处理 + 统一落盘(accept/reject 单条与 decideBatch 共用)。
@@ -21611,7 +22884,7 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
21611
22884
  version: rev
21612
22885
  } : void 0;
21613
22886
  const outcome = await fs.writeText(target, args.content, intent, void 0, policyOf(ctx, sc.session));
21614
- await afterManualSave(ctx, registry, sc, args.path);
22887
+ await afterManualSave(ctx, registry, sc, args.path, fs.processPath(target));
21615
22888
  return {
21616
22889
  ok: true,
21617
22890
  rev: outcome?.version ? String(outcome.version) : rev ?? void 0
@@ -21666,7 +22939,7 @@ function buildHandlers(ctx, registry, searcher = newSearcher(ctx), contentSearch
21666
22939
  error: "内容过大(>32MB),拒绝写回"
21667
22940
  };
21668
22941
  await writeFile(fs.processPath(target), bytes);
21669
- await afterManualSave(ctx, registry, sc, args.path);
22942
+ await afterManualSave(ctx, registry, sc, args.path, fs.processPath(target));
21670
22943
  return { ok: true };
21671
22944
  } catch (error) {
21672
22945
  return {
@@ -35961,7 +37234,8 @@ function createRuntime(ctx, config) {
35961
37234
  settings
35962
37235
  }),
35963
37236
  dapRpc: createDapRpc(ctx),
35964
- fileVersions: createFileVersions(ctx)
37237
+ fileVersions: createFileVersions(ctx),
37238
+ settings
35965
37239
  };
35966
37240
  }
35967
37241
  /**
@@ -35976,7 +37250,8 @@ function attachRuntime(ctx, runtime) {
35976
37250
  evidence.persist(cwd, snapshot);
35977
37251
  return true;
35978
37252
  });
35979
- const pending = installPending(ctx, (write) => {
37253
+ /** @author ddj 2026年11月24号 @param write 已确认的一次写入 @returns 无;落库失败不打断用户工具调用 */
37254
+ function recordPendingWrite(write) {
35980
37255
  try {
35981
37256
  trackPendingCover(write.cwd, write.path, true, write.sessionId);
35982
37257
  } catch {}
@@ -35985,7 +37260,36 @@ function attachRuntime(ctx, runtime) {
35985
37260
  } catch (error) {
35986
37261
  log.warn("待审差异落库失败:" + String(error));
35987
37262
  }
37263
+ }
37264
+ const pending = installPending(ctx, recordPendingWrite);
37265
+ const external = installExternalCapture({
37266
+ ctx,
37267
+ settings: () => runtime.settings.external(),
37268
+ record: recordPendingWrite
35988
37269
  });
37270
+ /**
37271
+ * @author ddj 2026年11月24号
37272
+ * @description: 任一工具调用期间都是 agent 写入窗口:bash / python 写盘落在窗口内时归属 agent。
37273
+ * 版本库写工具结束后再补扫一次,把命令造成的成片变化对齐进待审投影。
37274
+ * @param exec 工具执行描述
37275
+ * @param next 原始分发
37276
+ * @returns 原始结果
37277
+ */
37278
+ function aroundToolWindow(exec, next) {
37279
+ windows.enterTool();
37280
+ return Promise.resolve().then(next).finally(() => {
37281
+ windows.exitTool();
37282
+ if (!VCS_WRITE_TOOLS.has(String(exec.name ?? ""))) return;
37283
+ const cwd = cwdOfSession(ctx, exec.agent?.session);
37284
+ if (cwd) external.requestAlign(cwd);
37285
+ });
37286
+ }
37287
+ /** @author ddj 2026年11月24号 @param session 新建会话 @returns 无;工作区可用即开始监听 */
37288
+ function onCreated(session) {
37289
+ if (typeof session.id !== "string") return;
37290
+ const cwd = cwdOfSession(ctx, session);
37291
+ if (cwd) external.ensure(cwd, session.id);
37292
+ }
35989
37293
  /** @author ddj 2026年09月28号 @param exec Tool execution. @param result Tool result. */
35990
37294
  function onResult(exec, result) {
35991
37295
  captureToolResult(ctx, runtime.registry, exec, result);
@@ -35994,6 +37298,7 @@ function attachRuntime(ctx, runtime) {
35994
37298
  function onDisposed(session) {
35995
37299
  const cwd = cwdOf(session);
35996
37300
  if (cwd) {
37301
+ external.dismiss(cwd);
35997
37302
  runtime.registry.delete(cwd);
35998
37303
  runtime.searcher.dispose(cwd);
35999
37304
  runtime.contentSearcher.dispose(cwd);
@@ -36006,6 +37311,8 @@ function attachRuntime(ctx, runtime) {
36006
37311
  await stopCapture();
36007
37312
  evidence.dispose();
36008
37313
  pending.dispose();
37314
+ external.dispose();
37315
+ windows.dispose();
36009
37316
  runtime.fileVersions.dispose();
36010
37317
  closeArchiveDbs();
36011
37318
  disposeAllServers();
@@ -36016,9 +37323,13 @@ function attachRuntime(ctx, runtime) {
36016
37323
  ].map((run) => Promise.resolve().then(run)));
36017
37324
  }
36018
37325
  ctx.on("tools/result", onResult);
37326
+ ctx.on("tools/execute", aroundToolWindow);
37327
+ ctx.on("session/created", onCreated);
36019
37328
  ctx.on("session/disposed", onDisposed);
37329
+ for (const session of ctx.get("sessions").list()) onCreated(session);
36020
37330
  ctx.effect(() => cleanup, "vscode-mode:runtime");
36021
37331
  hookExitReclaim();
37332
+ return { external };
36022
37333
  }
36023
37334
  /**
36024
37335
  * Add user rules and bundled skills without requiring them on older Hosts.
@@ -36041,12 +37352,35 @@ async function apply(ctx, config) {
36041
37352
  bindHostLog(ctx);
36042
37353
  const runtime = createRuntime(ctx, config);
36043
37354
  const warnings = [];
36044
- attachRuntime(ctx, runtime);
37355
+ const capture = attachRuntime(ctx, runtime);
36045
37356
  installContent(ctx);
37357
+ /** 版本库写操作后的补扫串行链:并发 RPC 也不会叠出多次补扫。 */
37358
+ let alignChain = Promise.resolve();
36046
37359
  /** @author ddj 2026年09月28号 @param method RPC name. @param args Typed request. @returns RPC result. */
36047
37360
  function dispatch(method, args) {
36048
37361
  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);
37362
+ const pendingResult = handleRpc(ctx, registry, method, args, searcher, contentSearcher, lspRpc.handlers, aiRpc.handlers, fileVersions, svnRpc.handlers, dapRpc.handlers);
37363
+ if (!VCS_WRITE_METHODS.has(method)) return pendingResult;
37364
+ alignChain = alignChain.then(async () => {
37365
+ const cwd = await workspaceOfSession(args?.sessionId);
37366
+ if (cwd) capture.external.requestAlign(cwd);
37367
+ }).catch(() => {});
37368
+ return pendingResult;
37369
+ }
37370
+ /**
37371
+ * @author ddj 2026年11月24号
37372
+ * @description: 取 RPC 参数里的会话工作区;取不到就跳过补扫,绝不影响 RPC 本身。
37373
+ * @param sessionId 请求会话
37374
+ * @returns 工作区路径或 null
37375
+ */
37376
+ async function workspaceOfSession(sessionId) {
37377
+ try {
37378
+ if (!sessionId) return null;
37379
+ const scope = await resolveScope(ctx, sessionId);
37380
+ return "err" in scope ? null : scope.cwd;
37381
+ } catch {
37382
+ return null;
37383
+ }
36050
37384
  }
36051
37385
  /** @author ddj 2026年09月28号 @param warning Startup compatibility diagnostic. */
36052
37386
  function noteWarning(warning) {