dsh-vscode-mode 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +32 -4
  2. package/lib/client.js +68 -65
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +1961 -222
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +1 -1
  8. package/src/archivePurge.ts +411 -0
  9. package/src/client/addToConversation.ts +77 -18
  10. package/src/client/htmlPlan/HtmlPlanPanel.ts +9 -13
  11. package/src/client/htmlPlan/planActions.ts +97 -23
  12. package/src/client/htmlPlan/planPage.ts +2 -2
  13. package/src/client/reviewBatch.ts +48 -1
  14. package/src/client/state/diffSummary.ts +2 -1
  15. package/src/client/styles/editor.css +3 -1
  16. package/src/client/ui/EditorView.ts +8 -9
  17. package/src/client/ui/SvnCommitDialog.ts +256 -31
  18. package/src/client/ui/svnCommitModel.ts +63 -0
  19. package/src/index.ts +13 -0
  20. package/src/pending/capture.ts +201 -34
  21. package/src/pending/decide.ts +33 -1
  22. package/src/pending/externalCapture.ts +171 -8
  23. package/src/pending/kernel.ts +13 -2
  24. package/src/pending/noteTool.ts +96 -0
  25. package/src/pending/notes.ts +83 -0
  26. package/src/pending/persist.ts +301 -51
  27. package/src/pending/provenance.ts +45 -11
  28. package/src/pending/receipt.ts +177 -0
  29. package/src/pending/store.ts +161 -69
  30. package/src/pending/vcs.ts +25 -7
  31. package/src/pending/verdict.ts +170 -0
  32. package/src/pendingCompat.ts +14 -1
  33. package/src/pendingRpc.ts +19 -1
  34. package/src/reviewDb.ts +63 -2
  35. package/src/reviewRpc.ts +47 -1
  36. package/src/rpc.ts +36 -4
  37. package/src/shared/pendingReview.ts +20 -2
  38. package/src/shared/review.ts +17 -0
  39. package/src/shared/reviewRegions.ts +48 -3
  40. package/src/shared/rpc.ts +7 -1
  41. package/src/slowLog.ts +74 -0
  42. package/src/textEncoding.probe.ts +1 -0
@@ -2,6 +2,7 @@
2
2
  * 待审差异采集:环绕一次文件写入读取真实前后内容,只有内容确实变化才落库。
3
3
  * @author ddj 2026年10月29号
4
4
  */
5
+ import { createHash } from 'node:crypto'
5
6
  import { cwdOfSession } from '../store.js'
6
7
  import type { Ctx } from '../store.js'
7
8
  import { log } from '../log.js'
@@ -9,7 +10,10 @@ import { toolTargets, patchDiagnostics, OPS_PREFIX } from '../toolTargets.js'
9
10
  import { replaceCandidates, BULK_LIMIT } from './bulkTargets.js'
10
11
  import type { BulkSearcher } from './bulkTargets.js'
11
12
  import { rawText, rawReviewFile } from '../reviewEvidence.js'
12
- import type { PendingBaseKind, PendingOrigin } from '../shared/pendingReview.js'
13
+ import type { PendingBaseKind, PendingEvidence, PendingOrigin, PendingVerdict } from '../shared/pendingReview.js'
14
+ import { receiptsOf } from './receipt.js'
15
+ import type { ToolReceipt } from './receipt.js'
16
+ import { verdictOf } from './verdict.js'
13
17
 
14
18
  /** 可被采信为待审来源的写文件工具(含 dsh-ops 的单目标写工具)。 */
15
19
  const WRITE_TOOLS = [
@@ -67,6 +71,10 @@ export interface PendingWrite {
67
71
  origin?: PendingOrigin
68
72
  /** 修改前内容的可信度(外部采集用);缺省按 before 是否为空推断。 */
69
73
  baseKind?: PendingBaseKind
74
+ /** 证据强度;缺省按快照处理。 */
75
+ evidence?: PendingEvidence
76
+ /** 这次调用的结局;缺省按 changed 处理。 */
77
+ verdict?: PendingVerdict
70
78
  }
71
79
 
72
80
  /** 采集器。 */
@@ -121,10 +129,12 @@ export function installPending(
121
129
 
122
130
  /**
123
131
  * @author ddj 2026年10月30号
124
- * @description: 判定本次调用是否值得采集;不值得时返回 null,调用方直接透传原始分发。
125
- * @param ctx Host 生命周期
132
+ * @description: 判定本次调用是否值得采集并冻结写前基线;同目标并发调用改记「无基线」,
133
+ * 交给工具回执补前像,不再整次丢弃。
134
+ * @param scope 工作区作用域
126
135
  * @param state 采集状态
127
- * @param exec 工具分发上下文
136
+ * @param requested 目标路径
137
+ * @param tool 工具名
128
138
  * @returns 采集计划或 null
129
139
  */
130
140
  async function planOf(scope: { cwd: string; sessionId: string; fs: any }, state: CaptureState, requested: string, tool: string): Promise<CapturePlan | null> {
@@ -132,15 +142,17 @@ async function planOf(scope: { cwd: string; sessionId: string; fs: any }, state:
132
142
  if (state.stopped || state.disposed.has(sessionId)) return null
133
143
  const target = await fs.resolve(requested, { cwd })
134
144
  const identity = fs.processPath(target)
135
- if (state.stopped || state.disposed.has(sessionId) || typeof identity !== 'string' || !identity || state.busy.has(identity)) return null
145
+ if (state.stopped || state.disposed.has(sessionId) || typeof identity !== 'string' || !identity) return null
146
+ const base = { cwd: String(cwd), sessionId, path: requested, identity, target, fs, tool }
147
+ if (state.busy.has(identity)) return { ...base, before: undefined, hashBefore: null, held: false }
136
148
  state.busy.add(identity)
137
149
  try {
138
- const before = await readText(fs, target)
139
- if (state.stopped || state.disposed.has(sessionId) || (before !== null && before.length > MAX_TEXT)) {
150
+ const snapshot = await readSnapshot(fs, target)
151
+ if (state.stopped || state.disposed.has(sessionId) || (snapshot.text !== null && snapshot.text.length > MAX_TEXT)) {
140
152
  state.busy.delete(identity)
141
153
  return null
142
154
  }
143
- return { cwd: String(cwd), sessionId, path: requested, identity, before, target, fs, tool }
155
+ return { ...base, before: snapshot.text, hashBefore: snapshot.hash, held: true }
144
156
  } catch (error) {
145
157
  state.busy.delete(identity)
146
158
  throw error
@@ -153,7 +165,12 @@ interface CapturePlan {
153
165
  sessionId: string
154
166
  path: string
155
167
  identity: string
156
- before: string | null
168
+ /** 写前原始文本;undefined = 同目标并发占用,没取到基线。 */
169
+ before: string | null | undefined
170
+ /** 写前原始字节的 SHA-256;没有基线时为 null。 */
171
+ hashBefore: string | null
172
+ /** 本次计划是否占住 busy;只有占住的一方负责释放。 */
173
+ held: boolean
157
174
  target: unknown
158
175
  fs: any
159
176
  /** 触发本次写入的工具名,用于记录采集通道。 */
@@ -268,9 +285,18 @@ async function buildPlans(
268
285
  return plans
269
286
  }
270
287
 
288
+ /** 上报阶段共享的调用事实。 */
289
+ interface WriteContext {
290
+ scope: { cwd: string; sessionId: string; fs: any }
291
+ exec: WriteExec
292
+ isError: boolean
293
+ receipts: Map<string, ToolReceipt>
294
+ }
295
+
271
296
  /**
272
- * @author ddj 2026年10月30号
273
- * @description: 写工具执行前后各读一次,内容变化才上报;任何采集异常都不改变工具结果。
297
+ * @author ddj 2026年10月30号 / 2026年11月25号
298
+ * @description: 写工具执行前后各读一次,并用工具自己的回执对账;只有确认变化的调用才上报。
299
+ * 任何采集异常都不改变工具结果。
274
300
  * @param ctx Host 生命周期
275
301
  * @param state 采集状态
276
302
  * @param sink 已确认写入的接收方
@@ -306,45 +332,157 @@ async function aroundTool(
306
332
  }
307
333
  const plans = await buildPlans(scope, state, exec, targets.paths)
308
334
 
335
+ let result: unknown
336
+ let failed: unknown
309
337
  try {
310
- const result = await next()
338
+ result = await next()
311
339
  if (bulk && !state.stopped && !state.disposed.has(scope.sessionId)) await reconcileBulk(scope, exec, result, plans)
312
340
  if (name === 'apply_patch' && !state.stopped && !state.disposed.has(scope.sessionId)) {
313
341
  for (const diagnostic of patchDiagnostics(result)) recordGap(scope, exec, 'apply_patch', diagnostic)
314
342
  }
315
343
  return result
344
+ } catch (error) {
345
+ failed = error
346
+ throw error
316
347
  } finally {
317
- for (const plan of plans) {
318
- try { await reportWrite(state, sink, plan) }
319
- catch (error) { if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, plan.path, error); log.debug('待审上报失败:' + String(error)) }
320
- finally { state.busy.delete(plan.identity) }
348
+ await settle(scope, state, sink, exec, plans, result, failed)
349
+ }
350
+ }
351
+
352
+ /**
353
+ * @private
354
+ * @author ddj 2026年11月25号
355
+ * @description: 解析回执并逐条收尾;单条失败只记缺口,绝不改变工具结果与 busy 释放。
356
+ * @param scope 工作区作用域
357
+ * @param state 采集状态
358
+ * @param sink 已确认写入的接收方
359
+ * @param exec 工具分发上下文
360
+ * @param plans 写前冻结的采集计划
361
+ * @param result 工具结果
362
+ * @param failure 工具抛出的错误(没有则 undefined)
363
+ * @returns 无
364
+ */
365
+ async function settle(
366
+ scope: { cwd: string; sessionId: string; fs: any }, state: CaptureState, sink: (write: PendingWrite) => void,
367
+ exec: WriteExec, plans: CapturePlan[], result: unknown, failure: unknown,
368
+ ): Promise<void> {
369
+ const flagError = Boolean((result as { isError?: unknown } | undefined)?.isError)
370
+ const context: WriteContext = {
371
+ scope, exec, isError: failure !== undefined || flagError, receipts: await receiptsFor(scope, exec, result),
372
+ }
373
+ for (const plan of plans) {
374
+ try {
375
+ await reportWrite(state, sink, plan, context)
376
+ } catch (error) {
377
+ if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, plan.path, error)
378
+ log.debug('待审上报失败:' + String(error))
379
+ } finally {
380
+ if (plan.held) state.busy.delete(plan.identity)
321
381
  }
322
382
  }
323
383
  }
324
384
 
325
385
  /**
326
- * @author ddj 2026年11月04号
327
- * @description: 固定目标写后读回;内容一致不产生条目,卸载后不再上报。
386
+ * @private
387
+ * @author ddj 2026年11月25号
388
+ * @description: 把回执里的路径解析成条目身份;解析不了的回执丢弃,退回快照判定。
389
+ * @param scope 工作区作用域
390
+ * @param exec 工具分发上下文
391
+ * @param result 工具结果
392
+ * @returns 身份 → 回执
393
+ */
394
+ async function receiptsFor(
395
+ scope: { cwd: string; sessionId: string; fs: any }, exec: WriteExec, result: unknown,
396
+ ): Promise<Map<string, ToolReceipt>> {
397
+ const map = new Map<string, ToolReceipt>()
398
+ if (result === undefined) return map
399
+ let receipts: ToolReceipt[]
400
+ try {
401
+ receipts = receiptsOf(String(exec.name), result, Boolean((result as { isError?: unknown }).isError))
402
+ } catch {
403
+ return map
404
+ }
405
+ for (const receipt of receipts) {
406
+ try {
407
+ const target = await scope.fs.resolve(receipt.path, { cwd: scope.cwd })
408
+ const identity = scope.fs.processPath(target)
409
+ if (typeof identity === 'string' && identity) map.set(identity, receipt)
410
+ } catch {
411
+ log.debug('回执路径不可解析:' + receipt.path)
412
+ }
413
+ }
414
+ return map
415
+ }
416
+
417
+ /**
418
+ * @private
419
+ * @author ddj 2026年11月25号
420
+ * @description: 该路径的旧缺口在本次写入被正式采用后清掉,避免缺口里留着已解决的原因。
421
+ * @param plan 采集计划
422
+ * @returns 无
423
+ */
424
+ function clearGapsOf(plan: CapturePlan): void {
425
+ for (const [key, gap] of captureGaps) {
426
+ const identity = JSON.parse(key) as unknown[]
427
+ if (gap.cwd === plan.cwd && gap.sessionId === plan.sessionId && identity[3] === plan.path) captureGaps.delete(key)
428
+ }
429
+ }
430
+
431
+ /**
432
+ * @author ddj 2026年11月04号 / 2026年11月25号
433
+ * @description: 固定目标写后读回并按回执判定;不一致只记缺口,未确认变化一律不建条目。
328
434
  * @param state 采集生命周期状态
329
435
  * @param sink 已确认写入的接收方
330
436
  * @param plan 采集计划
437
+ * @param context 本次调用的事实
331
438
  * @returns 无;读回失败只记日志
332
439
  */
333
- async function reportWrite(state: CaptureState, sink: (write: PendingWrite) => void, plan: CapturePlan): Promise<void> {
440
+ async function reportWrite(
441
+ state: CaptureState, sink: (write: PendingWrite) => void, plan: CapturePlan, context: WriteContext,
442
+ ): Promise<void> {
334
443
  if (state.stopped || state.disposed.has(plan.sessionId)) return
444
+ const receipt = context.receipts.get(plan.identity)
445
+ // 没有基线也没有回执:这次调用改了什么无从判断,跳过(与旧行为一致,不造条目)。
446
+ if (plan.before === undefined && !receipt) {
447
+ log.debug('同目标并发写入且没有回执,跳过该次采集:' + plan.path)
448
+ return
449
+ }
335
450
  // 目录、provider 和目标均在写前冻结,切目录或卸载不能将内容串到其他工作区。
336
- const after = await readText(plan.fs, plan.target)
451
+ const after = await readSnapshot(plan.fs, plan.target)
337
452
  if (state.stopped || state.disposed.has(plan.sessionId)) return
338
- if (after !== null && after.length > MAX_TEXT) throw new Error('capture text budget exceeded')
339
- for (const [key, gap] of captureGaps) {
340
- const identity = JSON.parse(key) as unknown[]
341
- if (gap.cwd === plan.cwd && gap.sessionId === plan.sessionId && identity[3] === plan.path) captureGaps.delete(key)
453
+ if (after.text !== null && after.text.length > MAX_TEXT) throw new Error('capture text budget exceeded')
454
+ clearGapsOf(plan)
455
+
456
+ const judged = verdictOf({
457
+ receipt, isError: context.isError, hasBaseline: plan.before !== undefined,
458
+ beforeRead: plan.before ?? null, afterRead: after.text,
459
+ hashBefore: plan.hashBefore, hashAfter: after.hash,
460
+ })
461
+ if (judged.verdict === 'unverified') {
462
+ recordGap(context.scope, context.exec, plan.path, '回执与磁盘不一致,未记录该次调用:' + judged.reason)
463
+ return
342
464
  }
343
- if (plan.before === after) return
344
- sink({
465
+ if (judged.verdict !== 'changed') {
466
+ // 没记成条目却看到磁盘变了:可能是部分写入,也可能是别人写的,都不能冒充本次差异。
467
+ if (plan.before !== undefined && plan.before !== after.text) {
468
+ const reason = judged.verdict === 'failed'
469
+ ? '工具报错后文件内容发生变化,无法判断是否本次写入:'
470
+ : '回执声明没有变化但磁盘内容变了,未记录该次调用:'
471
+ recordGap(context.scope, context.exec, plan.path, reason + judged.reason)
472
+ }
473
+ return
474
+ }
475
+
476
+ // 没取到基线时用回执的前像补,条目会标成归一基线,撤销前必须确认。
477
+ const before = plan.before === undefined ? (receipt?.before ?? null) : plan.before
478
+ if (before === after.text) return
479
+ const write: PendingWrite = {
345
480
  cwd: plan.cwd, sessionId: plan.sessionId, path: plan.path, identity: plan.identity,
346
- before: plan.before, after, now: Date.now(), tool: plan.tool,
347
- })
481
+ before, after: after.text, now: Date.now(), tool: plan.tool,
482
+ evidence: judged.evidence, verdict: judged.verdict,
483
+ }
484
+ if (plan.before === undefined && judged.evidence === 'authoritative') write.baseKind = 'normalized'
485
+ sink(write)
348
486
  }
349
487
 
350
488
  /**
@@ -354,15 +492,44 @@ async function reportWrite(state: CaptureState, sink: (write: PendingWrite) => v
354
492
  * @param target 目标
355
493
  * @returns 文本或 null
356
494
  */
357
- export async function readText(fs: any, target: any, signal?: AbortSignal): Promise<string | null> {
495
+ /** 一次读盘的原始快照:文本用于写回,哈希用于与工具回执对账。 */
496
+ export interface TextSnapshot {
497
+ /** 原始文本;null = 文件不存在。 */
498
+ text: string | null
499
+ /** 原始字节的 SHA-256;文件不存在时为 null。 */
500
+ hash: string | null
501
+ }
502
+
503
+ /**
504
+ * @author ddj 2026年10月29号 / 2026年11月25号
505
+ * @description: 读原始字节并同时给出文本与 sha256;只有明确缺失返回空,不可读或超限保留失败语义。
506
+ * @param fs 文件系统
507
+ * @param target 目标
508
+ * @param signal 取消信号
509
+ * @returns 文本与哈希
510
+ */
511
+ export async function readSnapshot(fs: any, target: any, signal?: AbortSignal): Promise<TextSnapshot> {
358
512
  try {
359
- if (typeof fs.readBytes === 'function') {
360
- return rawText(rawReviewFile(await fs.readBytes(target, signal, MAX_TEXT)))
361
- }
362
- throw new Error('Raw byte capture unavailable')
513
+ if (typeof fs.readBytes !== 'function') throw new Error('Raw byte capture unavailable')
514
+ const bytes = await fs.readBytes(target, signal, MAX_TEXT)
515
+ if (bytes === null || bytes === undefined) return { text: null, hash: null }
516
+ const payload = Buffer.from(bytes)
517
+ return { text: rawText(rawReviewFile(payload)), hash: createHash('sha256').update(payload).digest('hex') }
363
518
  } catch (error) {
364
519
  const code = (error as { code?: string }).code
365
- if (code === 'ENOENT' || code === 'FS_NOT_FOUND') return null
520
+ if (code === 'ENOENT' || code === 'FS_NOT_FOUND') return { text: null, hash: null }
366
521
  throw error
367
522
  }
368
523
  }
524
+
525
+ /**
526
+ * @author ddj 2026年10月29号
527
+ * @description: 读取全文;只有明确缺失返回 null,不可读或超限错误保留失败语义。
528
+ * @param fs 文件系统
529
+ * @param target 目标
530
+ * @param signal 取消信号
531
+ * @returns 文本或 null
532
+ */
533
+ export async function readText(fs: any, target: any, signal?: AbortSignal): Promise<string | null> {
534
+ return (await readSnapshot(fs, target, signal)).text
535
+ }
@@ -161,7 +161,7 @@ function pickBlocks(blocks: ReviewBlock[], input: DecideInput): ReviewBlock[] |
161
161
  const scope = input.request.scope
162
162
  if (scope === 'file' || scope === 'all') return []
163
163
  if (scope === 'block') {
164
- const block = blocks.find((item) => item.id === input.request.blockId)
164
+ const block = findBlock(blocks, input.request.blockId)
165
165
  return block ? [block] : null
166
166
  }
167
167
  const start = input.request.startLine ?? 0
@@ -169,6 +169,32 @@ function pickBlocks(blocks: ReviewBlock[], input: DecideInput): ReviewBlock[] |
169
169
  return blocks.filter((block) => block.newStart <= end && block.newStart + Math.max(block.newLines.length, 1) >= start)
170
170
  }
171
171
 
172
+ /**
173
+ * @private
174
+ * @author ddj 2026年11月25号
175
+ * @description: 按 id 找块,找不到再按内容指纹、最后按旧坐标 id 兜底。
176
+ * 块身份现在是内容指纹,上游行号飘动不会让同一个块换名;旧客户端发来的
177
+ * `hunkIndex:oldLine:newLine` 仍按行号唯一匹配。
178
+ * @param blocks 当前差异块
179
+ * @param blockId 请求里的块 id
180
+ * @returns 唯一命中的块,找不到或不唯一时 undefined
181
+ */
182
+ function findBlock(blocks: ReviewBlock[], blockId: string | undefined): ReviewBlock | undefined {
183
+ if (!blockId) return undefined
184
+ const exact = blocks.find((block) => block.id === blockId)
185
+ if (exact) return exact
186
+ const fingerprint = blockId.split(':')[1]
187
+ if (fingerprint !== undefined && fingerprint !== '') {
188
+ const byFingerprint = blocks.filter((block) => block.id.split(':')[1] === fingerprint)
189
+ if (byFingerprint.length === 1) return byFingerprint[0]
190
+ }
191
+ const legacy = /^(\d+):(\d+):(\d+)$/.exec(blockId)
192
+ if (!legacy) return undefined
193
+ const byCoordinate = blocks.filter((block) => block.hunkIndex === Number(legacy[1])
194
+ && block.oldStart === Number(legacy[2]) && block.newStart === Number(legacy[3]))
195
+ return byCoordinate.length === 1 ? byCoordinate[0] : undefined
196
+ }
197
+
172
198
  /**
173
199
  * @author ddj 2026年10月29号
174
200
  * @description: 把目标块标记为已决定;整文件时把全部块一起标记。
@@ -201,6 +227,12 @@ export function capabilityOf(entry: PendingEntry, flags: PendingFlags): { keep:
201
227
  if (entry.baseKind === 'unknown') {
202
228
  return { keep: true, revert: false, reason: '未捕获修改前内容(外部写入):留档可见,但不能撤销,否则会删掉现有代码' }
203
229
  }
230
+ if (entry.baseKind === 'normalized') {
231
+ return {
232
+ keep: true, revert: true, confirmRevert: true,
233
+ reason: '基线与行尾已归一(来自工具回执):撤销会按归一文本写回,写前请确认',
234
+ }
235
+ }
204
236
  if (entry.earlierVersion === 'none' && entry.newText.length === 0) {
205
237
  return { keep: true, revert: false, reason: 'empty-create' }
206
238
  }
@@ -7,13 +7,16 @@
7
7
  * MAX_BATCH 个文件、MAX_FLUSH_BYTES 字节,其余留到下一轮。批量按**入队顺序**处理,不按 mtime:
8
8
  * 同一毫秒内的多次写入 mtime 相同,用它排序反而可能造出倒序 diff。
9
9
  * - 判定顺序固定:已知内容未变 → 跳过;插件自写窗口 → 跳过;编辑器保存窗口 → 只推进基线;
10
- * 版本库说干净 → 跳过或标成版本库同步;其余按窗口判定归属后落库。绝不按时间戳猜重复。
10
+ * 版本库说干净 → 跳过或标成版本库同步;拿不到版本库状态且是首次见到的路径 → 必须自带 mtime 证据
11
+ * (文件确实在监听开始之后被写过),否则只记缺口不建档;整文件新增短时间成批出现 → 熔断静默一段时间。
12
+ * 写记录前按身份重读一次条目:本批快照可能早于工具落库,不重读就会把工具写入再记成版本库同步。
13
+ * 其余按窗口判定归属后落库。绝不按时间戳猜重复,也绝不把「被读过」当成「被改过」。
11
14
  * - 递归监听不可用(Linux)时降级为逐子目录非递归监听;仍不可用就只靠补扫,并把原因写进缺口。
12
15
  * - 读盘一律走待审采集的严格 UTF-8 往返:二进制、GBK 等无法字节往返的内容不落记录(记缺口),
13
16
  * 绝不因为"分析"而改写任何字节。
14
17
  * 作者 ddj 2026-11-24
15
18
  */
16
- import { readdirSync, watch } from 'node:fs'
19
+ import { readdirSync, statSync, watch } from 'node:fs'
17
20
  import type { FSWatcher } from 'node:fs'
18
21
  import { join, resolve } from 'node:path'
19
22
  import type { Ctx } from '../store.js'
@@ -21,7 +24,7 @@ import { log } from '../log.js'
21
24
  import type { PendingWrite } from './capture.js'
22
25
  import { noteCaptureGap, readText } from './capture.js'
23
26
  import type { StoredEntry } from './persist.js'
24
- import { loadEntries } from './persist.js'
27
+ import { loadEntries, loadEntry } from './persist.js'
25
28
  import { FILE_EXCLUDES, EXCLUDES } from '../search/ripgrep.js'
26
29
  import { pathKeyOf, windows } from './provenance.js'
27
30
  import type { VcsStatus } from './vcs.js'
@@ -51,6 +54,18 @@ export const SEEN_MAX = 5000
51
54
  export const ALIGN_INTERVAL_MS = 10 * 60_000
52
55
  /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
53
56
  export const ALIGN_AFTER_VCS_MS = 1500
57
+ /** 每个工作区最多记住多少条「已上报过的缺口」,防止事件风暴把去重表撑大。 */
58
+ 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
54
69
 
55
70
  /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
56
71
  export const VCS_WRITE_METHODS = new Set([
@@ -63,7 +78,11 @@ export const VCS_WRITE_TOOLS = new Set([
63
78
  'svn_propset', 'svn_propdel', 'svn_changelist', 'remote_ssh_write',
64
79
  ])
65
80
 
66
- /** 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。 */
81
+ /**
82
+ * 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。
83
+ * 只收版本库元数据、Unity 缓存与构建产物:第三方与代码生成目录不在忽略之列,
84
+ * 它们的改动靠「mtime 证据 + 版本库状态」两道闸门拦,而不是按目录名一刀切。
85
+ */
67
86
  export const EXTRA_IGNORE_SEGMENTS = ['.svn', '.hg', '.p4config', 'Library', 'Temp', 'obj', 'Logs']
68
87
 
69
88
  /** 忽略集合:目录段 + 文件名模式。 */
@@ -127,6 +146,10 @@ export interface ExternalCaptureDeps {
127
146
  status?(cwd: string, sessionId: string): Promise<VcsStatus | null>
128
147
  /** 覆盖补扫执行(测试注入);缺省调用 alignInWorkspace。 */
129
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
130
153
  now?(): number
131
154
  }
132
155
 
@@ -164,6 +187,17 @@ interface Workspace {
164
187
  alignTimer: ReturnType<typeof setTimeout> | null
165
188
  /** 延后补扫的定时器(版本库命令后/手动按钮,同一工作区合并一次)。 */
166
189
  requestTimer: ReturnType<typeof setTimeout> | null
190
+ /** 本次监听的起始时刻:文件 mtime 不比它新,就不是「刚被写过」。 */
191
+ startedAt: number
192
+ /** 已上报过的缺口键(同路径/同原因只报一次)。 */
193
+ gapKeys: Set<string>
194
+ /** 上次把「版本库状态不可用」写进缺口的时刻。 */
195
+ statusNoteAt: number
196
+ /** 熔断窗口起点与窗口内已建的整文件新增条数。 */
197
+ burstAt: number
198
+ burstCount: number
199
+ /** 熔断静默截止时刻:在此之前不新建整文件新增记录。 */
200
+ burstMutedUntil: number
167
201
  }
168
202
 
169
203
  // --endregion
@@ -198,6 +232,8 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
198
232
  cwd: String(cwd), sessionId, watchers: [], dirty: new Map(), seen: new Map(),
199
233
  timer: null, firstAt: 0, flushing: false, again: false, degraded: '',
200
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,
201
237
  }
202
238
  spaces.set(key, created)
203
239
  return created
@@ -237,6 +273,7 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
237
273
  */
238
274
  function startWatch(space: Workspace): void {
239
275
  if (space.watchers.length || stopped) return
276
+ space.startedAt = now()
240
277
  try {
241
278
  const watcher = watch(space.cwd, { recursive: true, persistent: false }, (_event, name) => onEvent(space, space.cwd, name))
242
279
  // EventEmitter 的 'error' 无监听者时抛出未捕获异常,必须挂处理器
@@ -293,6 +330,24 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
293
330
  return map
294
331
  }
295
332
 
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
+
296
351
  /**
297
352
  * @private
298
353
  * @description: 读磁盘内容;缺失返回 null,其它失败抛出(由调用点记缺口)。
@@ -323,10 +378,101 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
323
378
  return space.status
324
379
  }
325
380
  const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId)
326
- space.status = scope ? await vcsStatus(scope.shell, space.cwd) : null
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))
327
387
  return space.status
328
388
  }
329
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
420
+ * @description: 同一条缺口只上报一次;去重表满了就丢最早的键,保证内存有界。
421
+ * @param space 工作区状态
422
+ * @param key 去重键
423
+ * @param absolute 出问题的路径
424
+ * @param message 原因
425
+ * @returns 无
426
+ */
427
+ function noteGapOnce(space: Workspace, key: string, absolute: string, message: string): void {
428
+ if (space.gapKeys.has(key)) return
429
+ if (space.gapKeys.size >= GAP_KEY_MAX) {
430
+ const oldest = space.gapKeys.values().next().value
431
+ if (oldest !== undefined) space.gapKeys.delete(oldest)
432
+ }
433
+ space.gapKeys.add(key)
434
+ noteCaptureGap(space.cwd, space.sessionId, absolute, message)
435
+ }
436
+
437
+ /**
438
+ * @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
+
330
476
  /**
331
477
  * @private
332
478
  * @description: 处理一个路径:判定链见文件头注释。
@@ -357,18 +503,30 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
357
503
  space.seen.set(key, content)
358
504
  // 编辑器保存:只推进基线;已有条目按外部改动吸收(基线不动、标分歧),不新开行
359
505
  if (!stored) return false
360
- deps.record(writeOf(space, absolute, stored.entry.newText, content, at, 'watch', 'editor', 'known'))
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'))
361
509
  return true
362
510
  }
363
511
 
364
512
  const status = await statusOf(space)
365
513
  if (status && !status.entries.has(key)) {
366
- // 版本库说这个路径相对基线干净:内容变化只能来自版本库同步
514
+ // 版本库说这个路径相对基线干净:可能是版本库同步,也可能是工具刚写完、
515
+ // 而本批快照还停在上一轮(git 忽略的路径根本不出现在 status 里)。
367
516
  space.seen.set(key, content)
368
517
  if (!stored) return false
369
- deps.record(writeOf(space, absolute, stored.entry.newText, content, at, 'vcs', 'vcs', 'known'))
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'))
370
521
  return true
371
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
+ }
372
530
 
373
531
  const before = await beforeOf(space, key, absolute, stored, status, content)
374
532
  if (before.text === null && content === null) {
@@ -376,6 +534,11 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
376
534
  space.seen.set(key, null)
377
535
  return false
378
536
  }
537
+ // 没有基线的整文件新增是幽灵记录的典型形态:短时间成批出现就熔断,避免一次噪声刷满面板
538
+ if (!stored && before.text === null && !allowNewWholeFile(space, absolute)) {
539
+ space.seen.set(key, content)
540
+ return false
541
+ }
379
542
  deps.record(writeOf(space, absolute, before.text, content, at, 'watch',
380
543
  windows.inAgentWindow(at) ? 'agent' : 'external', before.kind))
381
544
  space.seen.set(key, content)