dsh-vscode-mode 0.36.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.
@@ -25,6 +25,7 @@ let host: {
25
25
  ctx: PlanActionCtx
26
26
  appendText: (sessionId: string | undefined, text: string) => Promise<string>
27
27
  sendTask: (sessionId: string | undefined, text: string) => Promise<PlanActionResult>
28
+ steerTask: (sessionId: string | undefined, text: string) => Promise<PlanActionResult>
28
29
  } | null = null
29
30
  /** 取异常的展示文案。 */
30
31
  function messageOf(error: unknown): string {
@@ -211,15 +212,15 @@ function unwrap(result: unknown): PlanActionResult {
211
212
  }
212
213
 
213
214
  /**
214
- * 安装动作宿主(index.ts 装配一次)。
215
+ * 安装选项(appendText / sendTask / steerTask 可注入,便于单测;生产缺省用会话输入门面)。
215
216
  * @author ddj 2026年11月21号
216
- * @param ctx 客户端上下文
217
- * @returns 幂等卸载器
217
+ * @author ddj 2026年11月24号(新增 steerTask)
218
218
  */
219
- /** 安装选项(appendText / sendTask 可注入,便于单测;生产缺省用会话输入门面)。 */
220
219
  export interface HtmlPlanActionOptions {
221
220
  appendText?: (sessionId: string | undefined, text: string) => Promise<string>
222
221
  sendTask?: (sessionId: string | undefined, text: string) => Promise<unknown>
222
+ /** 送进 agent 当前回合(steer):答复先到、审批后结算,两者才落在同一次请求里。 */
223
+ steerTask?: (sessionId: string | undefined, text: string) => Promise<unknown>
223
224
  }
224
225
 
225
226
  /**
@@ -244,28 +245,81 @@ function sendResultOf(raw: unknown): PlanActionResult {
244
245
  return fail('发送结果未知' + detail)
245
246
  }
246
247
 
248
+ /**
249
+ * 安装动作宿主(index.ts 装配一次)。
250
+ * @author ddj 2026年11月21号
251
+ * @param ctx 客户端上下文
252
+ * @returns 幂等卸载器
253
+ */
247
254
  export function installHtmlPlanActions(ctx: PlanActionCtx, options: HtmlPlanActionOptions = {}): () => void {
248
255
  const injectedAppend = options.appendText
249
256
  const injectedSend = options.sendTask
257
+ const injectedSteer = options.steerTask
250
258
  const addToConversation = injectedAppend && injectedSend ? null : createAddToConversation(ctx as never)
251
259
  const sendInjected = injectedSend
260
+ const steerInjected = injectedSteer
252
261
  const conversations = addToConversation
262
+
263
+ /** 走会话投递门面的详细回执(sendTaskResult 缺失时给可读失败)。 */
264
+ const sendViaResults = async (
265
+ sessionId: string | undefined,
266
+ text: string,
267
+ mode: 'queue' | 'steer',
268
+ ): Promise<PlanActionResult> => {
269
+ const send = conversations?.sendTaskResult
270
+ if (typeof send !== 'function') return fail('当前 DSH 不支持直接发送,请用「填入对话输入框」')
271
+ return sendResultOf(await send.call(conversations, sessionId, text, mode))
272
+ }
273
+
253
274
  host = {
254
275
  ctx,
255
276
  appendText: injectedAppend ?? ((sessionId, text) => conversations!.appendText(sessionId, text)),
256
277
  sendTask: typeof sendInjected === 'function'
257
278
  ? async (sessionId, text) => sendResultOf(await sendInjected(sessionId, text))
258
- : async (sessionId, text) => {
259
- const send = conversations?.sendTaskResult
260
- if (typeof send !== 'function') return fail('当前 DSH 不支持直接发送,请用「填入对话输入框」')
261
- return sendResultOf(await send.call(conversations, sessionId, text))
262
- },
279
+ : (sessionId, text) => sendViaResults(sessionId, text, 'queue'),
280
+ steerTask: typeof steerInjected === 'function'
281
+ ? async (sessionId, text) => sendResultOf(await steerInjected(sessionId, text))
282
+ : (sessionId, text) => sendViaResults(sessionId, text, 'steer'),
263
283
  }
264
284
  return () => {
265
285
  host = null
266
286
  }
267
287
  }
268
288
 
289
+ /**
290
+ * 已送进当前回合、但审批结算还没成功的答复:同一 callId 与同一正文不重复送。
291
+ *
292
+ * 批准这一步可能失败(网络、审批已被别处结算),用户会再点一次;没有这张表,
293
+ * 同一份答复会被送两遍给模型。
294
+ */
295
+ const steeredReplies = new Map<string, { callId: string; text: string }>()
296
+
297
+ /**
298
+ * 把一段正文送进 agent 当前回合(steer),让它和审批结果落在同一次模型请求里。
299
+ *
300
+ * 顺序只能是「先 steer 正文,再结算审批」。反过来时,审批一结算宿主立刻把工具结果
301
+ * 交给模型并开始下一步,而排队投递(queue)的消息属于下一回合,于是表现为
302
+ * 「agent 直接开始执行,我填的答复等这一轮跑完才送到」。
303
+ * @author ddj 2026年11月24号
304
+ * @param sessionId 会话 id
305
+ * @param callId 待审批调用的 id(同一份答复的去重键)
306
+ * @param body 正文
307
+ * @returns 动作结果
308
+ */
309
+ async function steerIntoRun(sessionId: string, callId: string, body: string): Promise<PlanActionResult> {
310
+ const previous = steeredReplies.get(sessionId)
311
+ if (previous && previous.callId === callId && previous.text === body) return ok()
312
+ if (!host) return fail('计划动作桥未就绪')
313
+ let result: PlanActionResult
314
+ try {
315
+ result = await host.steerTask(sessionId, body)
316
+ } catch (error) {
317
+ return fail('送进当前回合失败:' + messageOf(error))
318
+ }
319
+ if (result.ok) steeredReplies.set(sessionId, { callId, text: body })
320
+ return result
321
+ }
322
+
269
323
  /**
270
324
  * 回答官方 plan-review:批准 = 选批准标签;不批准 = 选继续规划标签(若官方提供)。
271
325
  * @author ddj 2026年11月21号
@@ -282,6 +336,7 @@ export async function answerPlanReview(sessionId: string, approve: boolean): Pro
282
336
  if (!label) return fail(approve ? '该审批没有可用的批准选项' : '官方审批没有「继续规划」选项,请在对话中要求修改')
283
337
  try {
284
338
  await live.pending.answer({ answers: [{ id: live.labels.questionId, selected: [label] }] })
339
+ steeredReplies.delete(sessionId)
285
340
  return ok()
286
341
  } catch (error) {
287
342
  return fail('提交审批失败:' + messageOf(error))
@@ -296,7 +351,9 @@ export async function answerPlanReview(sessionId: string, approve: boolean): Pro
296
351
  return fail('当前 DSH 不支持在插件内作答,请在对话审批卡片中操作')
297
352
  }
298
353
  try {
299
- return unwrap(await questions.answer(sessionId, review.callId, answer))
354
+ const result = unwrap(await questions.answer(sessionId, review.callId, answer))
355
+ if (result.ok) steeredReplies.delete(sessionId)
356
+ return result
300
357
  } catch (error) {
301
358
  return fail('提交审批失败:' + messageOf(error))
302
359
  }
@@ -323,27 +380,44 @@ export async function exitPlanMode(sessionId: string): Promise<PlanActionResult>
323
380
  }
324
381
 
325
382
  /**
326
- * 发送计划页答复给 agent:有待审批时先提交「继续规划」,再发送反馈正文。
383
+ * 把手填正文交给 agent,并同时结算官方审批(页面「回复」/「回复并执行」)。
384
+ *
385
+ * 有待审批卡片时:先把正文 steer 进当前回合,再结算审批(approve=true 选批准标签,
386
+ * false 选「继续规划」)。宿主在审批一结算就把工具结果交给模型并开始下一步,
387
+ * 所以顺序不能反——反过来时答复只能排到下一回合,表现为「agent 先执行,答复晚一步才送到」。
388
+ * steer 失败就不动审批(保持可重试),避免出现「批了但答复没送到」的半截状态。
327
389
  * @author ddj 2026年11月21号
390
+ * @author ddj 2026年11月24号(批准前先把正文送进当前回合;新增 approve 参数)
328
391
  * @param sessionId 会话 id
329
- * @param text 答复 markdown
330
- * @returns 动作结果(失败带原因,答复文本不丢)
392
+ * @param text 答复 / 指令 markdown
393
+ * @param approve true 结算为「同意执行」,false 结算为「继续规划」;没有待审批时只发消息
394
+ * @returns 动作结果(失败带原因,正文不丢)
331
395
  */
332
- export async function submitPlanResponse(sessionId: string, text: string): Promise<PlanActionResult> {
396
+ export async function submitPlanResponse(sessionId: string, text: string, approve = true): Promise<PlanActionResult> {
333
397
  if (!host) return fail('计划动作桥未就绪')
334
398
  if (!sessionId) return fail('当前没有活动会话')
335
399
  const body = String(text ?? '').trim()
336
- if (!body) return fail('答复为空:先在页面里作答再点「回复」')
337
- // 有待审批卡片:先结算为「同意执行」,再把答复作为用户消息送出;失败则不发,避免半截状态。
338
- if (readPendingReview(sessionId)) {
339
- const approved = await answerPlanReview(sessionId, true)
340
- if (!approved.ok) return fail('先同意执行失败,答复未发送:' + String(approved.error ?? ''))
400
+ if (!body) return fail(approve ? '答复为空:先在页面里作答再点「回复」' : '指令为空')
401
+ const review = readPendingReview(sessionId)
402
+ if (!review) {
403
+ try {
404
+ return await host.sendTask(sessionId, body)
405
+ } catch (error) {
406
+ return fail('发送失败:' + messageOf(error))
407
+ }
341
408
  }
342
- try {
343
- return await host.sendTask(sessionId, body)
344
- } catch (error) {
345
- return fail('发送失败:' + messageOf(error))
409
+ const bodyLabel = approve ? '答复' : '指令'
410
+ const steered = await steerIntoRun(sessionId, review.callId, body)
411
+ if (!steered.ok) {
412
+ return fail(bodyLabel + '没送进当前回合,审批保持待处理:' + String(steered.error ?? '') + '。可点「填入对话输入框」手动发送')
346
413
  }
414
+ const settled = await answerPlanReview(sessionId, approve)
415
+ if (!settled.ok) {
416
+ const settleLabel = approve ? '批准' : '「继续规划」'
417
+ return fail(bodyLabel + '已送进当前回合,但' + settleLabel + '失败:' + String(settled.error ?? '')
418
+ + '。点页签的「' + (approve ? '同意执行' : '继续规划') + '」重试即可,' + bodyLabel + '不会重复发送')
419
+ }
420
+ return ok()
347
421
  }
348
422
 
349
423
  /**
@@ -95,7 +95,7 @@ const BRIDGE_SCRIPT = [
95
95
  ' const copy = Array.from(footer.querySelectorAll("button")).find((btn) => /copy response|复制答复/i.test(btn.textContent || ""))',
96
96
  ' footer.insertBefore(reply, copy || footer.firstChild)',
97
97
  ' const hint = sheet.querySelector("p.hint")',
98
- ' if (hint) hint.textContent = reviewPending ? "点「回复并执行」= 同意计划并把答复发给 agent;要修改请先在页签点「继续规划」。" : "点「回复」直接发送给 agent;也可以复制后手动粘贴。"',
98
+ ' if (hint) hint.textContent = reviewPending ? "点「回复并执行」= 把答复和批准一起交给 agent(同一步读到);要改计划请先点页签「继续规划」。" : "点「回复」直接发送给 agent;也可以复制后手动粘贴。"',
99
99
  ' }',
100
100
  ' }',
101
101
  ' try { new MutationObserver(() => { try { hookSheet() } catch (error) { /* 忽略 */ } }).observe(document.body || document.documentElement, { childList: true, subtree: true }) } catch (error) { /* 无 MutationObserver */ }',
@@ -109,7 +109,7 @@ const BRIDGE_SCRIPT = [
109
109
  ' const reply = Array.from(sheet.querySelectorAll("footer button")).find((btn) => /回复|发送中|已发送|发送失败/.test(btn.textContent || ""))',
110
110
  ' if (reply && !reply.disabled) reply.textContent = reviewPending ? "回复并执行" : "回复"',
111
111
  ' const hint = sheet.querySelector("p.hint")',
112
- ' if (hint && !/发送失败/.test(hint.textContent || "")) hint.textContent = reviewPending ? "点「回复并执行」= 同意计划并把答复发给 agent;要修改请先在页签点「继续规划」。" : "点「回复」直接发送给 agent;也可以复制后手动粘贴。"',
112
+ ' if (hint && !/发送失败/.test(hint.textContent || "")) hint.textContent = reviewPending ? "点「回复并执行」= 把答复和批准一起交给 agent(同一步读到);要改计划请先点页签「继续规划」。" : "点「回复」直接发送给 agent;也可以复制后手动粘贴。"',
113
113
  ' }',
114
114
  ' return',
115
115
  ' }',
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import { cwdOfSession } from './store.js'
12
12
  import { resolveScope } from './registry.js'
13
13
  import { trackPendingCover } from './pendingCompat.js'
14
14
  import { closeArchiveDbs } from './archiveDb.js'
15
+ import { startArchiveSweep } from './archivePurge.js'
15
16
  import { handleRpc, integrationBaseUrlOf } from './rpc.js'
16
17
  import { newSearcher } from './search/orchestrator.js'
17
18
  import { newContentSearcher } from './search/content.js'
@@ -94,6 +95,8 @@ function attachRuntime(ctx: Ctx, runtime: Runtime): { external: ReturnType<typeo
94
95
  settings: () => runtime.settings.external(),
95
96
  record: recordPendingWrite,
96
97
  })
98
+ // 归档库每日清理:保留期 + 每文件上限,独立于会话存续
99
+ const sweep = startArchiveSweep()
97
100
  /**
98
101
  * @author ddj 2026年11月24号
99
102
  * @description: 任一工具调用期间都是 agent 写入窗口:bash / python 写盘落在窗口内时归属 agent。
@@ -141,6 +144,7 @@ function attachRuntime(ctx: Ctx, runtime: Runtime): { external: ReturnType<typeo
141
144
  evidence.dispose()
142
145
  pending.dispose()
143
146
  external.dispose()
147
+ sweep.dispose()
144
148
  windows.dispose()
145
149
  runtime.fileVersions.dispose()
146
150
  closeArchiveDbs()
@@ -7,13 +7,15 @@
7
7
  * MAX_BATCH 个文件、MAX_FLUSH_BYTES 字节,其余留到下一轮。批量按**入队顺序**处理,不按 mtime:
8
8
  * 同一毫秒内的多次写入 mtime 相同,用它排序反而可能造出倒序 diff。
9
9
  * - 判定顺序固定:已知内容未变 → 跳过;插件自写窗口 → 跳过;编辑器保存窗口 → 只推进基线;
10
- * 版本库说干净 → 跳过或标成版本库同步;其余按窗口判定归属后落库。绝不按时间戳猜重复。
10
+ * 版本库说干净 → 跳过或标成版本库同步;拿不到版本库状态且是首次见到的路径 → 必须自带 mtime 证据
11
+ * (文件确实在监听开始之后被写过),否则只记缺口不建档;其余按窗口判定归属后落库。
12
+ * 绝不按时间戳猜重复,也绝不把「被读过」当成「被改过」。
11
13
  * - 递归监听不可用(Linux)时降级为逐子目录非递归监听;仍不可用就只靠补扫,并把原因写进缺口。
12
14
  * - 读盘一律走待审采集的严格 UTF-8 往返:二进制、GBK 等无法字节往返的内容不落记录(记缺口),
13
15
  * 绝不因为"分析"而改写任何字节。
14
16
  * 作者 ddj 2026-11-24
15
17
  */
16
- import { readdirSync, watch } from 'node:fs'
18
+ import { readdirSync, statSync, watch } from 'node:fs'
17
19
  import type { FSWatcher } from 'node:fs'
18
20
  import { join, resolve } from 'node:path'
19
21
  import type { Ctx } from '../store.js'
@@ -51,6 +53,12 @@ export const SEEN_MAX = 5000
51
53
  export const ALIGN_INTERVAL_MS = 10 * 60_000
52
54
  /** 版本库写命令之后推迟多久补扫:等命令输出落盘、索引失效完成。 */
53
55
  export const ALIGN_AFTER_VCS_MS = 1500
56
+ /** 每个工作区最多记住多少条「已上报过的缺口」,防止事件风暴把去重表撑大。 */
57
+ export const GAP_KEY_MAX = 500
58
+ /** 「版本库状态不可用」这条诊断的最短间隔:同一工作区 5 分钟只报一次。 */
59
+ export const STATUS_NOTE_MIN_MS = 5 * 60_000
60
+ /** mtime 证据的时钟容差:监听开始前这段时间内写过的文件也算「刚被写过」。 */
61
+ export const WATCH_SKEW_MS = 2000
54
62
 
55
63
  /** 会改动工作副本的版本库 RPC:只有这些方法之后才值得补扫。 */
56
64
  export const VCS_WRITE_METHODS = new Set([
@@ -63,7 +71,11 @@ export const VCS_WRITE_TOOLS = new Set([
63
71
  'svn_propset', 'svn_propdel', 'svn_changelist', 'remote_ssh_write',
64
72
  ])
65
73
 
66
- /** 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。 */
74
+ /**
75
+ * 额外忽略的目录名(在搜索排除项之外,按原样大小写敏感匹配,口径与 EXCLUDES 一致)。
76
+ * 只收版本库元数据、Unity 缓存与构建产物:第三方与代码生成目录不在忽略之列,
77
+ * 它们的改动靠「mtime 证据 + 版本库状态」两道闸门拦,而不是按目录名一刀切。
78
+ */
67
79
  export const EXTRA_IGNORE_SEGMENTS = ['.svn', '.hg', '.p4config', 'Library', 'Temp', 'obj', 'Logs']
68
80
 
69
81
  /** 忽略集合:目录段 + 文件名模式。 */
@@ -127,6 +139,8 @@ export interface ExternalCaptureDeps {
127
139
  status?(cwd: string, sessionId: string): Promise<VcsStatus | null>
128
140
  /** 覆盖补扫执行(测试注入);缺省调用 alignInWorkspace。 */
129
141
  align?(cwd: string, sessionId: string): Promise<void>
142
+ /** 覆盖 mtime 读取(测试注入);缺省 statSync。拿不到返回 undefined。 */
143
+ mtime?(cwd: string, absolute: string): number | undefined
130
144
  now?(): number
131
145
  }
132
146
 
@@ -164,6 +178,12 @@ interface Workspace {
164
178
  alignTimer: ReturnType<typeof setTimeout> | null
165
179
  /** 延后补扫的定时器(版本库命令后/手动按钮,同一工作区合并一次)。 */
166
180
  requestTimer: ReturnType<typeof setTimeout> | null
181
+ /** 本次监听的起始时刻:文件 mtime 不比它新,就不是「刚被写过」。 */
182
+ startedAt: number
183
+ /** 已上报过的缺口键(同路径/同原因只报一次)。 */
184
+ gapKeys: Set<string>
185
+ /** 上次把「版本库状态不可用」写进缺口的时刻。 */
186
+ statusNoteAt: number
167
187
  }
168
188
 
169
189
  // --endregion
@@ -198,6 +218,7 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
198
218
  cwd: String(cwd), sessionId, watchers: [], dirty: new Map(), seen: new Map(),
199
219
  timer: null, firstAt: 0, flushing: false, again: false, degraded: '',
200
220
  statusAt: 0, status: undefined, alignedAt: 0, alignTimer: null, requestTimer: null,
221
+ startedAt: 0, gapKeys: new Set(), statusNoteAt: 0,
201
222
  }
202
223
  spaces.set(key, created)
203
224
  return created
@@ -237,6 +258,7 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
237
258
  */
238
259
  function startWatch(space: Workspace): void {
239
260
  if (space.watchers.length || stopped) return
261
+ space.startedAt = now()
240
262
  try {
241
263
  const watcher = watch(space.cwd, { recursive: true, persistent: false }, (_event, name) => onEvent(space, space.cwd, name))
242
264
  // EventEmitter 的 'error' 无监听者时抛出未捕获异常,必须挂处理器
@@ -323,10 +345,77 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
323
345
  return space.status
324
346
  }
325
347
  const scope = vcsScopeOf(deps.ctx, space.cwd, space.sessionId)
326
- space.status = scope ? await vcsStatus(scope.shell, space.cwd) : null
348
+ if (!scope) {
349
+ noteStatusOnce(space, '没有 shell 能力,版本库状态不可用')
350
+ space.status = null
351
+ return space.status
352
+ }
353
+ space.status = await vcsStatus(scope.shell, space.cwd, (reason) => noteStatusOnce(space, reason))
327
354
  return space.status
328
355
  }
329
356
 
357
+ /**
358
+ * @private
359
+ * @author ddj 2026-11-24
360
+ * @description: 读文件修改时间(测试可注入);读不到返回 undefined。
361
+ * @param space 工作区状态
362
+ * @param absolute 绝对路径
363
+ * @returns 毫秒时间戳或 undefined
364
+ */
365
+ function mtimeOf(space: Workspace, absolute: string): number | undefined {
366
+ if (deps.mtime) return deps.mtime(space.cwd, absolute)
367
+ try { return statSync(absolute).mtimeMs } catch { return undefined }
368
+ }
369
+
370
+ /**
371
+ * @private
372
+ * @author ddj 2026-11-24
373
+ * @description: 判断文件是否在本次监听开始之后被写过:这是「拿不到版本库状态」时唯一的外部证据。
374
+ * @param space 工作区状态
375
+ * @param absolute 绝对路径
376
+ * @returns 刚被写过返回 true
377
+ */
378
+ function recentlyWritten(space: Workspace, absolute: string): boolean {
379
+ if (!space.startedAt) return false
380
+ const mtime = mtimeOf(space, absolute)
381
+ return mtime !== undefined && mtime >= space.startedAt - WATCH_SKEW_MS
382
+ }
383
+
384
+ /**
385
+ * @private
386
+ * @author ddj 2026-11-24
387
+ * @description: 同一条缺口只上报一次;去重表满了就丢最早的键,保证内存有界。
388
+ * @param space 工作区状态
389
+ * @param key 去重键
390
+ * @param absolute 出问题的路径
391
+ * @param message 原因
392
+ * @returns 无
393
+ */
394
+ function noteGapOnce(space: Workspace, key: string, absolute: string, message: string): void {
395
+ if (space.gapKeys.has(key)) return
396
+ if (space.gapKeys.size >= GAP_KEY_MAX) {
397
+ const oldest = space.gapKeys.values().next().value
398
+ if (oldest !== undefined) space.gapKeys.delete(oldest)
399
+ }
400
+ space.gapKeys.add(key)
401
+ noteCaptureGap(space.cwd, space.sessionId, absolute, message)
402
+ }
403
+
404
+ /**
405
+ * @private
406
+ * @author ddj 2026-11-24
407
+ * @description: 「版本库状态不可用」按工作区节流上报,让面板能说清为什么没拦住噪声。
408
+ * @param space 工作区状态
409
+ * @param reason 失败原因(命令回执头 200 字)
410
+ * @returns 无
411
+ */
412
+ function noteStatusOnce(space: Workspace, reason: string): void {
413
+ const at = now()
414
+ if (at - space.statusNoteAt < STATUS_NOTE_MIN_MS) return
415
+ space.statusNoteAt = at
416
+ noteCaptureGap(space.cwd, space.sessionId, space.cwd, '版本库状态不可用:' + reason.slice(0, 200))
417
+ }
418
+
330
419
  /**
331
420
  * @private
332
421
  * @description: 处理一个路径:判定链见文件头注释。
@@ -369,6 +458,13 @@ export function installExternalCapture(deps: ExternalCaptureDeps): ExternalCaptu
369
458
  deps.record(writeOf(space, absolute, stored.entry.newText, content, at, 'vcs', 'vcs', 'known'))
370
459
  return true
371
460
  }
461
+ // 拿不到版本库状态时,首次见到的路径必须自带证据:文件真的在监听开始之后被写过。
462
+ // 否则事件多半只是读取/属性变化(整树扫描、索引器、杀软),按「整文件新增」建档会刷出幽灵差异。
463
+ if (!status && !stored && !space.seen.has(key) && !recentlyWritten(space, absolute)) {
464
+ noteGapOnce(space, 'absent:' + key, absolute, '无版本库状态且文件未改动,未建档')
465
+ space.seen.set(key, content)
466
+ return false
467
+ }
372
468
 
373
469
  const before = await beforeOf(space, key, absolute, stored, status, content)
374
470
  if (before.text === null && content === null) {
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import type { DatabaseSync } from 'node:sqlite'
6
6
  import { activeReady, dbFor } from '../archiveDb.js'
7
+ import { log } from '../log.js'
7
8
  import type { PendingBaseKind, PendingLineage, PendingOrigin, PendingSource } from '../shared/pendingReview.js'
8
9
  import type { PendingEntry } from './kernel.js'
9
10
 
@@ -518,3 +519,89 @@ export function saveDecisions(cwd: string, records: KeepRecord[]): { id: string;
518
519
  throw error
519
520
  }
520
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
+ }
@@ -18,9 +18,10 @@ import type { PendingEntry } from './kernel.js'
18
18
  import type { PendingFlags, StoredEntry } from './persist.js'
19
19
  import type { KeepRecord } from './persist.js'
20
20
  import {
21
- dropEntry, earliestUndone, latestApplied, loadBlocks, loadEntries, pendingDb, pushHistory,
22
- readOp, saveBlocks, saveDecisions, saveEntry, setHistoryState, writeOp,
21
+ dropEntry, earliestUndone, latestApplied, loadBlocks, loadEntries, pendingDb, purgeEntries, pushHistory,
22
+ readOp, saveBlocks, saveDecisions, saveEntry, setHistoryState, vacuumEntries, writeOp,
23
23
  } from './persist.js'
24
+ import type { PurgeFilter, PurgeOutcome } from './persist.js'
24
25
 
25
26
  /**
26
27
  * @author ddj 2026年10月29号
@@ -603,6 +604,40 @@ export function removeEntry(cwd: string, id: string, revision: number): boolean
603
604
  return true
604
605
  }
605
606
 
607
+ /** 清库回执:命中、删除、保留条数,以及可选的 VACUUM 耗时。 */
608
+ export interface PendingPurgeOutcome extends PurgeOutcome {
609
+ /** VACUUM 耗时毫秒;dryRun 或未清理时为 undefined。 */
610
+ vacuumMs?: number
611
+ }
612
+
613
+ /** 清库默认口径:只清 watch 通道、空基线的条目——幽灵记录就长这样。 */
614
+ export const PURGE_DEFAULT_SOURCES = ['watch']
615
+ /** 清库默认基线口径:空基线(改前内容缺失)。 */
616
+ export const PURGE_DEFAULT_BASE_KINDS = ['absent']
617
+
618
+ /**
619
+ * @public
620
+ * @author ddj 2026-11-24
621
+ * @description: 清掉指定通道的待审条目(幽灵记录治理入口)。dryRun 只报数;
622
+ * 真删之后按需 VACUUM,把已删行占的页还给磁盘。
623
+ * @param cwd 工作区
624
+ * @param filter 筛选条件(缺省 watch + absent)
625
+ * @param options dryRun 只数不删;vacuum 删除后是否回收
626
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
627
+ */
628
+ export function purgePending(
629
+ cwd: string, filter: PurgeFilter = {}, options: { dryRun?: boolean; vacuum?: boolean } = {},
630
+ ): PendingPurgeOutcome {
631
+ const scoped: PurgeFilter = {
632
+ sources: filter.sources && filter.sources.length ? filter.sources : PURGE_DEFAULT_SOURCES,
633
+ baseKinds: filter.baseKinds && filter.baseKinds.length ? filter.baseKinds : PURGE_DEFAULT_BASE_KINDS,
634
+ before: filter.before,
635
+ }
636
+ const outcome = purgeEntries(cwd, scoped, options.dryRun === true)
637
+ if (options.dryRun || !outcome.removed || !options.vacuum) return outcome
638
+ return { ...outcome, vacuumMs: vacuumEntries(cwd) }
639
+ }
640
+
606
641
  /**
607
642
  * @author ddj 2026年10月29号
608
643
  * @description: 取错误码用于拒绝原因,没有则回落到消息文本。
@@ -390,12 +390,22 @@ async function runCommand(
390
390
  * 非 git/svn(含 Perforce 与无版本库)一律返回 null,由调用方降级为「只对齐已记录条目」。
391
391
  * @param shell shell 能力
392
392
  * @param cwd 工作区
393
+ * @param onFailure 失败原因回调(可选):调用方用它把「为什么没有状态」写进采集缺口
393
394
  * @returns 状态集合或 null
394
395
  */
395
- export async function vcsStatus(shell: ShellLike, cwd: string): Promise<VcsStatus | null> {
396
+ export async function vcsStatus(
397
+ shell: ShellLike, cwd: string, onFailure?: (reason: string) => void,
398
+ ): Promise<VcsStatus | null> {
396
399
  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)
400
+ if (!detected) {
401
+ onFailure?.('不是 git/svn 工作副本')
402
+ return null
403
+ }
404
+ if (detected.kind === 'p4') {
405
+ onFailure?.('Perforce 工作副本不支持状态探测')
406
+ return null
407
+ }
408
+ return detected.kind === 'git' ? gitStatus(shell, detected.root, onFailure) : svnStatus(shell, detected.root, onFailure)
399
409
  }
400
410
 
401
411
  /**
@@ -404,11 +414,15 @@ export async function vcsStatus(shell: ShellLike, cwd: string): Promise<VcsStatu
404
414
  * @description: git 状态:一条 status 命令解析出改动集合。
405
415
  * @param shell shell 能力
406
416
  * @param root 仓库根
417
+ * @param onFailure 失败原因回调(可选)
407
418
  * @returns 状态集合或 null(命令失败)
408
419
  */
409
- async function gitStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
420
+ async function gitStatus(shell: ShellLike, root: string, onFailure?: (reason: string) => void): Promise<VcsStatus | null> {
410
421
  const status = await runCommand(shell, 'git -c status.renames=false status --porcelain=v1 -z --untracked-files=all', root)
411
- if (!status.ok) return null
422
+ if (!status.ok) {
423
+ onFailure?.('git status 失败:' + status.stderr.slice(0, 200))
424
+ return null
425
+ }
412
426
  const entries = new Map<string, VcsEntry>()
413
427
  for (const entry of parseGitStatus(status.stdout)) {
414
428
  const absolute = join(root, ...entry.path.split(GIT_SEPARATOR))
@@ -424,11 +438,15 @@ async function gitStatus(shell: ShellLike, root: string): Promise<VcsStatus | nu
424
438
  * @description: svn 状态:一条 status --xml 解析出改动集合。
425
439
  * @param shell shell 能力
426
440
  * @param root 工作副本根
441
+ * @param onFailure 失败原因回调(可选)
427
442
  * @returns 状态集合或 null(命令失败)
428
443
  */
429
- async function svnStatus(shell: ShellLike, root: string): Promise<VcsStatus | null> {
444
+ async function svnStatus(shell: ShellLike, root: string, onFailure?: (reason: string) => void): Promise<VcsStatus | null> {
430
445
  const status = await runCommand(shell, 'svn status --xml', root)
431
- if (!status.ok) return null
446
+ if (!status.ok) {
447
+ onFailure?.('svn status 失败:' + status.stderr.slice(0, 200))
448
+ return null
449
+ }
432
450
  const entries = new Map<string, VcsEntry>()
433
451
  for (const entry of parseSvnStatus(status.stdout)) {
434
452
  const absolute = resolve(root, entry.path)
package/src/pendingRpc.ts CHANGED
@@ -7,7 +7,7 @@ import { bucketOf } from './registry.js'
7
7
  import { readText } from './pending/capture.js'
8
8
  import { pendingRawId, setPendingCovers, trackPendingCover } from './pendingCompat.js'
9
9
  import { loadEntries, pendingVersion, saveEntry } from './pending/persist.js'
10
- import { applyDecide, importFromVcs, itemOf, loadDetail, loadPage, recordWrite, refreshed, removeEntry, undoDecide } from './pending/store.js'
10
+ import { applyDecide, importFromVcs, itemOf, loadDetail, loadPage, purgePending, recordWrite, refreshed, removeEntry, undoDecide } from './pending/store.js'
11
11
  import { alignInWorkspace } from './pending/externalAlign.js'
12
12
  import type { ShellLike } from './pending/vcs.js'
13
13
  import type { Ctx } from './store.js'
@@ -205,6 +205,24 @@ function refreshHandlers(kit: ScopeKit): Partial<RpcHandlerMap> {
205
205
  setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path))
206
206
  return { ok: true, imported: outcome.imported, changed: outcome.changed, gaps: outcome.gaps }
207
207
  },
208
+ /**
209
+ * @author ddj 2026-11-24
210
+ * @description: 清掉指定通道的幽灵记录。dryRun 只报数;真删后按需 VACUUM,
211
+ * 并重建「待审接管」集合,避免旧路径继续顶掉官方行。
212
+ * @param args 清理请求
213
+ * @returns 命中、删除、保留条数与 VACUUM 耗时
214
+ */
215
+ 'edrv.pending.purge': async (args) => {
216
+ const cwd = await kit.write(args.sessionId)
217
+ const outcome = purgePending(cwd, {
218
+ sources: args.sources,
219
+ baseKinds: args.baseKinds,
220
+ before: args.before,
221
+ }, { dryRun: args.dryRun === true, vacuum: true })
222
+ const page = loadPage(cwd, args.sessionId)
223
+ setPendingCovers(cwd, args.sessionId, page.items.map((item) => item.path))
224
+ return { ok: true, matched: outcome.matched, removed: outcome.removed, kept: outcome.kept, vacuumMs: outcome.vacuumMs }
225
+ },
208
226
  }
209
227
  }
210
228