dsh-vscode-mode 0.34.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.
Files changed (43) hide show
  1. package/README.md +25 -4
  2. package/lib/client.js +63 -63
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +1841 -73
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/SKILL.md +23 -0
  8. package/skills/dsh-vscodemode-html-plan/references/blocks.md +14 -0
  9. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.css +20 -0
  10. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.js +36 -1
  11. package/skills/dsh-vscodemode-html-plan/runtime/pack.mjs +35 -4
  12. package/skills/dsh-vscodemode-html-plan/runtime/plan.mjs +17 -6
  13. package/src/capture.ts +3 -0
  14. package/src/client/htmlPlan/HtmlPlanPanel.ts +8 -3
  15. package/src/client/htmlPlan/planPage.ts +31 -1
  16. package/src/client/reviewBatch.ts +8 -0
  17. package/src/client/state/diffSummary.ts +6 -1
  18. package/src/client/state/reviewFeed.ts +35 -4
  19. package/src/client/ui/EditorView.ts +7 -0
  20. package/src/client/ui/McpSettings.ts +21 -0
  21. package/src/client/ui/OfficialReview.ts +20 -2
  22. package/src/fileOpenSettings.ts +29 -0
  23. package/src/htmlPlanAttachments.ts +362 -0
  24. package/src/htmlPlanCommand.ts +257 -18
  25. package/src/index.ts +74 -6
  26. package/src/mcpManaged.ts +12 -3
  27. package/src/mcpManagerBridge.ts +5 -1
  28. package/src/mcpRuntime.ts +33 -4
  29. package/src/pending/capture.ts +32 -4
  30. package/src/pending/decide.ts +12 -3
  31. package/src/pending/externalAlign.ts +297 -0
  32. package/src/pending/externalCapture.ts +581 -0
  33. package/src/pending/kernel.ts +19 -1
  34. package/src/pending/persist.ts +114 -12
  35. package/src/pending/provenance.ts +239 -0
  36. package/src/pending/store.ts +30 -4
  37. package/src/pending/vcs.ts +122 -0
  38. package/src/pendingCompat.ts +13 -6
  39. package/src/pendingRpc.ts +19 -2
  40. package/src/rpc.ts +7 -2
  41. package/src/shared/pendingReview.ts +19 -1
  42. package/src/shared/review.ts +3 -1
  43. package/src/shared/rpc.ts +4 -0
@@ -4,7 +4,7 @@
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 type { PendingBaseKind, PendingLineage, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
8
8
  import type { PendingEntry } from './kernel.js'
9
9
 
10
10
  /** 数据库行。 */
@@ -24,10 +24,44 @@ export interface StoredEntry {
24
24
  flags: PendingFlags
25
25
  }
26
26
 
27
- /** 待审库版本号,写进 metadata 便于日后迁移。v3 给评论表加了引文与上下文列。 */
28
- const SCHEMA_VERSION = '3'
27
+ /** 待审库版本号,写进 metadata 便于日后迁移。v4 给条目加了采集来源与基线可信度。 */
28
+ const SCHEMA_VERSION = '4'
29
29
  /** 迁移前的备份后缀。 */
30
30
  const BACKUP_SUFFIX = '.before-pending.bak'
31
+ /** 工作区待审版本号:条目一落库就自增,供客户端轮询判断是否需要重读列表。 */
32
+ const versions = new Map<string, number>()
33
+
34
+ /**
35
+ * @author ddj 2026-11-24
36
+ * @description: 读工作区待审版本号;只在条目真正落库后自增,保证「先记录后通知 UI」。
37
+ * @param cwd 工作区
38
+ * @returns 单调递增的版本号
39
+ */
40
+ export function pendingVersion(cwd: string): number {
41
+ return versions.get(cwd) ?? 0
42
+ }
43
+
44
+ /**
45
+ * @private
46
+ * @author ddj 2026-11-24
47
+ * @description: 条目状态变化后自增版本号(进程内计数,不落盘)。
48
+ * @param cwd 工作区
49
+ * @returns 无
50
+ */
51
+ function bumpVersion(cwd: string): void {
52
+ versions.set(cwd, (versions.get(cwd) ?? 0) + 1)
53
+ }
54
+
55
+ /**
56
+ * @private
57
+ * @author ddj 2026-11-24
58
+ * @description: 清空某工作区版本号(活跃库重建时用,避免把旧计数当新变化)。
59
+ * @param cwd 工作区
60
+ * @returns 无
61
+ */
62
+ export function resetPendingVersion(cwd: string): void {
63
+ versions.delete(cwd)
64
+ }
31
65
 
32
66
  /**
33
67
  * @author ddj 2026年10月29号
@@ -45,6 +79,7 @@ export function pendingDb(cwd: string): DatabaseSync {
45
79
  try {
46
80
  db.exec(DDL)
47
81
  migrateHistory(db)
82
+ migrateProvenance(db)
48
83
  db.prepare("INSERT INTO metadata(name,value) VALUES('pending_schema',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value")
49
84
  .run(SCHEMA_VERSION)
50
85
  db.exec('COMMIT')
@@ -63,7 +98,9 @@ CREATE TABLE IF NOT EXISTS pending_entries (
63
98
  unseen INTEGER NOT NULL DEFAULT 0, missing INTEGER NOT NULL DEFAULT 0,
64
99
  diverged INTEGER NOT NULL DEFAULT 0, oversized INTEGER NOT NULL DEFAULT 0,
65
100
  revision INTEGER NOT NULL DEFAULT 0, session_id TEXT NOT NULL,
66
- session_ids TEXT NOT NULL, lineage TEXT);
101
+ session_ids TEXT NOT NULL, lineage TEXT,
102
+ source TEXT NOT NULL DEFAULT 'tool', origin TEXT NOT NULL DEFAULT 'agent',
103
+ base_kind TEXT NOT NULL DEFAULT 'known');
67
104
  CREATE TABLE IF NOT EXISTS pending_blocks (
68
105
  entry_id TEXT NOT NULL, block_id TEXT NOT NULL, decision TEXT NOT NULL,
69
106
  PRIMARY KEY(entry_id,block_id));
@@ -76,6 +113,21 @@ CREATE TABLE IF NOT EXISTS pending_history (
76
113
  state TEXT NOT NULL DEFAULT 'applied');
77
114
  `
78
115
 
116
+ /**
117
+ * @author ddj 2026-11-24
118
+ * @description: v3 → v4:给条目补三列来源字段。旧行按默认值读成「工具链路 / agent / 已知内容」,
119
+ * 与 v3 的语义一致,不需要回填。
120
+ * @param db 已打开的工作区库
121
+ * @returns 无
122
+ */
123
+ function migrateProvenance(db: DatabaseSync): void {
124
+ const columns = db.prepare('PRAGMA table_info(pending_entries)').all() as Row[]
125
+ const names = new Set(columns.map((column) => String(column.name)))
126
+ if (!names.has('source')) db.exec("ALTER TABLE pending_entries ADD COLUMN source TEXT NOT NULL DEFAULT 'tool'")
127
+ if (!names.has('origin')) db.exec("ALTER TABLE pending_entries ADD COLUMN origin TEXT NOT NULL DEFAULT 'agent'")
128
+ if (!names.has('base_kind')) db.exec("ALTER TABLE pending_entries ADD COLUMN base_kind TEXT NOT NULL DEFAULT 'known'")
129
+ }
130
+
79
131
  /**
80
132
  * @author ddj 2026年10月29号
81
133
  * @description: v1 历史表补 state 列(rebuild 成本高于一次 ALTER)。
@@ -107,7 +159,7 @@ export function loadEntries(cwd: string): StoredEntry[] {
107
159
  * @returns 无
108
160
  */
109
161
  export function saveEntry(cwd: string, stored: StoredEntry): void {
110
- upsertEntry(pendingDb(cwd), stored)
162
+ upsertEntry(pendingDb(cwd), cwd, stored)
111
163
  }
112
164
 
113
165
  /**
@@ -118,18 +170,22 @@ export function saveEntry(cwd: string, stored: StoredEntry): void {
118
170
  * @param stored 条目与标记
119
171
  * @returns 无
120
172
  */
121
- function upsertEntry(db: DatabaseSync, stored: StoredEntry): void {
173
+ function upsertEntry(db: DatabaseSync, cwd: string, stored: StoredEntry): void {
122
174
  const { entry, flags } = stored
123
175
  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(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
176
+ (id,path,earlier,old_text,new_text,updated_at,unseen,missing,diverged,oversized,revision,session_id,session_ids,lineage,
177
+ source,origin,base_kind)
178
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
126
179
  ON CONFLICT(id) DO UPDATE SET path=excluded.path,earlier=excluded.earlier,old_text=excluded.old_text,
127
180
  new_text=excluded.new_text,updated_at=excluded.updated_at,unseen=excluded.unseen,missing=excluded.missing,
128
181
  diverged=excluded.diverged,oversized=excluded.oversized,revision=excluded.revision,
129
- session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage`)
182
+ session_id=excluded.session_id,session_ids=excluded.session_ids,lineage=excluded.lineage,
183
+ source=excluded.source,origin=excluded.origin,base_kind=excluded.base_kind`)
130
184
  .run(entry.id, entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt,
131
185
  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)
186
+ flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds), entry.lineage ? JSON.stringify(entry.lineage) : null,
187
+ entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known')
188
+ bumpVersion(cwd)
133
189
  }
134
190
 
135
191
  /**
@@ -146,6 +202,7 @@ export function dropEntry(cwd: string, id: string): void {
146
202
  db.prepare('DELETE FROM pending_entries WHERE id=?').run(id)
147
203
  db.prepare('DELETE FROM pending_blocks WHERE entry_id=?').run(id)
148
204
  db.exec('COMMIT')
205
+ bumpVersion(cwd)
149
206
  } catch (error) {
150
207
  if (db.isTransaction) db.exec('ROLLBACK')
151
208
  throw error
@@ -179,6 +236,7 @@ export function saveBlocks(cwd: string, entryId: string, blocks: { id: string; d
179
236
  try {
180
237
  writeBlocks(db, entryId, blocks)
181
238
  db.exec('COMMIT')
239
+ bumpVersion(cwd)
182
240
  } catch (error) {
183
241
  if (db.isTransaction) db.exec('ROLLBACK')
184
242
  throw error
@@ -346,12 +404,52 @@ function entryOfRow(row: Row): PendingEntry {
346
404
  earlierVersion: String(row.earlier) === 'none' ? 'none' : 'file',
347
405
  oldText: String(row.old_text), newText: String(row.new_text), updatedAt: Number(row.updated_at),
348
406
  sessionId: String(row.session_id), sessionIds: JSON.parse(String(row.session_ids)) as string[],
407
+ source: sourceOfRow(row),
408
+ origin: originOfRow(row),
409
+ baseKind: baseKindOfRow(row),
349
410
  }
350
411
  if (Number(row.unseen) === 1) entry.unseen = true
351
412
  if (lineage !== undefined) entry.lineage = lineage
352
413
  return entry
353
414
  }
354
415
 
416
+ /**
417
+ * @private
418
+ * @author ddj 2026-11-24
419
+ * @description: 读采集通道列;v3 旧库升级后该列有默认值,异常值按 `tool` 处理。
420
+ * @param row 数据库行
421
+ * @returns 采集通道
422
+ */
423
+ function sourceOfRow(row: Row): PendingSource {
424
+ const value = String(row.source ?? 'tool')
425
+ return (value === 'edit' || value === 'write' || value === 'remote_ssh_write' || value === 'watch'
426
+ || value === 'scan' || value === 'vcs') ? value : 'tool'
427
+ }
428
+
429
+ /**
430
+ * @private
431
+ * @author ddj 2026-11-24
432
+ * @description: 读归属列;异常值按 `agent` 处理(与 v3 语义一致)。
433
+ * @param row 数据库行
434
+ * @returns 归属
435
+ */
436
+ function originOfRow(row: Row): PendingOrigin {
437
+ const value = String(row.origin ?? 'agent')
438
+ return value === 'editor' || value === 'vcs' || value === 'external' ? value : 'agent'
439
+ }
440
+
441
+ /**
442
+ * @private
443
+ * @author ddj 2026-11-24
444
+ * @description: 读基线可信度列;异常值按 `known` 处理。
445
+ * @param row 数据库行
446
+ * @returns 基线可信度
447
+ */
448
+ function baseKindOfRow(row: Row): PendingBaseKind {
449
+ const value = String(row.base_kind ?? 'known')
450
+ return value === 'absent' || value === 'vcs' || value === 'unknown' ? value : 'known'
451
+ }
452
+
355
453
  /**
356
454
  * @author ddj 2026年10月29号
357
455
  * @description: 由数据库行还原标记。
@@ -390,7 +488,8 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
390
488
  const db = pendingDb(cwd)
391
489
  const skipped: { id: string; reason: string }[] = []
392
490
  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=?`)
491
+ missing=?,diverged=?,oversized=?,revision=?,session_id=?,session_ids=?,lineage=?,source=?,origin=?,base_kind=?
492
+ WHERE id=? AND revision=?`)
394
493
 
395
494
  db.exec('BEGIN IMMEDIATE')
396
495
  try {
@@ -400,7 +499,9 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
400
499
  const changed = advance.run(entry.path, entry.earlierVersion, entry.oldText, entry.newText, entry.updatedAt,
401
500
  entry.unseen === true ? 1 : 0, flags.missing ? 1 : 0, flags.diverged ? 1 : 0, flags.oversized ? 1 : 0,
402
501
  flags.revision, entry.sessionId, JSON.stringify(entry.sessionIds),
403
- entry.lineage ? JSON.stringify(entry.lineage) : null, record.entryId, expected)
502
+ entry.lineage ? JSON.stringify(entry.lineage) : null,
503
+ entry.source ?? 'tool', entry.origin ?? 'agent', entry.baseKind ?? 'known',
504
+ record.entryId, expected)
404
505
  // 读条目到落库之间被别的决定推进过:只放弃这一条
405
506
  if (changed.changes !== 1) {
406
507
  skipped.push({ id: record.entryId, reason: '待审条目已变化,请重试' })
@@ -410,6 +511,7 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
410
511
  insertHistory(db, 'decide', record.entryId, record.snapshot, Date.now())
411
512
  }
412
513
  db.exec('COMMIT')
514
+ if (records.length) bumpVersion(cwd)
413
515
  return skipped
414
516
  } catch (error) {
415
517
  if (db.isTransaction) db.exec('ROLLBACK')
@@ -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
@@ -2,10 +2,11 @@
2
2
  * 待审投影的工作区存储:把采集到的写入折进单条累计条目,并承接 Keep/Revert 与外部改动的吸收。
3
3
  * @author ddj 2026年10月29号
4
4
  */
5
- import type { PendingDecide, PendingDetail, PendingHistoryMove, PendingItem, PendingPage } from '../shared/pendingReview.js'
5
+ import type { PendingDecide, PendingDetail, PendingHistoryMove, PendingItem, PendingOrigin, PendingPage } from '../shared/pendingReview.js'
6
6
  import type { ReviewBlockState } from '../shared/reviewRegions.js'
7
7
  import { reviewBlocks } from '../shared/reviewRegions.js'
8
8
  import { addedFiles } from '../reviewDb.js'
9
+ import { pathKeyOf, sourceOfTool, windows } from './provenance.js'
9
10
  import type { PendingWrite } from './capture.js'
10
11
  import { readText, pendingGaps } from './capture.js'
11
12
  import type { ShellLike, VcsImportOptions } from './vcs.js'
@@ -70,6 +71,9 @@ export function foldWrite(stored: StoredEntry | undefined, write: PendingWrite):
70
71
  oldText: write.before ?? '',
71
72
  newText: write.after ?? '',
72
73
  updatedAt: write.now,
74
+ source: sourceOfTool(write.tool),
75
+ origin: originOf(write),
76
+ baseKind: write.before === null ? 'absent' : (write.baseKind ?? 'known'),
73
77
  })
74
78
  if (!stored) {
75
79
  return {
@@ -90,6 +94,21 @@ export function foldWrite(stored: StoredEntry | undefined, write: PendingWrite):
90
94
  }
91
95
  }
92
96
 
97
+ /**
98
+ * @private
99
+ * @author ddj 2026-11-24
100
+ * @description: 本次写入的归属:显式指定优先,否则按窗口判定(工具链路默认 agent)。
101
+ * @param write 采集到的写入
102
+ * @returns 归属
103
+ */
104
+ function originOf(write: PendingWrite): PendingOrigin {
105
+ if (write.origin) return write.origin
106
+ const window = windows.windowOf(pathKeyOf(write.identity))
107
+ if (window === 'self') return 'agent'
108
+ if (window === 'editor') return 'editor'
109
+ return 'agent'
110
+ }
111
+
93
112
  /**
94
113
  * @author ddj 2026年10月29号
95
114
  * @description: 条目转列表投影,已解决条目仍保留但不可再决定。
@@ -115,6 +134,9 @@ export function itemOf(stored: StoredEntry, baselineEmpty = false): PendingItem
115
134
  updatedAt: entry.updatedAt,
116
135
  sessionId: entry.sessionId,
117
136
  sessionIds: entry.sessionIds,
137
+ source: entry.source ?? 'tool',
138
+ origin: entry.origin ?? 'agent',
139
+ baseKind: entry.baseKind ?? 'known',
118
140
  }
119
141
  if (entry.lineage !== undefined) item.lineage = entry.lineage
120
142
  return item
@@ -204,9 +226,11 @@ export function recordWrite(write: PendingWrite): void {
204
226
  * @param now 时间
205
227
  * @returns 新条目与标记
206
228
  */
207
- export function absorbed(stored: StoredEntry, content: string, now: number): StoredEntry {
229
+ export function absorbed(stored: StoredEntry, content: string, now: number, origin?: PendingOrigin): StoredEntry {
230
+ const entry: PendingEntry = { ...stored.entry, newText: content, updatedAt: now, unseen: true }
231
+ if (origin) entry.origin = origin
208
232
  return {
209
- entry: { ...stored.entry, newText: content, updatedAt: now, unseen: true },
233
+ entry,
210
234
  flags: { ...stored.flags, diverged: true, missing: false, revision: stored.flags.revision + 1 },
211
235
  }
212
236
  }
@@ -299,7 +323,9 @@ export async function applyDecide(
299
323
  now: Date.now(),
300
324
  write: (content) => {
301
325
  if (content === null) return deleteTarget(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy)
302
- return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy)(content)
326
+ // 允许重建:文件已被删除时撤销的语义就是「恢复修改前内容」。createIfAbsent 原子创建,
327
+ // 期间有人抢先写了同名文件会失败并回到 diverged,不会覆盖别人的新内容。
328
+ return writerFor(fs, cwd, stored.entry.id, stored.entry.newText, signal, policy, true)(content)
303
329
  },
304
330
  })
305
331
  if (!outcome.ok) return { ok: false, reason: outcome.reason }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { readFile, stat } from 'node:fs/promises'
7
7
  import { dirname, join, resolve, sep } from 'node:path'
8
+ import { pathKeyOf } from './provenance.js'
8
9
 
9
10
  /** 支持的版本库种类。 */
10
11
  export type VcsKind = 'git' | 'svn' | 'p4'
@@ -23,6 +24,23 @@ export interface VcsChange {
23
24
  newText: string | null
24
25
  }
25
26
 
27
+ /** 工作副本相对基线的一条状态(补扫只关心这三类)。 */
28
+ export type VcsEntryStatus = 'modified' | 'added' | 'deleted'
29
+
30
+ /** 一条状态条目:绝对路径与归一状态。 */
31
+ export interface VcsEntry {
32
+ path: string
33
+ status: VcsEntryStatus
34
+ }
35
+
36
+ /** 一次状态探测结果:根目录、种类与「相对基线有改动」的路径集合。 */
37
+ export interface VcsStatus {
38
+ kind: VcsKind
39
+ root: string
40
+ /** 绝对路径比较键 → 状态条目(键由 pathKeyFor 生成,调用方直接比对)。 */
41
+ entries: Map<string, VcsEntry>
42
+ }
43
+
26
44
  /** 导入选项。 */
27
45
  export interface VcsImportOptions {
28
46
  includeUntracked?: boolean
@@ -365,6 +383,110 @@ async function runCommand(
365
383
  }
366
384
  }
367
385
 
386
+ /**
387
+ * @author ddj 2026-11-24
388
+ * @description: 只读一条状态命令,取「工作副本相对基线有改动」的路径集合。补扫用它当候选与
389
+ * 「干净」判据:不在集合里的路径,其内容变化只能来自版本库同步,不该记成 agent 改动。
390
+ * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
391
+ * @param shell shell 能力
392
+ * @param cwd 工作区
393
+ * @returns 状态集合或 null
394
+ */
395
+ export async function vcsStatus(shell: ShellLike, cwd: string): Promise<VcsStatus | null> {
396
+ const detected = await detectVcsRoot(cwd)
397
+ if (!detected || detected.kind === 'p4') return null
398
+ return detected.kind === 'git' ? gitStatus(shell, detected.root) : svnStatus(shell, detected.root)
399
+ }
400
+
401
+ /**
402
+ * @private
403
+ * @author ddj 2026-11-24
404
+ * @description: git 状态:一条 status 命令解析出改动集合。
405
+ * @param shell shell 能力
406
+ * @param root 仓库根
407
+ * @returns 状态集合或 null(命令失败)
408
+ */
409
+ async function gitStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
410
+ const status = await runCommand(shell, 'git -c status.renames=false status --porcelain=v1 -z --untracked-files=all', root)
411
+ if (!status.ok) return null
412
+ const entries = new Map<string, VcsEntry>()
413
+ for (const entry of parseGitStatus(status.stdout)) {
414
+ const absolute = join(root, ...entry.path.split(GIT_SEPARATOR))
415
+ if (!insideRoot(root, absolute)) continue
416
+ entries.set(pathKeyOf(absolute), { path: absolute, status: gitStatusOf(entry.status) })
417
+ }
418
+ return { kind: 'git', root, entries }
419
+ }
420
+
421
+ /**
422
+ * @private
423
+ * @author ddj 2026-11-24
424
+ * @description: svn 状态:一条 status --xml 解析出改动集合。
425
+ * @param shell shell 能力
426
+ * @param root 工作副本根
427
+ * @returns 状态集合或 null(命令失败)
428
+ */
429
+ async function svnStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
430
+ const status = await runCommand(shell, 'svn status --xml', root)
431
+ if (!status.ok) return null
432
+ const entries = new Map<string, VcsEntry>()
433
+ for (const entry of parseSvnStatus(status.stdout)) {
434
+ const absolute = resolve(root, entry.path)
435
+ if (!insideRoot(root, absolute)) continue
436
+ entries.set(pathKeyOf(absolute), { path: absolute, status: svnStatusOf(entry.status) })
437
+ }
438
+ return { kind: 'svn', root, entries }
439
+ }
440
+
441
+ /**
442
+ * @private
443
+ * @author ddj 2026-11-24
444
+ * @description: git 状态码归一:删除优先,其次新增/未跟踪,其余按修改。
445
+ * @param status 两位状态码
446
+ * @returns 归一状态
447
+ */
448
+ function gitStatusOf(status: string): VcsEntryStatus {
449
+ if (status.includes('D')) return 'deleted'
450
+ if (status === '??' || status.includes('A')) return 'added'
451
+ return 'modified'
452
+ }
453
+
454
+ /**
455
+ * @private
456
+ * @author ddj 2026-11-24
457
+ * @description: svn 条目状态归一。
458
+ * @param status wc-status 的 item 值
459
+ * @returns 归一状态
460
+ */
461
+ function svnStatusOf(status: string): VcsEntryStatus {
462
+ if (status === 'deleted' || status === 'missing') return 'deleted'
463
+ if (status === 'added' || status === 'unversioned' || status === 'replaced') return 'added'
464
+ return 'modified'
465
+ }
466
+
467
+ /**
468
+ * @author ddj 2026-11-24
469
+ * @description: 读某路径的版本库基线内容;只用于补录记录的修改前内容。
470
+ * @param shell shell 能力
471
+ * @param status 已探测的状态(给根目录与种类)
472
+ * @param absolute 绝对路径
473
+ * @returns 基线内容;读不到返回 null
474
+ */
475
+ export async function vcsBaselineOf(
476
+ shell: ShellLike, status: Pick<VcsStatus, 'kind' | 'root'>, absolute: string,
477
+ ): Promise<string | null> {
478
+ const root = status.root
479
+ const relative = absolute.slice(root.length).replace(/^[\\/]+/, '').split(sep).join(GIT_SEPARATOR)
480
+ if (!relative) return null
481
+ try {
482
+ if (status.kind === 'git') return await gitBaseline(shell, root, relative)
483
+ const shown = await runCommand(shell, `svn cat -r BASE ${quote(absolute)}`, root)
484
+ return shown.ok ? shown.stdout : null
485
+ } catch {
486
+ return null
487
+ }
488
+ }
489
+
368
490
  /**
369
491
  * @author ddj 2026年10月30号
370
492
  * @description: 读单元格文本,不存在时返回 null。