dsh-vscode-mode 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +28 -5
  2. package/lib/client.js +63 -63
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +1885 -54
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +1 -1
  8. package/src/archivePurge.ts +319 -0
  9. package/src/capture.ts +3 -0
  10. package/src/client/addToConversation.ts +77 -18
  11. package/src/client/htmlPlan/HtmlPlanPanel.ts +9 -13
  12. package/src/client/htmlPlan/planActions.ts +97 -23
  13. package/src/client/htmlPlan/planPage.ts +2 -2
  14. package/src/client/reviewBatch.ts +8 -0
  15. package/src/client/state/diffSummary.ts +6 -1
  16. package/src/client/state/reviewFeed.ts +35 -4
  17. package/src/client/ui/EditorView.ts +7 -0
  18. package/src/client/ui/McpSettings.ts +21 -0
  19. package/src/client/ui/OfficialReview.ts +20 -2
  20. package/src/fileOpenSettings.ts +29 -0
  21. package/src/index.ts +78 -6
  22. package/src/mcpManaged.ts +12 -3
  23. package/src/mcpManagerBridge.ts +5 -1
  24. package/src/mcpRuntime.ts +33 -4
  25. package/src/pending/capture.ts +32 -4
  26. package/src/pending/decide.ts +12 -3
  27. package/src/pending/externalAlign.ts +297 -0
  28. package/src/pending/externalCapture.ts +677 -0
  29. package/src/pending/kernel.ts +19 -1
  30. package/src/pending/persist.ts +201 -12
  31. package/src/pending/provenance.ts +239 -0
  32. package/src/pending/store.ts +67 -6
  33. package/src/pending/vcs.ts +140 -0
  34. package/src/pendingCompat.ts +13 -6
  35. package/src/pendingRpc.ts +37 -2
  36. package/src/rpc.ts +30 -2
  37. package/src/shared/pendingReview.ts +19 -1
  38. package/src/shared/review.ts +3 -1
  39. package/src/shared/rpc.ts +8 -0
@@ -3,8 +3,9 @@
3
3
  * 无 IO、无时钟、不改入参;调用方传入 now 与内容,便于测试与复用。
4
4
  * @author ddj 2026年10月29号
5
5
  */
6
- import type { PendingEarlier, PendingLineage } from '../shared/pendingReview.js'
6
+ import type { PendingBaseKind, PendingEarlier, PendingLineage, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
7
7
  import { logicalLines } from '../shared/lineEndings.js'
8
+ import { strongerSource } from './provenance.js'
8
9
 
9
10
  /** 内存态条目:比展示投影多保存两侧全文。 */
10
11
  export interface PendingEntry {
@@ -18,6 +19,12 @@ export interface PendingEntry {
18
19
  sessionId: string
19
20
  sessionIds: string[]
20
21
  lineage?: PendingLineage
22
+ /** 采集通道;缺省按 `tool` 解释。 */
23
+ source?: PendingSource
24
+ /** 归属;缺省按 `agent` 解释。 */
25
+ origin?: PendingOrigin
26
+ /** 修改前内容的可信度;缺省按 `known` 解释。 */
27
+ baseKind?: PendingBaseKind
21
28
  }
22
29
 
23
30
  /** 新建条目的入参。 */
@@ -30,6 +37,9 @@ export interface NewPending {
30
37
  newText: string
31
38
  updatedAt: number
32
39
  lineage?: PendingLineage
40
+ source?: PendingSource
41
+ origin?: PendingOrigin
42
+ baseKind?: PendingBaseKind
33
43
  }
34
44
 
35
45
  /** 决定后对条目的局部推进;未出现的字段表示不改。 */
@@ -76,6 +86,11 @@ export function mergeEntries(earlier: PendingEntry, later: PendingEntry): Pendin
76
86
  ...later,
77
87
  updatedAt: later.updatedAt,
78
88
  sessionIds: unionSessions(earlier, later),
89
+ // 采集通道取更强的一侧(工具链路胜过 watch,watch 胜过补扫),归属取最近一次改动。
90
+ source: strongerSource(earlier.source, later.source),
91
+ origin: later.origin ?? earlier.origin,
92
+ // 基线一旦落成"已知内容",就不再退回未知;未知只来自首次观察失败的那条记录。
93
+ baseKind: later.baseKind ?? earlier.baseKind,
79
94
  }
80
95
  if (later.lineage === undefined && earlier.lineage !== undefined) merged.lineage = earlier.lineage
81
96
  if (earlier.earlierVersion === 'none' && later.earlierVersion === 'none') {
@@ -107,6 +122,9 @@ export function entryFromNew(input: NewPending): PendingEntry {
107
122
  sessionIds: [input.sessionId],
108
123
  }
109
124
  if (input.lineage !== undefined) entry.lineage = input.lineage
125
+ if (input.source !== undefined) entry.source = input.source
126
+ if (input.origin !== undefined) entry.origin = input.origin
127
+ if (input.baseKind !== undefined) entry.baseKind = input.baseKind
110
128
  return entry
111
129
  }
112
130
 
@@ -4,7 +4,8 @@
4
4
  */
5
5
  import type { DatabaseSync } from 'node:sqlite'
6
6
  import { activeReady, dbFor } from '../archiveDb.js'
7
- import type { PendingLineage } from '../shared/pendingReview.js'
7
+ import { log } from '../log.js'
8
+ import type { PendingBaseKind, PendingLineage, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
8
9
  import type { PendingEntry } from './kernel.js'
9
10
 
10
11
  /** 数据库行。 */
@@ -24,10 +25,44 @@ export interface StoredEntry {
24
25
  flags: PendingFlags
25
26
  }
26
27
 
27
- /** 待审库版本号,写进 metadata 便于日后迁移。v3 给评论表加了引文与上下文列。 */
28
- const SCHEMA_VERSION = '3'
28
+ /** 待审库版本号,写进 metadata 便于日后迁移。v4 给条目加了采集来源与基线可信度。 */
29
+ const SCHEMA_VERSION = '4'
29
30
  /** 迁移前的备份后缀。 */
30
31
  const BACKUP_SUFFIX = '.before-pending.bak'
32
+ /** 工作区待审版本号:条目一落库就自增,供客户端轮询判断是否需要重读列表。 */
33
+ const versions = new Map<string, number>()
34
+
35
+ /**
36
+ * @author ddj 2026-11-24
37
+ * @description: 读工作区待审版本号;只在条目真正落库后自增,保证「先记录后通知 UI」。
38
+ * @param cwd 工作区
39
+ * @returns 单调递增的版本号
40
+ */
41
+ export function pendingVersion(cwd: string): number {
42
+ return versions.get(cwd) ?? 0
43
+ }
44
+
45
+ /**
46
+ * @private
47
+ * @author ddj 2026-11-24
48
+ * @description: 条目状态变化后自增版本号(进程内计数,不落盘)。
49
+ * @param cwd 工作区
50
+ * @returns 无
51
+ */
52
+ function bumpVersion(cwd: string): void {
53
+ versions.set(cwd, (versions.get(cwd) ?? 0) + 1)
54
+ }
55
+
56
+ /**
57
+ * @private
58
+ * @author ddj 2026-11-24
59
+ * @description: 清空某工作区版本号(活跃库重建时用,避免把旧计数当新变化)。
60
+ * @param cwd 工作区
61
+ * @returns 无
62
+ */
63
+ export function resetPendingVersion(cwd: string): void {
64
+ versions.delete(cwd)
65
+ }
31
66
 
32
67
  /**
33
68
  * @author ddj 2026年10月29号
@@ -45,6 +80,7 @@ export function pendingDb(cwd: string): DatabaseSync {
45
80
  try {
46
81
  db.exec(DDL)
47
82
  migrateHistory(db)
83
+ migrateProvenance(db)
48
84
  db.prepare("INSERT INTO metadata(name,value) VALUES('pending_schema',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value")
49
85
  .run(SCHEMA_VERSION)
50
86
  db.exec('COMMIT')
@@ -63,7 +99,9 @@ CREATE TABLE IF NOT EXISTS pending_entries (
63
99
  unseen INTEGER NOT NULL DEFAULT 0, missing INTEGER NOT NULL DEFAULT 0,
64
100
  diverged INTEGER NOT NULL DEFAULT 0, oversized INTEGER NOT NULL DEFAULT 0,
65
101
  revision INTEGER NOT NULL DEFAULT 0, session_id TEXT NOT NULL,
66
- session_ids TEXT NOT NULL, lineage TEXT);
102
+ session_ids TEXT NOT NULL, lineage TEXT,
103
+ source TEXT NOT NULL DEFAULT 'tool', origin TEXT NOT NULL DEFAULT 'agent',
104
+ base_kind TEXT NOT NULL DEFAULT 'known');
67
105
  CREATE TABLE IF NOT EXISTS pending_blocks (
68
106
  entry_id TEXT NOT NULL, block_id TEXT NOT NULL, decision TEXT NOT NULL,
69
107
  PRIMARY KEY(entry_id,block_id));
@@ -76,6 +114,21 @@ CREATE TABLE IF NOT EXISTS pending_history (
76
114
  state TEXT NOT NULL DEFAULT 'applied');
77
115
  `
78
116
 
117
+ /**
118
+ * @author ddj 2026-11-24
119
+ * @description: v3 → v4:给条目补三列来源字段。旧行按默认值读成「工具链路 / agent / 已知内容」,
120
+ * 与 v3 的语义一致,不需要回填。
121
+ * @param db 已打开的工作区库
122
+ * @returns 无
123
+ */
124
+ function migrateProvenance(db: DatabaseSync): void {
125
+ const columns = db.prepare('PRAGMA table_info(pending_entries)').all() as Row[]
126
+ const names = new Set(columns.map((column) => String(column.name)))
127
+ if (!names.has('source')) db.exec("ALTER TABLE pending_entries ADD COLUMN source TEXT NOT NULL DEFAULT 'tool'")
128
+ if (!names.has('origin')) db.exec("ALTER TABLE pending_entries ADD COLUMN origin TEXT NOT NULL DEFAULT 'agent'")
129
+ if (!names.has('base_kind')) db.exec("ALTER TABLE pending_entries ADD COLUMN base_kind TEXT NOT NULL DEFAULT 'known'")
130
+ }
131
+
79
132
  /**
80
133
  * @author ddj 2026年10月29号
81
134
  * @description: v1 历史表补 state 列(rebuild 成本高于一次 ALTER)。
@@ -107,7 +160,7 @@ export function loadEntries(cwd: string): StoredEntry[] {
107
160
  * @returns 无
108
161
  */
109
162
  export function saveEntry(cwd: string, stored: StoredEntry): void {
110
- upsertEntry(pendingDb(cwd), stored)
163
+ upsertEntry(pendingDb(cwd), cwd, stored)
111
164
  }
112
165
 
113
166
  /**
@@ -118,18 +171,22 @@ export function saveEntry(cwd: string, stored: StoredEntry): void {
118
171
  * @param stored 条目与标记
119
172
  * @returns 无
120
173
  */
121
- function upsertEntry(db: DatabaseSync, stored: StoredEntry): void {
174
+ function upsertEntry(db: DatabaseSync, cwd: string, stored: StoredEntry): void {
122
175
  const { entry, flags } = stored
123
176
  db.prepare(`INSERT INTO pending_entries
124
- (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage)
125
- VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
177
+ (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage,
178
+ source,origin,base_kind)
179
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
126
180
  ON CONFLICT(id) DO UPDATE SET path=excluded.path,earlier=excluded.earlier,old_text=excluded.old_text,
127
181
  new_text=excluded.new_text,updated_at=excluded.updated_at,unseen=excluded.unseen,missing=excluded.missing,
128
182
  diverged=excluded.diverged,oversized=excluded.oversized,revision=excluded.revision,
129
- session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage`)
183
+ session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage,
184
+ source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind`)
130
185
  .run(entry.id, entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt,
131
186
  entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0,
132
- flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null)
187
+ flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null,
188
+ entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known')
189
+ bumpVersion(cwd)
133
190
  }
134
191
 
135
192
  /**
@@ -146,6 +203,7 @@ export function dropEntry(cwd: string, id: string): void {
146
203
  db.prepare('DELETE FROM pending_entries WHERE id=?').run(id)
147
204
  db.prepare('DELETE FROM pending_blocks WHERE entry_id=?').run(id)
148
205
  db.exec('COMMIT')
206
+ bumpVersion(cwd)
149
207
  } catch (error) {
150
208
  if (db.isTransaction) db.exec('ROLLBACK')
151
209
  throw error
@@ -179,6 +237,7 @@ export function saveBlocks(cwd: string, entryId: string, blocks: { id: string; d
179
237
  try {
180
238
  writeBlocks(db, entryId, blocks)
181
239
  db.exec('COMMIT')
240
+ bumpVersion(cwd)
182
241
  } catch (error) {
183
242
  if (db.isTransaction) db.exec('ROLLBACK')
184
243
  throw error
@@ -346,12 +405,52 @@ function entryOfRow(row: Row): PendingEntry {
346
405
  earlierVersion: String(row.earlier) === 'none' ? 'none' : 'file',
347
406
  oldText: String(row.old_text), newText: String(row.new_text), updatedAt: Number(row.updated_at),
348
407
  sessionId: String(row.session_id), sessionIds: JSON.parse(String(row.session_ids)) as string[],
408
+ source: sourceOfRow(row),
409
+ origin: originOfRow(row),
410
+ baseKind: baseKindOfRow(row),
349
411
  }
350
412
  if (Number(row.unseen) === 1) entry.unseen = true
351
413
  if (lineage !== undefined) entry.lineage = lineage
352
414
  return entry
353
415
  }
354
416
 
417
+ /**
418
+ * @private
419
+ * @author ddj 2026-11-24
420
+ * @description: 读采集通道列;v3 旧库升级后该列有默认值,异常值按 `tool` 处理。
421
+ * @param row 数据库行
422
+ * @returns 采集通道
423
+ */
424
+ function sourceOfRow(row: Row): PendingSource {
425
+ const value = String(row.source ?? 'tool')
426
+ return (value === 'edit' || value === 'write' || value === 'remote_ssh_write' || value === 'watch'
427
+ || value === 'scan' || value === 'vcs') ? value : 'tool'
428
+ }
429
+
430
+ /**
431
+ * @private
432
+ * @author ddj 2026-11-24
433
+ * @description: 读归属列;异常值按 `agent` 处理(与 v3 语义一致)。
434
+ * @param row 数据库行
435
+ * @returns 归属
436
+ */
437
+ function originOfRow(row: Row): PendingOrigin {
438
+ const value = String(row.origin ?? 'agent')
439
+ return value === 'editor' || value === 'vcs' || value === 'external' ? value : 'agent'
440
+ }
441
+
442
+ /**
443
+ * @private
444
+ * @author ddj 2026-11-24
445
+ * @description: 读基线可信度列;异常值按 `known` 处理。
446
+ * @param row 数据库行
447
+ * @returns 基线可信度
448
+ */
449
+ function baseKindOfRow(row: Row): PendingBaseKind {
450
+ const value = String(row.base_kind ?? 'known')
451
+ return value === 'absent' || value === 'vcs' || value === 'unknown' ? value : 'known'
452
+ }
453
+
355
454
  /**
356
455
  * @author ddj 2026年10月29号
357
456
  * @description: 由数据库行还原标记。
@@ -390,7 +489,8 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
390
489
  const db = pendingDb(cwd)
391
490
  const skipped: { id: string; reason: string }[] = []
392
491
  const advance = db.prepare(`UPDATE pending_entries SET path=?,earlier=?,old_text=?,new_text=?,updated_at=?,unseen=?,
393
- missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=? WHERE id=? AND revision=?`)
492
+ missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?
493
+ WHERE id=? AND revision=?`)
394
494
 
395
495
  db.exec('BEGIN IMMEDIATE')
396
496
  try {
@@ -400,7 +500,9 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
400
500
  const changed = advance.run(entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt,
401
501
  entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0,
402
502
  flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds),
403
- entry.lineage ? JSON.stringify(entry.lineage) : null, record.entryId, expected)
503
+ entry.lineage ? JSON.stringify(entry.lineage) : null,
504
+ entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known',
505
+ record.entryId, expected)
404
506
  // 读条目到落库之间被别的决定推进过:只放弃这一条
405
507
  if (changed.changes !== 1) {
406
508
  skipped.push({ id: record.entryId, reason: '待审条目已变化,请重试' })
@@ -410,9 +512,96 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
410
512
  insertHistory(db, 'decide', record.entryId, record.snapshot, Date.now())
411
513
  }
412
514
  db.exec('COMMIT')
515
+ if (records.length) bumpVersion(cwd)
413
516
  return skipped
414
517
  } catch (error) {
415
518
  if (db.isTransaction) db.exec('ROLLBACK')
416
519
  throw error
417
520
  }
418
521
  }
522
+
523
+ /** 清理筛选条件:只按「采集通道 + 基线可信度 + 时间窗」命中,不猜内容。 */
524
+ export interface PurgeFilter {
525
+ /** 采集通道(缺省 watch)。 */
526
+ sources?: string[]
527
+ /** 基线可信度(缺省 absent)。 */
528
+ baseKinds?: string[]
529
+ /** 只清这个时间之前更新的条目(毫秒时间戳)。 */
530
+ before?: number
531
+ }
532
+
533
+ /** 一次清理的结果。 */
534
+ export interface PurgeOutcome {
535
+ /** 命中多少条(dryRun 也算)。 */
536
+ matched: number
537
+ /** 真正删掉多少条;dryRun 恒为 0。 */
538
+ removed: number
539
+ /** 命中但因为有判定历史而保留的条数。 */
540
+ kept: number
541
+ }
542
+
543
+ /**
544
+ * @public
545
+ * @author ddj 2026-11-24
546
+ * @description: 按条件清理待审条目(清幽灵记录用)。命中判定与删除在同一份读结果上做:
547
+ * 有 pending_history 的条目(已经 Keep/Revert 过)一律保留,绝不按内容猜。
548
+ * @param cwd 工作区
549
+ * @param filter 筛选条件
550
+ * @param dryRun 只数不删
551
+ * @returns 命中、删除与保留条数
552
+ * @throws 事务级异常整体回滚后抛出
553
+ */
554
+ export function purgeEntries(cwd: string, filter: PurgeFilter = {}, dryRun = false): PurgeOutcome {
555
+ const db = pendingDb(cwd)
556
+ const sources = filter.sources && filter.sources.length ? new Set(filter.sources) : null
557
+ const baseKinds = filter.baseKinds && filter.baseKinds.length ? new Set(filter.baseKinds) : null
558
+ const before = typeof filter.before === 'number' ? filter.before : null
559
+ // 只读三列,不把两侧全文拉进内存(大库上单条全文可达百 KB)
560
+ const rows = db.prepare(`SELECT id, source, base_kind, updated_at,
561
+ EXISTS(SELECT 1 FROM pending_history h WHERE h.entry_id = pending_entries.id) AS decided
562
+ FROM pending_entries`).all() as Row[]
563
+
564
+ const hits: string[] = []
565
+ let kept = 0
566
+ for (const row of rows) {
567
+ if (sources && !sources.has(String(row.source))) continue
568
+ if (baseKinds && !baseKinds.has(String(row.base_kind))) continue
569
+ if (before !== null && Number(row.updated_at) >= before) continue
570
+ if (Number(row.decided) === 1) kept += 1
571
+ else hits.push(String(row.id))
572
+ }
573
+ if (dryRun || !hits.length) return { matched: hits.length, removed: 0, kept }
574
+
575
+ db.exec('BEGIN IMMEDIATE')
576
+ try {
577
+ const dropEntryRow = db.prepare('DELETE FROM pending_entries WHERE id=?')
578
+ const dropBlockRows = db.prepare('DELETE FROM pending_blocks WHERE entry_id=?')
579
+ for (const id of hits) {
580
+ dropEntryRow.run(id)
581
+ dropBlockRows.run(id)
582
+ }
583
+ db.exec('COMMIT')
584
+ } catch (error) {
585
+ if (db.isTransaction) db.exec('ROLLBACK')
586
+ throw error
587
+ }
588
+ bumpVersion(cwd)
589
+ return { matched: hits.length, removed: hits.length, kept }
590
+ }
591
+
592
+ /**
593
+ * @public
594
+ * @author ddj 2026-11-24
595
+ * @description: 回收已删行占用的页;失败只记日志,不影响已完成的删除。
596
+ * @param cwd 工作区
597
+ * @returns 耗时毫秒
598
+ */
599
+ export function vacuumEntries(cwd: string): number {
600
+ const started = Date.now()
601
+ try {
602
+ pendingDb(cwd).exec('VACUUM')
603
+ } catch (error) {
604
+ log.warn('待审库 VACUUM 失败:' + String(error))
605
+ }
606
+ return Date.now() - started
607
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * 采集来源与归属:把「谁把这次变化变成记录」和「谁动的文件」拆成两个正交字段,
3
+ * 并维护三类时间窗(工具调用 / 编辑器保存 / 插件自写),供 watch 采集判定归属。
4
+ *
5
+ * 设计取舍:
6
+ * - 归属只用**确定性窗口**判定,不猜 stdout、不看 mtime:任一工具调用在执行期间为 agent 窗口
7
+ * (结束时留 2s 尾巴),`edrv.save` 前后 2s 内命中同一路径为编辑器窗口,插件自己写回的路径
8
+ * 为自写窗口。窗口之外的写盘一律记外部来源,宁可让用户确认一次,也不冒充 agent。
9
+ * - 去重键是「路径 + 内容哈希」:内容逐字节相等就视为同一次变化,绝不按时间戳猜。
10
+ * - 三张表都有上限,长跑实例不会无界增长。
11
+ * 作者 ddj 2026-11-24
12
+ */
13
+ import { createHash } from 'node:crypto'
14
+ import type { PendingBaseKind, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
15
+ import { pathKeyFor } from '../shared/pathKey.js'
16
+
17
+ // --region 常量
18
+
19
+ /** 工具调用结束后的归属尾巴:写完盘到 flush 之间还有事件延迟。 */
20
+ export const AGENT_TAIL_MS = 2000
21
+ /** 编辑器保存的归属窗口。 */
22
+ export const EDITOR_WINDOW_MS = 2000
23
+ /** 插件自写(撤销写回、远端镜像写穿)的窗口:写入后 watch 会立刻收到事件。 */
24
+ export const SELF_WINDOW_MS = 5000
25
+ /** 路径标记表上限:超出按写入序逐出最旧。 */
26
+ export const MARK_MAX = 2000
27
+
28
+ /** 写工具 → 采集通道。未列出的写工具按 `tool` 处理。 */
29
+ const SOURCE_OF_TOOL: Record<string, PendingSource> = {
30
+ edit: 'edit',
31
+ str_replace_editor: 'edit',
32
+ apply_patch: 'edit',
33
+ 'ops_edit_file': 'edit',
34
+ write: 'write',
35
+ 'ops_write_file': 'write',
36
+ 'ops_remove': 'write',
37
+ 'ops_copy': 'write',
38
+ 'ops_move': 'write',
39
+ 'ops_replace': 'edit',
40
+ remote_ssh_write: 'remote_ssh_write',
41
+ // 外部采集直接把通道名当工具名传进来,原样保留,不能被归一成 tool
42
+ watch: 'watch',
43
+ scan: 'scan',
44
+ vcs: 'vcs',
45
+ }
46
+
47
+ /** 通道强度:合并同一路径的两次采集时,强通道保留其来源标签。 */
48
+ const SOURCE_RANK: Record<PendingSource, number> = {
49
+ edit: 6, write: 6, remote_ssh_write: 5, tool: 4, watch: 3, scan: 2, vcs: 1,
50
+ }
51
+
52
+ // --endregion
53
+
54
+ // --region 纯函数
55
+
56
+ /**
57
+ * @author ddj 2026-11-24
58
+ * @description: Host 侧的路径比较键:盘符恒折叠大小写,其余按运行平台折叠。
59
+ * @param path 路径
60
+ * @returns 比较键
61
+ */
62
+ export function pathKeyOf(path: string): string {
63
+ return pathKeyFor(path, process.platform === 'win32')
64
+ }
65
+
66
+ /**
67
+ * @author ddj 2026-11-24
68
+ * @description: 写工具名 → 采集通道;未知工具统一按 `tool`。
69
+ * @param tool 工具名
70
+ * @returns 采集通道
71
+ */
72
+ export function sourceOfTool(tool: unknown): PendingSource {
73
+ const name = typeof tool === 'string' ? tool : ''
74
+ return SOURCE_OF_TOOL[name] ?? 'tool'
75
+ }
76
+
77
+ /**
78
+ * @author ddj 2026-11-24
79
+ * @description: 合并同一路径的两次采集来源:强通道优先,同级保留首次值。
80
+ * @param earlier 已落库通道(可为空)
81
+ * @param later 本次通道
82
+ * @returns 应当落库的通道
83
+ */
84
+ export function strongerSource(earlier: PendingSource | undefined, later: PendingSource | undefined): PendingSource {
85
+ const left = earlier ?? 'tool'
86
+ const right = later ?? 'tool'
87
+ return (SOURCE_RANK[left] >= SOURCE_RANK[right] ? left : right)
88
+ }
89
+
90
+ /**
91
+ * @author ddj 2026-11-24
92
+ * @description: 去重键:路径比较键 + 内容 sha256。只按内容判同一变化,不看时间。
93
+ * @param pathKey 路径比较键
94
+ * @param content 文件内容(缺失用空串)
95
+ * @returns 去重键
96
+ */
97
+ export function dedupeKey(pathKey: string, content: string | null): string {
98
+ return pathKey + '\u0000' + createHash('sha256').update(content ?? '\u0000absent').digest('hex')
99
+ }
100
+
101
+ /**
102
+ * @author ddj 2026-11-24
103
+ * @description: 撤销白名单:只有 agent 来源且基线可信时才可以直接撤销。
104
+ * @param origin 归属
105
+ * @param baseKind 基线与可信度
106
+ * @returns 可直接撤销 / 需确认 / 禁止
107
+ */
108
+ export function revertPolicyOf(
109
+ origin: PendingOrigin | undefined,
110
+ baseKind: PendingBaseKind | undefined,
111
+ ): 'direct' | 'confirm' | 'blocked' {
112
+ if ((baseKind ?? 'known') === 'unknown') return 'blocked'
113
+ return (origin ?? 'agent') === 'agent' ? 'direct' : 'confirm'
114
+ }
115
+
116
+ /**
117
+ * @author ddj 2026-11-24
118
+ * @description: 条目来源徽标文案;官方行没有徽标。
119
+ * @param entry 待审条目的来源字段
120
+ * @returns 展示文案
121
+ */
122
+ export function sourceLabelOf(entry: { source?: PendingSource; origin?: PendingOrigin }): string {
123
+ const source = entry.source ?? 'tool'
124
+ const origin = entry.origin ?? 'agent'
125
+ if (origin === 'agent') return source + ' · agent'
126
+ if (origin === 'editor') return '编辑器保存'
127
+ if (origin === 'vcs') return '版本库同步'
128
+ return source + ' · 外部'
129
+ }
130
+
131
+ // --endregion
132
+
133
+ // --region 时间窗
134
+
135
+ /** 一条路径上的窗口标记。 */
136
+ interface Marks {
137
+ selfAt?: number
138
+ editorAt?: number
139
+ }
140
+
141
+ /** 进程内窗口状态:随插件装配创建,卸载清空。 */
142
+ interface WindowState {
143
+ /** 正在执行的工具调用数。 */
144
+ depth: number
145
+ /** agent 窗口的结束时刻。 */
146
+ until: number
147
+ /** 路径标记表(插入序即淘汰序)。 */
148
+ marks: Map<string, Marks>
149
+ }
150
+
151
+ /**
152
+ * 创建窗口注册表(不依赖 Host,可单测)。
153
+ * @author ddj 2026-11-24
154
+ * @returns 注册表能力
155
+ */
156
+ export function createWindows() {
157
+ const state: WindowState = { depth: 0, until: 0, marks: new Map() }
158
+
159
+ /**
160
+ * @description: 逐出超期标记,再压到上限内。
161
+ * @param now 当前时间
162
+ */
163
+ function sweep(now: number): void {
164
+ for (const [key, mark] of state.marks) {
165
+ const self = mark.selfAt !== undefined && now - mark.selfAt <= SELF_WINDOW_MS
166
+ const editor = mark.editorAt !== undefined && now - mark.editorAt <= EDITOR_WINDOW_MS
167
+ if (!self && !editor) state.marks.delete(key)
168
+ }
169
+ while (state.marks.size > MARK_MAX) {
170
+ const oldest = state.marks.keys().next().value
171
+ if (oldest === undefined) break
172
+ state.marks.delete(oldest)
173
+ }
174
+ }
175
+
176
+ /**
177
+ * @description: 取(或建)一条路径的标记。
178
+ * @param key 路径比较键
179
+ * @param now 当前时间
180
+ * @returns 可变标记对象
181
+ */
182
+ function markOf(key: string, now: number): Marks {
183
+ sweep(now)
184
+ const existing = state.marks.get(key)
185
+ if (existing) return existing
186
+ const created: Marks = {}
187
+ state.marks.set(key, created)
188
+ return created
189
+ }
190
+
191
+ return {
192
+ /** @returns 工具调用开始,进入 agent 窗口。 */
193
+ enterTool(now = Date.now()): void {
194
+ state.depth += 1
195
+ state.until = now + AGENT_TAIL_MS
196
+ },
197
+ /** @param now 当前时间 @returns 工具调用结束,留下尾巴。 */
198
+ exitTool(now = Date.now()): void {
199
+ state.depth = Math.max(0, state.depth - 1)
200
+ state.until = Math.max(state.until, now + AGENT_TAIL_MS)
201
+ },
202
+ /** @param now 当前时间 @returns 当前是否算 agent 写入窗口。 */
203
+ inAgentWindow(now = Date.now()): boolean {
204
+ return state.depth > 0 || now <= state.until
205
+ },
206
+ /** @param key 路径比较键 @param now 当前时间 @returns 打自写标记。 */
207
+ markSelf(key: string, now = Date.now()): void {
208
+ markOf(key, now).selfAt = now
209
+ },
210
+ /** @param key 路径比较键 @param now 当前时间 @returns 打编辑器保存标记。 */
211
+ markEditor(key: string, now = Date.now()): void {
212
+ markOf(key, now).editorAt = now
213
+ },
214
+ /**
215
+ * @description: 取占用窗口的类别;自写优先于编辑器,两者都没有返回 null。
216
+ * @param key 路径比较键
217
+ * @param now 当前时间
218
+ * @returns 窗口类别
219
+ */
220
+ windowOf(key: string, now = Date.now()): 'self' | 'editor' | null {
221
+ const mark = state.marks.get(key)
222
+ if (!mark) return null
223
+ if (mark.selfAt !== undefined && now - mark.selfAt <= SELF_WINDOW_MS) return 'self'
224
+ if (mark.editorAt !== undefined && now - mark.editorAt <= EDITOR_WINDOW_MS) return 'editor'
225
+ return null
226
+ },
227
+ /** @returns 无。清空全部窗口(插件卸载)。 */
228
+ dispose(): void {
229
+ state.depth = 0
230
+ state.until = 0
231
+ state.marks.clear()
232
+ },
233
+ }
234
+ }
235
+
236
+ /** 进程级窗口注册表:capture.ts / rpc.ts / externalCapture.ts 共用同一份。 */
237
+ export const windows = createWindows()
238
+
239
+ // --endregion