dsh-vscode-mode 0.38.0 → 0.40.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 (66) hide show
  1. package/README.md +38 -33
  2. package/lib/client.js +87 -68
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +11406 -4920
  5. package/lib/index.js.map +1 -1
  6. package/package.json +3 -2
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +44 -42
  8. package/skills/dsh-vscodemode-test-check/SKILL.md +82 -0
  9. package/src/archiveDb.ts +24 -0
  10. package/src/attachmentBytes.ts +84 -0
  11. package/src/client/htmlPlan/HtmlPlanModeChip.ts +181 -0
  12. package/src/client/htmlPlan/HtmlPlanPanel.ts +230 -61
  13. package/src/client/htmlPlan/planActions.ts +38 -8
  14. package/src/client/htmlPlan/planPage.ts +111 -9
  15. package/src/client/index.ts +9 -0
  16. package/src/client/openReceipt.ts +5 -2
  17. package/src/client/planBridge.ts +27 -2
  18. package/src/client/planState.ts +51 -4
  19. package/src/client/sidebar/panels/TestCheckPanel.ts +485 -0
  20. package/src/client/sidebar/panels/useTestCheckData.ts +414 -0
  21. package/src/client/sidebar/types.ts +2 -0
  22. package/src/client/state/diffSummary.ts +3 -0
  23. package/src/client/styles/editor.css +91 -0
  24. package/src/client/testCheck/TestCheckChip.ts +181 -0
  25. package/src/client/testCheck/TestCheckPanel.ts +339 -0
  26. package/src/client/testCheckPanelState.ts +173 -0
  27. package/src/client/ui/EditorView.ts +77 -7
  28. package/src/client/ui/McpSettings.ts +2 -2
  29. package/src/client/ui/OfficialReview.ts +6 -4
  30. package/src/htmlPlanAttachments.ts +4 -1
  31. package/src/htmlPlanCommand.ts +87 -235
  32. package/src/htmlPlanGuidance.ts +67 -0
  33. package/src/htmlPlanMode.ts +547 -0
  34. package/src/index.ts +28 -55
  35. package/src/officialCapture.ts +58 -9
  36. package/src/pending/externalCapture.ts +195 -401
  37. package/src/pending/kernel.ts +24 -1
  38. package/src/pending/persist.ts +109 -22
  39. package/src/pending/provenance.ts +5 -28
  40. package/src/pending/store.ts +109 -100
  41. package/src/pending/tracking.ts +81 -0
  42. package/src/pendingCompat.ts +26 -1
  43. package/src/pendingRpc.ts +8 -56
  44. package/src/planAutoPage.ts +306 -0
  45. package/src/planPagePack.ts +148 -0
  46. package/src/registry.ts +7 -2
  47. package/src/reviewDb.ts +1 -1
  48. package/src/reviewRpc.ts +14 -6
  49. package/src/rpc.ts +34 -0
  50. package/src/shared/htmlPlanMode.ts +26 -0
  51. package/src/shared/pendingReview.ts +15 -7
  52. package/src/shared/review.ts +5 -0
  53. package/src/shared/rpc.ts +53 -7
  54. package/src/shared/testCheck.ts +759 -0
  55. package/src/shared/testCheckHtml.ts +276 -0
  56. package/src/shared/testCheckPolicyDefault.ts +37 -0
  57. package/src/shared/testCheckSnippets.ts +197 -0
  58. package/src/store.ts +17 -1
  59. package/src/testCheckCommand.ts +287 -0
  60. package/src/testCheckGuidance.ts +79 -0
  61. package/src/testCheckMode.ts +654 -0
  62. package/src/testCheckPolicy.ts +141 -0
  63. package/src/testCheckRpc.ts +196 -0
  64. package/src/testCheckStore.ts +822 -0
  65. package/src/pending/externalAlign.ts +0 -297
  66. package/src/pending/vcs.ts +0 -584
@@ -1,22 +1,17 @@
1
1
  /**
2
- * 外部改动实时采集:非 DSH 文件工具(`ops_bash` 里 `node -e`、prettier、生成器、python/sed 等)
3
- * 改过的文件,用被监听目录的写事件补进待审投影。
2
+ * 差异追踪窗口的跟随器:只跟随“AI 文件工具动过、用户还没处理完”的文件。
4
3
  *
5
4
  * 设计取舍:
6
- * - 只监听工作区根(递归),事件先入队,300ms 静默或 2000ms 封顶后统一读盘;单轮最多处理
7
- * MAX_BATCH 个文件、MAX_FLUSH_BYTES 字节,其余留到下一轮。批量按**入队顺序**处理,不按 mtime:
8
- * 同一毫秒内的多次写入 mtime 相同,用它排序反而可能造出倒序 diff。
9
- * - 判定顺序固定:已知内容未变 → 跳过;插件自写窗口 → 跳过;编辑器保存窗口 → 只推进基线;
10
- * 版本库说干净 → 跳过或标成版本库同步;拿不到版本库状态且是首次见到的路径 → 必须自带 mtime 证据
11
- * (文件确实在监听开始之后被写过),否则只记缺口不建档;整文件新增短时间成批出现 → 熔断静默一段时间。
12
- * 写记录前按身份重读一次条目:本批快照可能早于工具落库,不重读就会把工具写入再记成版本库同步。
13
- * 其余按窗口判定归属后落库。绝不按时间戳猜重复,也绝不把「被读过」当成「被改过」。
14
- * - 递归监听不可用(Linux)时降级为逐子目录非递归监听;仍不可用就只靠补扫,并把原因写进缺口。
15
- * - 读盘一律走待审采集的严格 UTF-8 往返:二进制、GBK 等无法字节往返的内容不落记录(记缺口),
16
- * 绝不因为"分析"而改写任何字节。
17
- * 作者 ddj 2026-11-24
5
+ * - 不再为任何新路径建档。`handleOne` 先看该路径有没有开着的窗口:没有就直接丢弃事件,
6
+ * Unity 重写 `index.json`、生成 `.meta`、脚本写盘都不会再冒出一条差异。
7
+ * - 窗口内的改动只折当前内容(基线不动):watch 事件走 300ms 静默 / 2000ms 封顶合并,
8
+ * 启动、每 10 分钟和手动按钮各跑一次校准,把窗口内漏掉的事件从磁盘补齐。
9
+ * - 读盘一律走待审采集的严格 UTF-8 往返:二进制、GBK 等无法字节往返的内容只记缺口,
10
+ * 绝不因为“分析”而改写任何字节。
11
+ * - 递归监听不可用(Linux)时降级为逐子目录非递归监听;仍不可用就只靠校准。
12
+ * 作者 ddj 2026年11月25号
18
13
  */
19
- import { readdirSync, statSync, watch } from 'node:fs'
14
+ import { readdirSync, watch } from 'node:fs'
20
15
  import type { FSWatcher } from 'node:fs'
21
16
  import { join, resolve } from 'node:path'
22
17
  import type { Ctx } from '../store.js'
@@ -24,12 +19,10 @@ import { log } from '../log.js'
24
19
  import type { PendingWrite } from './capture.js'
25
20
  import { noteCaptureGap, readText } from './capture.js'
26
21
  import type { StoredEntry } from './persist.js'
27
- import { loadEntries, loadEntry } from './persist.js'
22
+ import { loadEntries } from './persist.js'
28
23
  import { FILE_EXCLUDES, EXCLUDES } from '../search/ripgrep.js'
29
24
  import { pathKeyOf, windows } from './provenance.js'
30
- import type { VcsStatus } from './vcs.js'
31
- import { vcsBaselineOf, vcsStatus } from './vcs.js'
32
- import { vcsScopeOf } from './externalAlign.js'
25
+ import { isOpenEntry } from './tracking.js'
33
26
  import { invalidateIndex } from '../treeIndex.js'
34
27
 
35
28
  // --region 预算与忽略清单
@@ -44,44 +37,18 @@ export const MAX_BATCH = 64
44
37
  export const MAX_FLUSH_BYTES = 8 << 20
45
38
  /** 单文件读取上限(与待审采集一致)。 */
46
39
  export const MAX_FILE_BYTES = 1024 * 1024
47
- /** 版本库状态命令的最小间隔:补扫与 watch 合并取用,避免频繁起进程。 */
48
- export const VCS_STATUS_MIN_INTERVAL_MS = 5000
49
40
  /** 递归监听不可用时,最多逐目录监听多少个一级子目录。 */
50
41
  export const WATCH_DIR_MAX = 64
51
- /** 内存基线表上限(路径比较键数)。 */
52
- export const SEEN_MAX = 5000
53
- /** 定时补扫间隔。 */
54
- export const ALIGN_INTERVAL_MS = 10 * 60_000
55
- /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
56
- export const ALIGN_AFTER_VCS_MS = 1500
42
+ /** 定时校准间隔:窗口内漏掉的事件靠它从磁盘补齐。 */
43
+ export const SYNC_INTERVAL_MS = 10 * 60_000
44
+ /** 单次校准最多扫描多少个开窗文件。 */
45
+ export const SYNC_MAX = 64
57
46
  /** 每个工作区最多记住多少条「已上报过的缺口」,防止事件风暴把去重表撑大。 */
58
47
  export const GAP_KEY_MAX = 500
59
- /** 「版本库状态不可用」这条诊断的最短间隔:同一工作区 5 分钟只报一次。 */
60
- export const STATUS_NOTE_MIN_MS = 5 * 60_000
61
- /** mtime 证据的时钟容差:监听开始前这段时间内写过的文件也算「刚被写过」。 */
62
- export const WATCH_SKEW_MS = 2000
63
- /** 熔断窗口:统计「整文件新增」记录的时间窗。 */
64
- export const BURST_WINDOW_MS = 5 * 60_000
65
- /** 窗口内最多允许的整文件新增条数:超过即判定为批量噪声。 */
66
- export const BURST_NEW_LIMIT = 200
67
- /** 熔断后的静默期:这段时间只更新已有条目,不新建。 */
68
- export const BURST_COOLDOWN_MS = 10 * 60_000
69
-
70
- /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
71
- export const VCS_WRITE_METHODS = new Set([
72
- 'svn.revert', 'svn.resolve', 'svn.add', 'svn.cleanup', 'svn.update', 'svn.ignore', 'svn.commit',
73
- ])
74
-
75
- /** 会改动工作副本的版本库工具名。 */
76
- export const VCS_WRITE_TOOLS = new Set([
77
- 'svn_add', 'svn_delete', 'svn_revert', 'svn_commit', 'svn_update', 'svn_resolve', 'svn_cleanup',
78
- 'svn_propset', 'svn_propdel', 'svn_changelist', 'remote_ssh_write',
79
- ])
80
48
 
81
49
  /**
82
50
  * 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。
83
- * 只收版本库元数据、Unity 缓存与构建产物:第三方与代码生成目录不在忽略之列,
84
- * 它们的改动靠「mtime 证据 + 版本库状态」两道闸门拦,而不是按目录名一刀切。
51
+ * 只收版本库元数据、Unity 缓存与构建产物;其余目录跟随事件进入判定,未开窗的路径会被直接丢弃。
85
52
  */
86
53
  export const EXTRA_IGNORE_SEGMENTS = ['.svn', '.hg', '.p4config', 'Library', 'Temp', 'obj', 'Logs']
87
54
 
@@ -126,39 +93,43 @@ export function isIgnoredPath(cwd: string, absolute: string): boolean {
126
93
 
127
94
  // --region 类型
128
95
 
129
- /** 外部采集的两个开关。 */
96
+ /** 跟随器的两个开关。 */
130
97
  export interface ExternalSettings {
98
+ /** 实时跟随开窗文件(watch)。 */
131
99
  watch: boolean
100
+ /** 启动与每 10 分钟从磁盘校准开窗文件。 */
132
101
  scan: boolean
133
102
  }
134
103
 
135
- /** 采集依赖:Host 能力 + 可注入的测试接缝。 */
104
+ /** 一次校准的结果。 */
105
+ export interface SyncOutcome {
106
+ /** 检查了多少个开窗文件。 */
107
+ checked: number
108
+ /** 折进了多少次改动。 */
109
+ folded: number
110
+ /** 读盘失败等缺口说明。 */
111
+ gaps: string[]
112
+ }
113
+
114
+ /** 跟随器依赖:Host 能力 + 可注入的测试接缝。 */
136
115
  export interface ExternalCaptureDeps {
137
116
  ctx: Ctx
138
117
  settings(): ExternalSettings
139
- /** 落库:与 installPending 复用同一个 sink。 */
140
- record(write: PendingWrite): void
118
+ /** 折进窗口:与工具链路共用同一个待审库入口,返回是否真的折了。 */
119
+ fold(write: PendingWrite): boolean
141
120
  /** 覆盖读盘(测试注入);缺省走 ctx.fs 的严格 UTF-8 往返。 */
142
121
  read?(cwd: string, absolute: string): Promise<string | null>
143
122
  /** 覆盖条目读取(测试注入);缺省读待审库。 */
144
- entries?(cwd: string): Map<string, StoredEntry>
145
- /** 覆盖版本库状态(测试注入);缺省跑一条 status 命令。 */
146
- status?(cwd: string, sessionId: string): Promise<VcsStatus | null>
147
- /** 覆盖补扫执行(测试注入);缺省调用 alignInWorkspace。 */
148
- align?(cwd: string, sessionId: string): Promise<void>
149
- /** 覆盖 mtime 读取(测试注入);缺省 statSync。拿不到返回 undefined。 */
150
- mtime?(cwd: string, absolute: string): number | undefined
151
- /** 覆盖单条最新条目读取(测试注入);缺省按身份查一条。 */
152
- latest?(cwd: string, absolute: string): StoredEntry | undefined
123
+ entries?(cwd: string): StoredEntry[]
153
124
  now?(): number
154
125
  }
155
126
 
156
- /** 采集器对外能力。 */
127
+ /** 跟随器对外能力。 */
157
128
  export interface ExternalCapture {
158
- /** 确保工作区已开始监听(幂等;同时触发一次后台补扫)。 */
129
+ /** 确保工作区已开始监听(幂等;同时安排一次启动校准)。 */
159
130
  ensure(cwd: string, sessionId: string): void
160
- /** 申请一次延迟补扫(版本库命令之后、手动按钮都用它;同一工作区会合并)。 */
161
- requestAlign(cwd: string, delayMs?: number): void
131
+ /** 立即校准一次并返回结果。 */
132
+ sync(cwd: string): Promise<SyncOutcome>
162
133
  /** 工作区不再需要监听(会话销毁)。 */
163
134
  dismiss(cwd: string): void
164
135
  /** 收到一个写事件(watcher 与测试共用)。 */
@@ -175,41 +146,29 @@ interface Workspace {
175
146
  sessionId: string
176
147
  watchers: FSWatcher[]
177
148
  dirty: Map<string, { path: string; seq: number }>
178
- seen: Map<string, string | null>
179
149
  timer: ReturnType<typeof setTimeout> | null
180
150
  firstAt: number
181
- flushing: boolean
182
- again: boolean
151
+ /** 串行链:watch 批次与校准不交叉读写同一批条目。 */
152
+ chain: Promise<void>
183
153
  degraded: string
184
- statusAt: number
185
- status?: VcsStatus | null
186
- alignedAt: number
187
- alignTimer: ReturnType<typeof setTimeout> | null
188
- /** 延后补扫的定时器(版本库命令后/手动按钮,同一工作区合并一次)。 */
189
- requestTimer: ReturnType<typeof setTimeout> | null
190
- /** 本次监听的起始时刻:文件 mtime 不比它新,就不是「刚被写过」。 */
191
- startedAt: number
154
+ /** 启动校准是否已排过。 */
155
+ scheduled: boolean
156
+ /** 定时校准器。 */
157
+ syncTimer: ReturnType<typeof setInterval> | null
192
158
  /** 已上报过的缺口键(同路径/同原因只报一次)。 */
193
159
  gapKeys: Set<string>
194
- /** 上次把「版本库状态不可用」写进缺口的时刻。 */
195
- statusNoteAt: number
196
- /** 熔断窗口起点与窗口内已建的整文件新增条数。 */
197
- burstAt: number
198
- burstCount: number
199
- /** 熔断静默截止时刻:在此之前不新建整文件新增记录。 */
200
- burstMutedUntil: number
201
160
  }
202
161
 
203
162
  // --endregion
204
163
 
205
- // --region 采集器
164
+ // --region 跟随器
206
165
 
207
166
  /**
208
167
  * @public
209
- * @author ddj 2026-11-24
210
- * @description: 装配外部改动采集:watch 进队、合并读盘、按判定链落库;可整体卸载。
168
+ * @author ddj 2026年11月25号
169
+ * @description: 装配差异窗口跟随器:watch 进队、合并读盘、只折已开窗路径;可整体卸载。
211
170
  * @param deps Host 能力与测试接缝
212
- * @returns 采集器
171
+ * @returns 跟随器
213
172
  */
214
173
  export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCapture {
215
174
  const spaces = new Map<string, Workspace>()
@@ -229,16 +188,26 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
229
188
  const existing = spaces.get(key)
230
189
  if (existing) return existing
231
190
  const created: Workspace = {
232
- cwd: String(cwd), sessionId, watchers: [], dirty: new Map(), seen: new Map(),
233
- timer: null, firstAt: 0, flushing: false, again: false, degraded: '',
234
- statusAt: 0, status: undefined, alignedAt: 0, alignTimer: null, requestTimer: null,
235
- startedAt: 0, gapKeys: new Set(), statusNoteAt: 0,
236
- burstAt: 0, burstCount: 0, burstMutedUntil: 0,
191
+ cwd: String(cwd), sessionId, watchers: [], dirty: new Map(), timer: null, firstAt: 0,
192
+ chain: Promise.resolve(), degraded: '', scheduled: false, syncTimer: null, gapKeys: new Set(),
237
193
  }
238
194
  spaces.set(key, created)
239
195
  return created
240
196
  }
241
197
 
198
+ /**
199
+ * @private
200
+ * @description: 把任务串到本工作区的调用链上,失败只记日志、不打断后续任务。
201
+ * @param space 工作区状态
202
+ * @param task 任务
203
+ * @returns 任务完成
204
+ */
205
+ function run(space: Workspace, task: () => Promise<void>): Promise<void> {
206
+ const next = space.chain.then(task).catch((error) => { log.warn('差异窗口跟随失败:' + String(error)) })
207
+ space.chain = next
208
+ return next
209
+ }
210
+
242
211
  /**
243
212
  * @private
244
213
  * @description: 事件分发:只收文件名,忽略目录与忽略清单。
@@ -267,17 +236,16 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
267
236
 
268
237
  /**
269
238
  * @private
270
- * @description: 开始监听;递归可用就用递归,否则逐一级子目录监听,都不可用时只留补扫。
239
+ * @description: 开始监听;递归可用就用递归,否则逐一级子目录监听,都不可用时只留校准。
271
240
  * @param space 工作区状态
272
241
  * @returns 无
273
242
  */
274
243
  function startWatch(space: Workspace): void {
275
244
  if (space.watchers.length || stopped) return
276
- space.startedAt = now()
277
245
  try {
278
246
  const watcher = watch(space.cwd, { recursive: true, persistent: false }, (_event, name) => onEvent(space, space.cwd, name))
279
247
  // EventEmitter 的 'error' 无监听者时抛出未捕获异常,必须挂处理器
280
- watcher.on('error', (error) => { log.warn('外部改动监听中断(改为只靠补扫):' + String(error)); closeWatchers(space) })
248
+ watcher.on('error', (error) => { log.warn('差异窗口监听中断(改为只靠校准):' + String(error)); closeWatchers(space) })
281
249
  space.watchers.push(watcher)
282
250
  return
283
251
  } catch (error) {
@@ -296,7 +264,7 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
296
264
  if (!space.watchers.length) space.degraded = '目录监听不可用'
297
265
  } catch (error) {
298
266
  space.degraded = '目录监听不可用:' + String(error)
299
- log.warn('外部改动监听不可用(改为只靠补扫):' + String(error))
267
+ log.warn('差异窗口监听不可用(改为只靠校准):' + String(error))
300
268
  }
301
269
  }
302
270
 
@@ -324,30 +292,12 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
324
292
  * @returns 路径比较键 → 条目
325
293
  */
326
294
  function entriesOf(cwd: string): Map<string, StoredEntry> {
327
- if (deps.entries) return deps.entries(cwd)
295
+ const stored = deps.entries ? deps.entries(cwd) : loadEntries(cwd)
328
296
  const map = new Map<string, StoredEntry>()
329
- for (const stored of loadEntries(cwd)) map.set(pathKeyOf(stored.entry.id), stored)
297
+ for (const entry of stored) map.set(pathKeyOf(entry.entry.id), entry)
330
298
  return map
331
299
  }
332
300
 
333
- /**
334
- * @private
335
- * @author ddj 2026年11月25号
336
- * @description: 取某路径的最新条目:批次快照可能早于工具落库,写记录前按身份重读一条。
337
- * @param space 工作区状态
338
- * @param absolute 绝对路径
339
- * @param fallback 批次内的旧条目
340
- * @returns 最新条目(读不到时回落到旧条目)
341
- */
342
- function latestOf(space: Workspace, absolute: string, fallback: StoredEntry | undefined): StoredEntry | undefined {
343
- try {
344
- if (deps.latest) return deps.latest(space.cwd, absolute) ?? fallback
345
- return loadEntry(space.cwd, absolute) ?? fallback
346
- } catch {
347
- return fallback
348
- }
349
- }
350
-
351
301
  /**
352
302
  * @private
353
303
  * @description: 读磁盘内容;缺失返回 null,其它失败抛出(由调用点记缺口)。
@@ -365,66 +315,15 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
365
315
 
366
316
  /**
367
317
  * @private
368
- * @description: 取版本库状态(带最小间隔缓存);无 shell 或非 git/svn 时返回 null。
369
- * @param space 工作区状态
370
- * @returns 状态或 null
371
- */
372
- async function statusOf(space: Workspace): Promise<VcsStatus | null> {
373
- const at = now()
374
- if (space.status !== undefined && at - space.statusAt < VCS_STATUS_MIN_INTERVAL_MS) return space.status
375
- space.statusAt = at
376
- if (deps.status) {
377
- space.status = await deps.status(space.cwd, space.sessionId)
378
- return space.status
379
- }
380
- const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId)
381
- if (!scope) {
382
- noteStatusOnce(space, '没有 shell 能力,版本库状态不可用')
383
- space.status = null
384
- return space.status
385
- }
386
- space.status = await vcsStatus(scope.shell, space.cwd, (reason) => noteStatusOnce(space, reason))
387
- return space.status
388
- }
389
-
390
- /**
391
- * @private
392
- * @author ddj 2026-11-24
393
- * @description: 读文件修改时间(测试可注入);读不到返回 undefined。
394
- * @param space 工作区状态
395
- * @param absolute 绝对路径
396
- * @returns 毫秒时间戳或 undefined
397
- */
398
- function mtimeOf(space: Workspace, absolute: string): number | undefined {
399
- if (deps.mtime) return deps.mtime(space.cwd, absolute)
400
- try { return statSync(absolute).mtimeMs } catch { return undefined }
401
- }
402
-
403
- /**
404
- * @private
405
- * @author ddj 2026-11-24
406
- * @description: 判断文件是否在本次监听开始之后被写过:这是「拿不到版本库状态」时唯一的外部证据。
407
- * @param space 工作区状态
408
- * @param absolute 绝对路径
409
- * @returns 刚被写过返回 true
410
- */
411
- function recentlyWritten(space: Workspace, absolute: string): boolean {
412
- if (!space.startedAt) return false
413
- const mtime = mtimeOf(space, absolute)
414
- return mtime !== undefined && mtime >= space.startedAt - WATCH_SKEW_MS
415
- }
416
-
417
- /**
418
- * @private
419
- * @author ddj 2026-11-24
318
+ * @author ddj 2026年11月25号
420
319
  * @description: 同一条缺口只上报一次;去重表满了就丢最早的键,保证内存有界。
421
320
  * @param space 工作区状态
422
- * @param key 去重键
423
321
  * @param absolute 出问题的路径
424
322
  * @param message 原因
425
323
  * @returns 无
426
324
  */
427
- function noteGapOnce(space: Workspace, key: string, absolute: string, message: string): void {
325
+ function noteGapOnce(space: Workspace, absolute: string, message: string): void {
326
+ const key = absolute + '\u0000' + message
428
327
  if (space.gapKeys.has(key)) return
429
328
  if (space.gapKeys.size >= GAP_KEY_MAX) {
430
329
  const oldest = space.gapKeys.values().next().value
@@ -436,214 +335,107 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
436
335
 
437
336
  /**
438
337
  * @private
439
- * @author ddj 2026-11-24
440
- * @description: 「版本库状态不可用」按工作区节流上报,让面板能说清为什么没拦住噪声。
441
- * @param space 工作区状态
442
- * @param reason 失败原因(命令回执头 200 字)
443
- * @returns 无
444
- */
445
- function noteStatusOnce(space: Workspace, reason: string): void {
446
- const at = now()
447
- if (at - space.statusNoteAt < STATUS_NOTE_MIN_MS) return
448
- space.statusNoteAt = at
449
- noteCaptureGap(space.cwd, space.sessionId, space.cwd, '版本库状态不可用:' + reason.slice(0, 200))
450
- }
451
-
452
- /**
453
- * @private
454
- * @author ddj 2026-11-24
455
- * @description: 整文件新增的熔断:短时间成批出现「没有基线的整文件新增」时判定为批量噪声,
456
- * 静默一段时间不新建档,只留一条缺口。已有条目的更新不受影响。
457
- * @param space 工作区状态
458
- * @param absolute 触发熔断的路径
459
- * @returns 允许新建返回 true
460
- */
461
- function allowNewWholeFile(space: Workspace, absolute: string): boolean {
462
- const at = now()
463
- if (space.burstMutedUntil > at) return false
464
- if (at - space.burstAt > BURST_WINDOW_MS) {
465
- space.burstAt = at
466
- space.burstCount = 0
467
- }
468
- space.burstCount += 1
469
- if (space.burstCount <= BURST_NEW_LIMIT) return true
470
- space.burstMutedUntil = at + BURST_COOLDOWN_MS
471
- noteGapOnce(space, 'burst:' + String(space.burstMutedUntil), absolute,
472
- `短时间内新建 ${space.burstCount} 条整文件新增记录:疑似批量噪声,暂停 ${Math.round(BURST_COOLDOWN_MS / 60000)} 分钟`)
473
- return false
474
- }
475
-
476
- /**
477
- * @private
478
- * @description: 处理一个路径:判定链见文件头注释。
338
+ * @author ddj 2026年11月25号
339
+ * @description: 把一个已开窗条目与磁盘对齐:内容变了就折进窗口,没变不落库。
479
340
  * @param space 工作区状态
480
- * @param absolute 绝对路径
481
- * @param entries 本批共享的条目表
482
- * @returns 是否新增或更新了条目
341
+ * @param stored 已开窗条目
342
+ * @returns 是否折了改动
343
+ * @throws 读盘失败
483
344
  */
484
- async function handleOne(space: Workspace, absolute: string, entries: Map<string, StoredEntry>): Promise<boolean> {
485
- const key = pathKeyOf(absolute)
486
- const at = now()
487
- const content = await readOf(space.cwd, absolute)
488
- const stored = entries.get(key)
489
- const sameContent = stored !== undefined && stored.entry.newText === (content ?? '')
490
- const sameMissing = stored !== undefined && stored.flags.missing === (content === null)
491
- if (stored && sameContent && sameMissing) {
492
- space.seen.set(key, content)
493
- return false
494
- }
495
-
496
- const window = windows.windowOf(key, at)
497
- if (window === 'self') {
498
- // 插件自己刚写回(撤销/镜像写穿):内容随后会出现在条目里,这里不建新记录
499
- space.seen.set(key, content)
500
- return false
501
- }
502
- if (window === 'editor') {
503
- space.seen.set(key, content)
504
- // 编辑器保存:只推进基线;已有条目按外部改动吸收(基线不动、标分歧),不新开行
505
- if (!stored) return false
506
- const current = latestOf(space, absolute, stored)
507
- if (!current || current.entry.newText === (content ?? '')) return false
508
- deps.record(writeOf(space, absolute, current.entry.newText, content, at, 'watch', 'editor', 'known'))
509
- return true
510
- }
511
-
512
- const status = await statusOf(space)
513
- if (status && !status.entries.has(key)) {
514
- // 版本库说这个路径相对基线干净:可能是版本库同步,也可能是工具刚写完、
515
- // 而本批快照还停在上一轮(git 忽略的路径根本不出现在 status 里)。
516
- space.seen.set(key, content)
517
- if (!stored) return false
518
- const current = latestOf(space, absolute, stored)
519
- if (!current || current.entry.newText === (content ?? '')) return false
520
- deps.record(writeOf(space, absolute, current.entry.newText, content, at, 'vcs', 'vcs', 'known'))
521
- return true
522
- }
523
- // 拿不到版本库状态时,首次见到的路径必须自带证据:文件真的在监听开始之后被写过。
524
- // 否则事件多半只是读取/属性变化(整树扫描、索引器、杀软),按「整文件新增」建档会刷出幽灵差异。
525
- if (!status && !stored && !space.seen.has(key) && !recentlyWritten(space, absolute)) {
526
- noteGapOnce(space, 'absent:' + key, absolute, '无版本库状态且文件未改动,未建档')
527
- space.seen.set(key, content)
528
- return false
529
- }
530
-
531
- const before = await beforeOf(space, key, absolute, stored, status, content)
532
- if (before.text === null && content === null) {
533
- // 观察不到任何内容(既没文件也没基线):没有可审的差异
534
- space.seen.set(key, null)
535
- return false
536
- }
537
- // 没有基线的整文件新增是幽灵记录的典型形态:短时间成批出现就熔断,避免一次噪声刷满面板
538
- if (!stored && before.text === null && !allowNewWholeFile(space, absolute)) {
539
- space.seen.set(key, content)
540
- return false
541
- }
542
- deps.record(writeOf(space, absolute, before.text, content, at, 'watch',
543
- windows.inAgentWindow(at) ? 'agent' : 'external', before.kind))
544
- space.seen.set(key, content)
545
- return true
345
+ async function foldStored(space: Workspace, stored: StoredEntry): Promise<boolean> {
346
+ if (stopped || !isOpenEntry(stored.entry)) return false
347
+ const key = pathKeyOf(stored.entry.id)
348
+ // 插件自己的写回(撤销/重做):内容随后会出现在条目里,这里不折
349
+ if (windows.windowOf(key, now()) === 'self') return false
350
+ const content = await readOf(space.cwd, stored.entry.id)
351
+ const sameMissing = stored.flags.missing === (content === null)
352
+ if (sameMissing && content === stored.entry.newText) return false
353
+ const origin = windows.windowOf(key, now()) === 'editor' ? 'editor' : 'external'
354
+ return deps.fold({
355
+ cwd: space.cwd,
356
+ sessionId: space.sessionId,
357
+ path: stored.entry.path,
358
+ identity: stored.entry.id,
359
+ before: stored.entry.newText,
360
+ after: content,
361
+ now: now(),
362
+ tool: 'watch',
363
+ origin,
364
+ baseKind: 'known',
365
+ })
546
366
  }
547
367
 
548
368
  /**
549
369
  * @private
550
- * @description: 求修改前内容:已知内容 → 首次观察 → 版本库新增/基线 → 未知。
370
+ * @description: 处理本工作区的一个批次:取一批 → 读盘判定 → 落库 → 失效目录树。
551
371
  * @param space 工作区状态
552
- * @param key 路径比较键
553
- * @param absolute 绝对路径
554
- * @param stored 既有条目
555
- * @param status 版本库状态
556
- * @param content 当前内容
557
- * @returns 修改前内容与可信度
372
+ * @returns 无
558
373
  */
559
- async function beforeOf(
560
- space: Workspace, key: string, absolute: string, stored: StoredEntry | undefined,
561
- status: VcsStatus | null, content: string | null,
562
- ): Promise<{ text: string | null; kind: 'known' | 'absent' | 'vcs' | 'unknown' }> {
563
- if (stored) return { text: stored.flags.missing ? null : stored.entry.newText, kind: 'known' }
564
- if (space.seen.has(key)) {
565
- const seen = space.seen.get(key) ?? null
566
- return { text: seen, kind: seen === null ? 'absent' : 'known' }
567
- }
568
- const entry = status?.entries.get(key)
569
- if (entry?.status === 'added') return { text: null, kind: 'absent' }
570
- if (entry && content !== null) {
571
- const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId)
572
- if (scope && status) {
573
- const base = await vcsBaselineOf(scope.shell, status, absolute)
574
- if (base !== null) return { text: base, kind: 'vcs' }
374
+ function flushSpace(space: Workspace): Promise<void> {
375
+ return run(space, async () => {
376
+ if (stopped) return
377
+ space.firstAt = 0
378
+ let bytes = 0
379
+ let recorded = 0
380
+ try {
381
+ const entries = entriesOf(space.cwd)
382
+ const batch = [...space.dirty.entries()].slice(0, MAX_BATCH)
383
+ for (const [key] of batch) space.dirty.delete(key)
384
+ const ordered = batch.sort((left, right) => left[1].seq - right[1].seq)
385
+ const touched: string[] = []
386
+ for (const [, item] of ordered) {
387
+ if (stopped) break
388
+ const stored = entries.get(pathKeyOf(item.path))
389
+ // 没开窗的路径直接丢:Unity、脚本、索引器改的文件都不再产生记录
390
+ if (!stored) continue
391
+ try {
392
+ const size = item.path.length
393
+ if (bytes + size > MAX_FLUSH_BYTES) { space.dirty.set(pathKeyOf(item.path), item); continue }
394
+ bytes += size
395
+ if (await foldStored(space, stored)) { recorded += 1; touched.push(item.path) }
396
+ } catch (error) {
397
+ noteGapOnce(space, item.path, String(error))
398
+ log.debug('差异窗口跳过:' + item.path + ': ' + String(error))
399
+ }
400
+ }
401
+ for (const path of touched) invalidateIndex(deps.ctx, space.cwd, path)
402
+ if (recorded) log.debug(`差异窗口折入 ${recorded} 条(${space.cwd})`)
403
+ } finally {
404
+ if (space.dirty.size) schedule(space)
575
405
  }
576
- }
577
- return { text: null, kind: 'unknown' }
406
+ })
578
407
  }
579
408
 
580
409
  /**
581
410
  * @private
582
- * @description: 组装一条待审写入(watch 通道)。
583
- * @param space 工作区状态
584
- * @param absolute 绝对路径
585
- * @param before 修改前内容
586
- * @param after 当前内容
587
- * @param at 时间
588
- * @param source 采集通道
589
- * @param origin 归属
590
- * @param baseKind 基线可信度
591
- * @returns 待审写入
592
- */
593
- function writeOf(
594
- space: Workspace, absolute: string, before: string | null, after: string | null, at: number,
595
- source: 'watch' | 'vcs', origin: 'agent' | 'editor' | 'vcs' | 'external',
596
- baseKind: 'known' | 'absent' | 'vcs' | 'unknown',
597
- ): PendingWrite {
598
- return {
599
- cwd: space.cwd, sessionId: space.sessionId, path: absolute, identity: absolute,
600
- before, after, now: at, tool: source, origin, baseKind,
601
- }
602
- }
603
-
604
- /**
605
- * @private
606
- * @description: 处理本工作区的一个批次:取一批 → 读盘判定 → 落库 → 失效目录树。
411
+ * @author ddj 2026年11月25号
412
+ * @description: 从磁盘校准所有开窗文件:补启动前/离线期间漏掉的事件。
607
413
  * @param space 工作区状态
608
- * @returns 无
414
+ * @returns 校准结果
609
415
  */
610
- async function flushSpace(space: Workspace): Promise<void> {
611
- if (stopped) return
612
- if (space.flushing) { space.again = true; return }
613
- space.flushing = true
614
- space.firstAt = 0
615
- let bytes = 0
616
- let recorded = 0
617
- try {
416
+ async function syncWorkspace(space: Workspace): Promise<SyncOutcome> {
417
+ const outcome: SyncOutcome = { checked: 0, folded: 0, gaps: [] }
418
+ await run(space, async () => {
419
+ if (stopped) return
618
420
  const entries = entriesOf(space.cwd)
619
- const batch = [...space.dirty.entries()].slice(0, MAX_BATCH)
620
- for (const [key] of batch) space.dirty.delete(key)
621
- const ordered = batch.sort((left, right) => left[1].seq - right[1].seq)
622
- const touched: string[] = []
623
- for (const [, item] of ordered) {
421
+ const open = [...entries.values()].filter((stored) => isOpenEntry(stored.entry)).slice(0, SYNC_MAX)
422
+ let bytes = 0
423
+ for (const stored of open) {
624
424
  if (stopped) break
425
+ outcome.checked += 1
426
+ const size = stored.entry.newText.length
427
+ if (bytes + size > MAX_FLUSH_BYTES) break
428
+ bytes += size
625
429
  try {
626
- const size = item.path.length
627
- if (bytes + size > MAX_FLUSH_BYTES) { space.dirty.set(pathKeyOf(item.path), item); continue }
628
- bytes += size
629
- if (await handleOne(space, item.path, entries)) { recorded += 1; touched.push(item.path) }
430
+ if (await foldStored(space, stored)) outcome.folded += 1
630
431
  } catch (error) {
631
- noteCaptureGap(space.cwd, space.sessionId, item.path, error)
632
- log.debug('外部改动跳过:' + item.path + ': ' + String(error))
432
+ const message = stored.entry.path + ': ' + String(error)
433
+ outcome.gaps.push(message)
434
+ noteGapOnce(space, stored.entry.path, String(error))
633
435
  }
634
436
  }
635
- for (const path of touched) invalidateIndex(deps.ctx, space.cwd, path)
636
- if (recorded) log.debug(`外部改动记录 ${recorded} 条(${space.cwd})`)
637
- } catch (error) {
638
- log.warn('外部改动处理失败:' + String(error))
639
- } finally {
640
- space.flushing = false
641
- if (space.seen.size > SEEN_MAX) {
642
- for (const key of [...space.seen.keys()].slice(0, space.seen.size - SEEN_MAX)) space.seen.delete(key)
643
- }
644
- if (space.dirty.size) schedule(space)
645
- else if (space.again) { space.again = false; schedule(space) }
646
- }
437
+ })
438
+ return outcome
647
439
  }
648
440
 
649
441
  /**
@@ -666,15 +458,20 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
666
458
  ensure(cwd: string, sessionId: string): void {
667
459
  if (stopped || !cwd) return
668
460
  const space = spaceOf(cwd, sessionId)
669
- if (!deps.settings().watch) return
670
- startWatch(space)
671
- // 启动对齐:后台跑一次补扫,把 watch 启动之前漏掉的改动补录进来
672
- if (!deps.settings().scan || space.alignedAt) return
673
- space.alignedAt = now()
674
- const timer = setTimeout(() => { void alignNow(space) }, 0)
461
+ if (deps.settings().watch) startWatch(space)
462
+ if (!deps.settings().scan || space.scheduled) return
463
+ space.scheduled = true
464
+ // 启动校准:重启后把窗口内离线期间的改动补齐
465
+ const timer = setTimeout(() => { void syncWorkspace(space) }, 0)
675
466
  if (typeof timer.unref === 'function') timer.unref()
676
- if (!space.alignTimer) space.alignTimer = setInterval(() => { void alignNow(space) }, ALIGN_INTERVAL_MS)
677
- if (typeof space.alignTimer.unref === 'function') space.alignTimer.unref()
467
+ if (!space.syncTimer) {
468
+ space.syncTimer = setInterval(() => { void syncWorkspace(space) }, SYNC_INTERVAL_MS)
469
+ if (typeof space.syncTimer.unref === 'function') space.syncTimer.unref()
470
+ }
471
+ },
472
+ sync(cwd: string): Promise<SyncOutcome> {
473
+ if (stopped || !cwd) return Promise.resolve({ checked: 0, folded: 0, gaps: [] })
474
+ return syncWorkspace(spaceOf(cwd, ''))
678
475
  },
679
476
  dismiss(cwd: string): void {
680
477
  const key = pathKeyOf(cwd)
@@ -682,23 +479,9 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
682
479
  if (!space) return
683
480
  closeWatchers(space)
684
481
  if (space.timer) clearTimeout(space.timer)
685
- if (space.requestTimer) clearTimeout(space.requestTimer)
686
- if (space.alignTimer) clearInterval(space.alignTimer)
482
+ if (space.syncTimer) clearInterval(space.syncTimer)
687
483
  spaces.delete(key)
688
484
  },
689
- requestAlign(cwd: string, delayMs = ALIGN_AFTER_VCS_MS): void {
690
- // 版本库写命令和手动按钮共用:同工作区在延迟窗内只跑一次补扫
691
- if (stopped || !cwd || !deps.settings().scan) return
692
- const space = spaces.get(pathKeyOf(cwd))
693
- if (!space) return
694
- if (space.requestTimer) clearTimeout(space.requestTimer)
695
- const timer = setTimeout(() => {
696
- space.requestTimer = null
697
- void alignNow(space)
698
- }, Math.max(0, delayMs))
699
- if (typeof timer.unref === 'function') timer.unref()
700
- space.requestTimer = timer
701
- },
702
485
  enqueue(cwd: string, absolute: string): void {
703
486
  enqueue(cwd, absolute)
704
487
  },
@@ -707,6 +490,7 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
707
490
  if (cwd && key !== pathKeyOf(cwd)) continue
708
491
  if (space.timer) { clearTimeout(space.timer); space.timer = null }
709
492
  await flushSpace(space)
493
+ await space.chain
710
494
  }
711
495
  },
712
496
  dispose(): void {
@@ -714,31 +498,41 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
714
498
  for (const space of spaces.values()) {
715
499
  closeWatchers(space)
716
500
  if (space.timer) clearTimeout(space.timer)
717
- if (space.alignTimer) clearInterval(space.alignTimer)
501
+ if (space.syncTimer) clearInterval(space.syncTimer)
718
502
  space.dirty.clear()
719
- space.seen.clear()
503
+ space.gapKeys.clear()
720
504
  }
721
505
  spaces.clear()
722
506
  },
723
507
  }
508
+ }
724
509
 
725
- /**
726
- * @private
727
- * @description: 后台补扫一次(复用 externalAlign 的候选与预算)。
728
- * @param space 工作区状态
729
- * @returns 无
730
- */
731
- async function alignNow(space: Workspace): Promise<void> {
732
- if (stopped || !deps.settings().scan) return
733
- try {
734
- if (deps.align) { await deps.align(space.cwd, space.sessionId); return }
735
- const { alignInWorkspace } = await import('./externalAlign.js')
736
- const outcome = await alignInWorkspace(deps.ctx, space.cwd, space.sessionId, deps.record)
737
- if (outcome.gaps.length) log.debug('补扫缺口:' + outcome.gaps.join(';'))
738
- } catch (error) {
739
- log.debug('后台补扫失败:' + String(error))
740
- }
741
- }
510
+ // --endregion
511
+
512
+ // --region 装配入口
513
+
514
+ /** 当前装配的跟随器实例:RPC 的「校准一次」经它执行,避免再实现一套读盘逻辑。 */
515
+ let activeCapture: ExternalCapture | undefined
516
+
517
+ /**
518
+ * @author ddj 2026年11月25号
519
+ * @description: 登记当前跟随器;卸载时传 undefined,避免 RPC 打到旧实例。
520
+ * @param instance 跟随器实例
521
+ * @returns 无
522
+ */
523
+ export function setCapture(instance: ExternalCapture | undefined): void {
524
+ activeCapture = instance
525
+ }
526
+
527
+ /**
528
+ * @author ddj 2026年11月25号
529
+ * @description: 从 RPC 侧触发一次校准:只对齐开窗文件,不建任何新记录。
530
+ * @param cwd 工作区
531
+ * @returns 校准结果
532
+ */
533
+ export async function captureSync(cwd: string): Promise<SyncOutcome> {
534
+ if (!activeCapture) return { checked: 0, folded: 0, gaps: ['差异窗口跟随器未装配'] }
535
+ return activeCapture.sync(cwd)
742
536
  }
743
537
 
744
538
  // --endregion